partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
GramFuzzer.add_to_cat_group
|
Associate the provided rule definition name ``def_name`` with the
category group ``cat_group`` in the category ``cat``.
:param str cat: The category the rule definition was declared in
:param str cat_group: The group within the category the rule belongs to
:param str def_name: The name of the rule definition
|
gramfuzz/gramfuzz/__init__.py
|
def add_to_cat_group(self, cat, cat_group, def_name):
"""Associate the provided rule definition name ``def_name`` with the
category group ``cat_group`` in the category ``cat``.
:param str cat: The category the rule definition was declared in
:param str cat_group: The group within the category the rule belongs to
:param str def_name: The name of the rule definition
"""
self.cat_groups.setdefault(cat, {}).setdefault(cat_group, deque()).append(def_name)
|
def add_to_cat_group(self, cat, cat_group, def_name):
"""Associate the provided rule definition name ``def_name`` with the
category group ``cat_group`` in the category ``cat``.
:param str cat: The category the rule definition was declared in
:param str cat_group: The group within the category the rule belongs to
:param str def_name: The name of the rule definition
"""
self.cat_groups.setdefault(cat, {}).setdefault(cat_group, deque()).append(def_name)
|
[
"Associate",
"the",
"provided",
"rule",
"definition",
"name",
"def_name",
"with",
"the",
"category",
"group",
"cat_group",
"in",
"the",
"category",
"cat",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L350-L358
|
[
"def",
"add_to_cat_group",
"(",
"self",
",",
"cat",
",",
"cat_group",
",",
"def_name",
")",
":",
"self",
".",
"cat_groups",
".",
"setdefault",
"(",
"cat",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"cat_group",
",",
"deque",
"(",
")",
")",
".",
"append",
"(",
"def_name",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.get_ref
|
Return one of the rules in the category ``cat`` with the name
``refname``. If multiple rule defintions exist for the defintion name
``refname``, use :any:`gramfuzz.rand` to choose a rule at random.
:param str cat: The category to look for the rule in.
:param str refname: The name of the rule definition. If the rule definition's name is
``"*"``, then a rule name will be chosen at random from within the category ``cat``.
:returns: gramfuzz.fields.Def
|
gramfuzz/gramfuzz/__init__.py
|
def get_ref(self, cat, refname):
"""Return one of the rules in the category ``cat`` with the name
``refname``. If multiple rule defintions exist for the defintion name
``refname``, use :any:`gramfuzz.rand` to choose a rule at random.
:param str cat: The category to look for the rule in.
:param str refname: The name of the rule definition. If the rule definition's name is
``"*"``, then a rule name will be chosen at random from within the category ``cat``.
:returns: gramfuzz.fields.Def
"""
if cat not in self.defs:
raise errors.GramFuzzError("referenced definition category ({!r}) not defined".format(cat))
if refname == "*":
refname = rand.choice(self.defs[cat].keys())
if refname not in self.defs[cat]:
raise errors.GramFuzzError("referenced definition ({!r}) not defined".format(refname))
return rand.choice(self.defs[cat][refname])
|
def get_ref(self, cat, refname):
"""Return one of the rules in the category ``cat`` with the name
``refname``. If multiple rule defintions exist for the defintion name
``refname``, use :any:`gramfuzz.rand` to choose a rule at random.
:param str cat: The category to look for the rule in.
:param str refname: The name of the rule definition. If the rule definition's name is
``"*"``, then a rule name will be chosen at random from within the category ``cat``.
:returns: gramfuzz.fields.Def
"""
if cat not in self.defs:
raise errors.GramFuzzError("referenced definition category ({!r}) not defined".format(cat))
if refname == "*":
refname = rand.choice(self.defs[cat].keys())
if refname not in self.defs[cat]:
raise errors.GramFuzzError("referenced definition ({!r}) not defined".format(refname))
return rand.choice(self.defs[cat][refname])
|
[
"Return",
"one",
"of",
"the",
"rules",
"in",
"the",
"category",
"cat",
"with",
"the",
"name",
"refname",
".",
"If",
"multiple",
"rule",
"defintions",
"exist",
"for",
"the",
"defintion",
"name",
"refname",
"use",
":",
"any",
":",
"gramfuzz",
".",
"rand",
"to",
"choose",
"a",
"rule",
"at",
"random",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L360-L379
|
[
"def",
"get_ref",
"(",
"self",
",",
"cat",
",",
"refname",
")",
":",
"if",
"cat",
"not",
"in",
"self",
".",
"defs",
":",
"raise",
"errors",
".",
"GramFuzzError",
"(",
"\"referenced definition category ({!r}) not defined\"",
".",
"format",
"(",
"cat",
")",
")",
"if",
"refname",
"==",
"\"*\"",
":",
"refname",
"=",
"rand",
".",
"choice",
"(",
"self",
".",
"defs",
"[",
"cat",
"]",
".",
"keys",
"(",
")",
")",
"if",
"refname",
"not",
"in",
"self",
".",
"defs",
"[",
"cat",
"]",
":",
"raise",
"errors",
".",
"GramFuzzError",
"(",
"\"referenced definition ({!r}) not defined\"",
".",
"format",
"(",
"refname",
")",
")",
"return",
"rand",
".",
"choice",
"(",
"self",
".",
"defs",
"[",
"cat",
"]",
"[",
"refname",
"]",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.gen
|
Generate ``num`` rules from category ``cat``, optionally specifying
preferred category groups ``preferred`` that should be preferred at
probability ``preferred_ratio`` over other randomly-chosen rule definitions.
:param int num: The number of rules to generate
:param str cat: The name of the category to generate ``num`` rules from
:param str cat_group: The category group (ie python file) to generate rules from. This
was added specifically to make it easier to generate data based on the name
of the file the grammar was defined in, and is intended to work with the
``TOP_CAT`` values that may be defined in a loaded grammar file.
:param list preferred: A list of preferred category groups to generate rules from
:param float preferred_ratio: The percent probability that the preferred
groups will be chosen over randomly choosen rule definitions from category ``cat``.
:param int max_recursion: The maximum amount to allow references to recurse
:param bool auto_process: Whether rules should be automatically pruned and
shortest reference paths determined. See :any:`gramfuzz.GramFuzzer.preprocess_rules`
for what would automatically be done.
|
gramfuzz/gramfuzz/__init__.py
|
def gen(self, num, cat=None, cat_group=None, preferred=None, preferred_ratio=0.5, max_recursion=None, auto_process=True):
"""Generate ``num`` rules from category ``cat``, optionally specifying
preferred category groups ``preferred`` that should be preferred at
probability ``preferred_ratio`` over other randomly-chosen rule definitions.
:param int num: The number of rules to generate
:param str cat: The name of the category to generate ``num`` rules from
:param str cat_group: The category group (ie python file) to generate rules from. This
was added specifically to make it easier to generate data based on the name
of the file the grammar was defined in, and is intended to work with the
``TOP_CAT`` values that may be defined in a loaded grammar file.
:param list preferred: A list of preferred category groups to generate rules from
:param float preferred_ratio: The percent probability that the preferred
groups will be chosen over randomly choosen rule definitions from category ``cat``.
:param int max_recursion: The maximum amount to allow references to recurse
:param bool auto_process: Whether rules should be automatically pruned and
shortest reference paths determined. See :any:`gramfuzz.GramFuzzer.preprocess_rules`
for what would automatically be done.
"""
import gramfuzz.fields
gramfuzz.fields.REF_LEVEL = 1
if cat is None and cat_group is None:
raise gramfuzz.errors.GramFuzzError("cat and cat_group are None, one must be set")
if cat is None and cat_group is not None:
if cat_group not in self.cat_group_defaults:
raise gramfuzz.errors.GramFuzzError(
"cat_group {!r} did not define a TOP_CAT variable"
)
cat = self.cat_group_defaults[cat_group]
if not isinstance(cat, basestring):
raise gramfuzz.errors.GramFuzzError(
"cat_group {!r}'s TOP_CAT variable was not a string"
)
if auto_process and self._rules_processed == False:
self.preprocess_rules()
if max_recursion is not None:
self.set_max_recursion(max_recursion)
if preferred is None:
preferred = []
res = deque()
cat_defs = self.defs[cat]
# optimizations
_res_append = res.append
_res_extend = res.extend
_choice = rand.choice
_maybe = rand.maybe
_val = utils.val
keys = self.defs[cat].keys()
self._last_pref_keys = self._get_pref_keys(cat, preferred)
# be sure to set this *after* fetching the pref keys (above^)
self._last_prefs = preferred
total_errors = deque()
total_gend = 0
while total_gend < num:
# use a rule definition from one of the preferred category
# groups
if len(self._last_pref_keys) > 0 and _maybe(preferred_ratio):
rand_key = _choice(self._last_pref_keys)
if rand_key not in cat_defs:
# TODO this means it was removed / pruned b/c it was unreachable??
# TODO look into this more
rand_key = _choice(list(keys))
# else just choose a key at random from the category
else:
rand_key = _choice(list(keys))
# pruning failed, this rule is not defined/reachable
if rand_key not in cat_defs:
continue
v = _choice(cat_defs[rand_key])
# not used directly by GramFuzzer, but could be useful
# to subclasses of GramFuzzer
info = {}
pre = deque()
self.pre_revert(info)
val_res = None
try:
val_res = _val(v, pre)
except errors.GramFuzzError as e:
raise
#total_errors.append(e)
#self.revert(info)
#continue
except RuntimeError as e:
print("RUNTIME ERROR")
self.revert(info)
continue
if val_res is not None:
_res_extend(pre)
_res_append(val_res)
total_gend += 1
self.post_revert(cat, res, total_gend, num, info)
return res
|
def gen(self, num, cat=None, cat_group=None, preferred=None, preferred_ratio=0.5, max_recursion=None, auto_process=True):
"""Generate ``num`` rules from category ``cat``, optionally specifying
preferred category groups ``preferred`` that should be preferred at
probability ``preferred_ratio`` over other randomly-chosen rule definitions.
:param int num: The number of rules to generate
:param str cat: The name of the category to generate ``num`` rules from
:param str cat_group: The category group (ie python file) to generate rules from. This
was added specifically to make it easier to generate data based on the name
of the file the grammar was defined in, and is intended to work with the
``TOP_CAT`` values that may be defined in a loaded grammar file.
:param list preferred: A list of preferred category groups to generate rules from
:param float preferred_ratio: The percent probability that the preferred
groups will be chosen over randomly choosen rule definitions from category ``cat``.
:param int max_recursion: The maximum amount to allow references to recurse
:param bool auto_process: Whether rules should be automatically pruned and
shortest reference paths determined. See :any:`gramfuzz.GramFuzzer.preprocess_rules`
for what would automatically be done.
"""
import gramfuzz.fields
gramfuzz.fields.REF_LEVEL = 1
if cat is None and cat_group is None:
raise gramfuzz.errors.GramFuzzError("cat and cat_group are None, one must be set")
if cat is None and cat_group is not None:
if cat_group not in self.cat_group_defaults:
raise gramfuzz.errors.GramFuzzError(
"cat_group {!r} did not define a TOP_CAT variable"
)
cat = self.cat_group_defaults[cat_group]
if not isinstance(cat, basestring):
raise gramfuzz.errors.GramFuzzError(
"cat_group {!r}'s TOP_CAT variable was not a string"
)
if auto_process and self._rules_processed == False:
self.preprocess_rules()
if max_recursion is not None:
self.set_max_recursion(max_recursion)
if preferred is None:
preferred = []
res = deque()
cat_defs = self.defs[cat]
# optimizations
_res_append = res.append
_res_extend = res.extend
_choice = rand.choice
_maybe = rand.maybe
_val = utils.val
keys = self.defs[cat].keys()
self._last_pref_keys = self._get_pref_keys(cat, preferred)
# be sure to set this *after* fetching the pref keys (above^)
self._last_prefs = preferred
total_errors = deque()
total_gend = 0
while total_gend < num:
# use a rule definition from one of the preferred category
# groups
if len(self._last_pref_keys) > 0 and _maybe(preferred_ratio):
rand_key = _choice(self._last_pref_keys)
if rand_key not in cat_defs:
# TODO this means it was removed / pruned b/c it was unreachable??
# TODO look into this more
rand_key = _choice(list(keys))
# else just choose a key at random from the category
else:
rand_key = _choice(list(keys))
# pruning failed, this rule is not defined/reachable
if rand_key not in cat_defs:
continue
v = _choice(cat_defs[rand_key])
# not used directly by GramFuzzer, but could be useful
# to subclasses of GramFuzzer
info = {}
pre = deque()
self.pre_revert(info)
val_res = None
try:
val_res = _val(v, pre)
except errors.GramFuzzError as e:
raise
#total_errors.append(e)
#self.revert(info)
#continue
except RuntimeError as e:
print("RUNTIME ERROR")
self.revert(info)
continue
if val_res is not None:
_res_extend(pre)
_res_append(val_res)
total_gend += 1
self.post_revert(cat, res, total_gend, num, info)
return res
|
[
"Generate",
"num",
"rules",
"from",
"category",
"cat",
"optionally",
"specifying",
"preferred",
"category",
"groups",
"preferred",
"that",
"should",
"be",
"preferred",
"at",
"probability",
"preferred_ratio",
"over",
"other",
"randomly",
"-",
"chosen",
"rule",
"definitions",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L382-L492
|
[
"def",
"gen",
"(",
"self",
",",
"num",
",",
"cat",
"=",
"None",
",",
"cat_group",
"=",
"None",
",",
"preferred",
"=",
"None",
",",
"preferred_ratio",
"=",
"0.5",
",",
"max_recursion",
"=",
"None",
",",
"auto_process",
"=",
"True",
")",
":",
"import",
"gramfuzz",
".",
"fields",
"gramfuzz",
".",
"fields",
".",
"REF_LEVEL",
"=",
"1",
"if",
"cat",
"is",
"None",
"and",
"cat_group",
"is",
"None",
":",
"raise",
"gramfuzz",
".",
"errors",
".",
"GramFuzzError",
"(",
"\"cat and cat_group are None, one must be set\"",
")",
"if",
"cat",
"is",
"None",
"and",
"cat_group",
"is",
"not",
"None",
":",
"if",
"cat_group",
"not",
"in",
"self",
".",
"cat_group_defaults",
":",
"raise",
"gramfuzz",
".",
"errors",
".",
"GramFuzzError",
"(",
"\"cat_group {!r} did not define a TOP_CAT variable\"",
")",
"cat",
"=",
"self",
".",
"cat_group_defaults",
"[",
"cat_group",
"]",
"if",
"not",
"isinstance",
"(",
"cat",
",",
"basestring",
")",
":",
"raise",
"gramfuzz",
".",
"errors",
".",
"GramFuzzError",
"(",
"\"cat_group {!r}'s TOP_CAT variable was not a string\"",
")",
"if",
"auto_process",
"and",
"self",
".",
"_rules_processed",
"==",
"False",
":",
"self",
".",
"preprocess_rules",
"(",
")",
"if",
"max_recursion",
"is",
"not",
"None",
":",
"self",
".",
"set_max_recursion",
"(",
"max_recursion",
")",
"if",
"preferred",
"is",
"None",
":",
"preferred",
"=",
"[",
"]",
"res",
"=",
"deque",
"(",
")",
"cat_defs",
"=",
"self",
".",
"defs",
"[",
"cat",
"]",
"# optimizations",
"_res_append",
"=",
"res",
".",
"append",
"_res_extend",
"=",
"res",
".",
"extend",
"_choice",
"=",
"rand",
".",
"choice",
"_maybe",
"=",
"rand",
".",
"maybe",
"_val",
"=",
"utils",
".",
"val",
"keys",
"=",
"self",
".",
"defs",
"[",
"cat",
"]",
".",
"keys",
"(",
")",
"self",
".",
"_last_pref_keys",
"=",
"self",
".",
"_get_pref_keys",
"(",
"cat",
",",
"preferred",
")",
"# be sure to set this *after* fetching the pref keys (above^)",
"self",
".",
"_last_prefs",
"=",
"preferred",
"total_errors",
"=",
"deque",
"(",
")",
"total_gend",
"=",
"0",
"while",
"total_gend",
"<",
"num",
":",
"# use a rule definition from one of the preferred category",
"# groups",
"if",
"len",
"(",
"self",
".",
"_last_pref_keys",
")",
">",
"0",
"and",
"_maybe",
"(",
"preferred_ratio",
")",
":",
"rand_key",
"=",
"_choice",
"(",
"self",
".",
"_last_pref_keys",
")",
"if",
"rand_key",
"not",
"in",
"cat_defs",
":",
"# TODO this means it was removed / pruned b/c it was unreachable??",
"# TODO look into this more",
"rand_key",
"=",
"_choice",
"(",
"list",
"(",
"keys",
")",
")",
"# else just choose a key at random from the category",
"else",
":",
"rand_key",
"=",
"_choice",
"(",
"list",
"(",
"keys",
")",
")",
"# pruning failed, this rule is not defined/reachable",
"if",
"rand_key",
"not",
"in",
"cat_defs",
":",
"continue",
"v",
"=",
"_choice",
"(",
"cat_defs",
"[",
"rand_key",
"]",
")",
"# not used directly by GramFuzzer, but could be useful",
"# to subclasses of GramFuzzer",
"info",
"=",
"{",
"}",
"pre",
"=",
"deque",
"(",
")",
"self",
".",
"pre_revert",
"(",
"info",
")",
"val_res",
"=",
"None",
"try",
":",
"val_res",
"=",
"_val",
"(",
"v",
",",
"pre",
")",
"except",
"errors",
".",
"GramFuzzError",
"as",
"e",
":",
"raise",
"#total_errors.append(e)",
"#self.revert(info)",
"#continue",
"except",
"RuntimeError",
"as",
"e",
":",
"print",
"(",
"\"RUNTIME ERROR\"",
")",
"self",
".",
"revert",
"(",
"info",
")",
"continue",
"if",
"val_res",
"is",
"not",
"None",
":",
"_res_extend",
"(",
"pre",
")",
"_res_append",
"(",
"val_res",
")",
"total_gend",
"+=",
"1",
"self",
".",
"post_revert",
"(",
"cat",
",",
"res",
",",
"total_gend",
",",
"num",
",",
"info",
")",
"return",
"res"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.post_revert
|
Commit any staged rule definition changes (rule generation went
smoothly).
|
gramfuzz/gramfuzz/__init__.py
|
def post_revert(self, cat, res, total_num, num, info):
"""Commit any staged rule definition changes (rule generation went
smoothly).
"""
if self._staged_defs is None:
return
for cat,def_name,def_value in self._staged_defs:
self.defs.setdefault(cat, {}).setdefault(def_name, deque()).append(def_value)
self._staged_defs = None
|
def post_revert(self, cat, res, total_num, num, info):
"""Commit any staged rule definition changes (rule generation went
smoothly).
"""
if self._staged_defs is None:
return
for cat,def_name,def_value in self._staged_defs:
self.defs.setdefault(cat, {}).setdefault(def_name, deque()).append(def_value)
self._staged_defs = None
|
[
"Commit",
"any",
"staged",
"rule",
"definition",
"changes",
"(",
"rule",
"generation",
"went",
"smoothly",
")",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L499-L507
|
[
"def",
"post_revert",
"(",
"self",
",",
"cat",
",",
"res",
",",
"total_num",
",",
"num",
",",
"info",
")",
":",
"if",
"self",
".",
"_staged_defs",
"is",
"None",
":",
"return",
"for",
"cat",
",",
"def_name",
",",
"def_value",
"in",
"self",
".",
"_staged_defs",
":",
"self",
".",
"defs",
".",
"setdefault",
"(",
"cat",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"def_name",
",",
"deque",
"(",
")",
")",
".",
"append",
"(",
"def_value",
")",
"self",
".",
"_staged_defs",
"=",
"None"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFFactory.fuzz_elements
|
Fuzz all elements inside the object
|
pyjfuzz/core/pjf_factory.py
|
def fuzz_elements(self, element):
"""
Fuzz all elements inside the object
"""
try:
if type(element) == dict:
tmp_element = {}
for key in element:
if len(self.config.parameters) > 0:
if self.config.exclude_parameters:
fuzz = key not in self.config.parameters
else:
fuzz = key in self.config.parameters
else:
fuzz = True
if fuzz:
if type(element[key]) == dict:
tmp_element.update({key: self.fuzz_elements(element[key])})
elif type(element[key]) == list:
tmp_element.update({key: self.fuzz_elements(element[key])})
else:
tmp_element.update({key: self.mutator.fuzz(element[key])})
else:
tmp_element.update({key: self.fuzz_elements(element[key])})
element = tmp_element
del tmp_element
elif type(element) == list:
arr = []
for key in element:
if type(key) == dict:
arr.append(self.fuzz_elements(key))
elif type(key) == list:
arr.append(self.fuzz_elements(key))
else:
if len(self.config.parameters) <= 0:
arr.append(self.mutator.fuzz(key))
else:
arr.append(key)
element = arr
del arr
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
return element
|
def fuzz_elements(self, element):
"""
Fuzz all elements inside the object
"""
try:
if type(element) == dict:
tmp_element = {}
for key in element:
if len(self.config.parameters) > 0:
if self.config.exclude_parameters:
fuzz = key not in self.config.parameters
else:
fuzz = key in self.config.parameters
else:
fuzz = True
if fuzz:
if type(element[key]) == dict:
tmp_element.update({key: self.fuzz_elements(element[key])})
elif type(element[key]) == list:
tmp_element.update({key: self.fuzz_elements(element[key])})
else:
tmp_element.update({key: self.mutator.fuzz(element[key])})
else:
tmp_element.update({key: self.fuzz_elements(element[key])})
element = tmp_element
del tmp_element
elif type(element) == list:
arr = []
for key in element:
if type(key) == dict:
arr.append(self.fuzz_elements(key))
elif type(key) == list:
arr.append(self.fuzz_elements(key))
else:
if len(self.config.parameters) <= 0:
arr.append(self.mutator.fuzz(key))
else:
arr.append(key)
element = arr
del arr
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
return element
|
[
"Fuzz",
"all",
"elements",
"inside",
"the",
"object"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_factory.py#L129-L171
|
[
"def",
"fuzz_elements",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"if",
"type",
"(",
"element",
")",
"==",
"dict",
":",
"tmp_element",
"=",
"{",
"}",
"for",
"key",
"in",
"element",
":",
"if",
"len",
"(",
"self",
".",
"config",
".",
"parameters",
")",
">",
"0",
":",
"if",
"self",
".",
"config",
".",
"exclude_parameters",
":",
"fuzz",
"=",
"key",
"not",
"in",
"self",
".",
"config",
".",
"parameters",
"else",
":",
"fuzz",
"=",
"key",
"in",
"self",
".",
"config",
".",
"parameters",
"else",
":",
"fuzz",
"=",
"True",
"if",
"fuzz",
":",
"if",
"type",
"(",
"element",
"[",
"key",
"]",
")",
"==",
"dict",
":",
"tmp_element",
".",
"update",
"(",
"{",
"key",
":",
"self",
".",
"fuzz_elements",
"(",
"element",
"[",
"key",
"]",
")",
"}",
")",
"elif",
"type",
"(",
"element",
"[",
"key",
"]",
")",
"==",
"list",
":",
"tmp_element",
".",
"update",
"(",
"{",
"key",
":",
"self",
".",
"fuzz_elements",
"(",
"element",
"[",
"key",
"]",
")",
"}",
")",
"else",
":",
"tmp_element",
".",
"update",
"(",
"{",
"key",
":",
"self",
".",
"mutator",
".",
"fuzz",
"(",
"element",
"[",
"key",
"]",
")",
"}",
")",
"else",
":",
"tmp_element",
".",
"update",
"(",
"{",
"key",
":",
"self",
".",
"fuzz_elements",
"(",
"element",
"[",
"key",
"]",
")",
"}",
")",
"element",
"=",
"tmp_element",
"del",
"tmp_element",
"elif",
"type",
"(",
"element",
")",
"==",
"list",
":",
"arr",
"=",
"[",
"]",
"for",
"key",
"in",
"element",
":",
"if",
"type",
"(",
"key",
")",
"==",
"dict",
":",
"arr",
".",
"append",
"(",
"self",
".",
"fuzz_elements",
"(",
"key",
")",
")",
"elif",
"type",
"(",
"key",
")",
"==",
"list",
":",
"arr",
".",
"append",
"(",
"self",
".",
"fuzz_elements",
"(",
"key",
")",
")",
"else",
":",
"if",
"len",
"(",
"self",
".",
"config",
".",
"parameters",
")",
"<=",
"0",
":",
"arr",
".",
"append",
"(",
"self",
".",
"mutator",
".",
"fuzz",
"(",
"key",
")",
")",
"else",
":",
"arr",
".",
"append",
"(",
"key",
")",
"element",
"=",
"arr",
"del",
"arr",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")",
"return",
"element"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFFactory.fuzzed
|
Get a printable fuzzed object
|
pyjfuzz/core/pjf_factory.py
|
def fuzzed(self):
"""
Get a printable fuzzed object
"""
try:
if self.config.strong_fuzz:
fuzzer = PJFMutators(self.config)
if self.config.url_encode:
if sys.version_info >= (3, 0):
return urllib.parse.quote(fuzzer.fuzz(json.dumps(self.config.json)))
else:
return urllib.quote(fuzzer.fuzz(json.dumps(self.config.json)))
else:
if type(self.config.json) in [list, dict]:
return fuzzer.fuzz(json.dumps(self.config.json))
else:
return fuzzer.fuzz(self.config.json)
else:
if self.config.url_encode:
if sys.version_info >= (3, 0):
return urllib.parse.quote(self.get_fuzzed(self.config.indent, self.config.utf8))
else:
return urllib.quote(self.get_fuzzed(self.config.indent, self.config.utf8))
else:
return self.get_fuzzed(self.config.indent, self.config.utf8)
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def fuzzed(self):
"""
Get a printable fuzzed object
"""
try:
if self.config.strong_fuzz:
fuzzer = PJFMutators(self.config)
if self.config.url_encode:
if sys.version_info >= (3, 0):
return urllib.parse.quote(fuzzer.fuzz(json.dumps(self.config.json)))
else:
return urllib.quote(fuzzer.fuzz(json.dumps(self.config.json)))
else:
if type(self.config.json) in [list, dict]:
return fuzzer.fuzz(json.dumps(self.config.json))
else:
return fuzzer.fuzz(self.config.json)
else:
if self.config.url_encode:
if sys.version_info >= (3, 0):
return urllib.parse.quote(self.get_fuzzed(self.config.indent, self.config.utf8))
else:
return urllib.quote(self.get_fuzzed(self.config.indent, self.config.utf8))
else:
return self.get_fuzzed(self.config.indent, self.config.utf8)
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Get",
"a",
"printable",
"fuzzed",
"object"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_factory.py#L180-L206
|
[
"def",
"fuzzed",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"config",
".",
"strong_fuzz",
":",
"fuzzer",
"=",
"PJFMutators",
"(",
"self",
".",
"config",
")",
"if",
"self",
".",
"config",
".",
"url_encode",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"return",
"urllib",
".",
"parse",
".",
"quote",
"(",
"fuzzer",
".",
"fuzz",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"config",
".",
"json",
")",
")",
")",
"else",
":",
"return",
"urllib",
".",
"quote",
"(",
"fuzzer",
".",
"fuzz",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"config",
".",
"json",
")",
")",
")",
"else",
":",
"if",
"type",
"(",
"self",
".",
"config",
".",
"json",
")",
"in",
"[",
"list",
",",
"dict",
"]",
":",
"return",
"fuzzer",
".",
"fuzz",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"config",
".",
"json",
")",
")",
"else",
":",
"return",
"fuzzer",
".",
"fuzz",
"(",
"self",
".",
"config",
".",
"json",
")",
"else",
":",
"if",
"self",
".",
"config",
".",
"url_encode",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"return",
"urllib",
".",
"parse",
".",
"quote",
"(",
"self",
".",
"get_fuzzed",
"(",
"self",
".",
"config",
".",
"indent",
",",
"self",
".",
"config",
".",
"utf8",
")",
")",
"else",
":",
"return",
"urllib",
".",
"quote",
"(",
"self",
".",
"get_fuzzed",
"(",
"self",
".",
"config",
".",
"indent",
",",
"self",
".",
"config",
".",
"utf8",
")",
")",
"else",
":",
"return",
"self",
".",
"get_fuzzed",
"(",
"self",
".",
"config",
".",
"indent",
",",
"self",
".",
"config",
".",
"utf8",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFFactory.get_fuzzed
|
Return the fuzzed object
|
pyjfuzz/core/pjf_factory.py
|
def get_fuzzed(self, indent=False, utf8=False):
"""
Return the fuzzed object
"""
try:
if "array" in self.json:
return self.fuzz_elements(dict(self.json))["array"]
else:
return self.fuzz_elements(dict(self.json))
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def get_fuzzed(self, indent=False, utf8=False):
"""
Return the fuzzed object
"""
try:
if "array" in self.json:
return self.fuzz_elements(dict(self.json))["array"]
else:
return self.fuzz_elements(dict(self.json))
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Return",
"the",
"fuzzed",
"object"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_factory.py#L209-L219
|
[
"def",
"get_fuzzed",
"(",
"self",
",",
"indent",
"=",
"False",
",",
"utf8",
"=",
"False",
")",
":",
"try",
":",
"if",
"\"array\"",
"in",
"self",
".",
"json",
":",
"return",
"self",
".",
"fuzz_elements",
"(",
"dict",
"(",
"self",
".",
"json",
")",
")",
"[",
"\"array\"",
"]",
"else",
":",
"return",
"self",
".",
"fuzz_elements",
"(",
"dict",
"(",
"self",
".",
"json",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFDecorators.mutate_object_decorate
|
Mutate a generic object based on type
|
pyjfuzz/core/pjf_decoretors.py
|
def mutate_object_decorate(self, func):
"""
Mutate a generic object based on type
"""
def mutate():
obj = func()
return self.Mutators.get_mutator(obj, type(obj))
return mutate
|
def mutate_object_decorate(self, func):
"""
Mutate a generic object based on type
"""
def mutate():
obj = func()
return self.Mutators.get_mutator(obj, type(obj))
return mutate
|
[
"Mutate",
"a",
"generic",
"object",
"based",
"on",
"type"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_decoretors.py#L34-L41
|
[
"def",
"mutate_object_decorate",
"(",
"self",
",",
"func",
")",
":",
"def",
"mutate",
"(",
")",
":",
"obj",
"=",
"func",
"(",
")",
"return",
"self",
".",
"Mutators",
".",
"get_mutator",
"(",
"obj",
",",
"type",
"(",
"obj",
")",
")",
"return",
"mutate"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Config.rewrite_redis_url
|
\
if REDIS_SERVER is just an ip address, then we try to translate it to
redis_url, redis://REDIS_SERVER so that it doesn't try to connect to
localhost while you try to connect to another server
:return:
|
singlebeat/beat.py
|
def rewrite_redis_url(self):
"""\
if REDIS_SERVER is just an ip address, then we try to translate it to
redis_url, redis://REDIS_SERVER so that it doesn't try to connect to
localhost while you try to connect to another server
:return:
"""
if self.REDIS_SERVER.startswith('unix://') or \
self.REDIS_SERVER.startswith('redis://') or \
self.REDIS_SERVER.startswith('rediss://'):
return self.REDIS_SERVER
return 'redis://{}/'.format(self.REDIS_SERVER)
|
def rewrite_redis_url(self):
"""\
if REDIS_SERVER is just an ip address, then we try to translate it to
redis_url, redis://REDIS_SERVER so that it doesn't try to connect to
localhost while you try to connect to another server
:return:
"""
if self.REDIS_SERVER.startswith('unix://') or \
self.REDIS_SERVER.startswith('redis://') or \
self.REDIS_SERVER.startswith('rediss://'):
return self.REDIS_SERVER
return 'redis://{}/'.format(self.REDIS_SERVER)
|
[
"\\",
"if",
"REDIS_SERVER",
"is",
"just",
"an",
"ip",
"address",
"then",
"we",
"try",
"to",
"translate",
"it",
"to",
"redis_url",
"redis",
":",
"//",
"REDIS_SERVER",
"so",
"that",
"it",
"doesn",
"t",
"try",
"to",
"connect",
"to",
"localhost",
"while",
"you",
"try",
"to",
"connect",
"to",
"another",
"server",
":",
"return",
":"
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L60-L71
|
[
"def",
"rewrite_redis_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"REDIS_SERVER",
".",
"startswith",
"(",
"'unix://'",
")",
"or",
"self",
".",
"REDIS_SERVER",
".",
"startswith",
"(",
"'redis://'",
")",
"or",
"self",
".",
"REDIS_SERVER",
".",
"startswith",
"(",
"'rediss://'",
")",
":",
"return",
"self",
".",
"REDIS_SERVER",
"return",
"'redis://{}/'",
".",
"format",
"(",
"self",
".",
"REDIS_SERVER",
")"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Config.get_host_identifier
|
\
we try to return IPADDR:PID form to identify where any singlebeat instance is
running.
:return:
|
singlebeat/beat.py
|
def get_host_identifier(self):
"""\
we try to return IPADDR:PID form to identify where any singlebeat instance is
running.
:return:
"""
if self._host_identifier:
return self._host_identifier
local_ip_addr = self.get_redis().connection_pool\
.get_connection('ping')._sock.getsockname()[0]
self._host_identifier = '{}:{}'.format(local_ip_addr, os.getpid())
return self._host_identifier
|
def get_host_identifier(self):
"""\
we try to return IPADDR:PID form to identify where any singlebeat instance is
running.
:return:
"""
if self._host_identifier:
return self._host_identifier
local_ip_addr = self.get_redis().connection_pool\
.get_connection('ping')._sock.getsockname()[0]
self._host_identifier = '{}:{}'.format(local_ip_addr, os.getpid())
return self._host_identifier
|
[
"\\",
"we",
"try",
"to",
"return",
"IPADDR",
":",
"PID",
"form",
"to",
"identify",
"where",
"any",
"singlebeat",
"instance",
"is",
"running",
"."
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L89-L101
|
[
"def",
"get_host_identifier",
"(",
"self",
")",
":",
"if",
"self",
".",
"_host_identifier",
":",
"return",
"self",
".",
"_host_identifier",
"local_ip_addr",
"=",
"self",
".",
"get_redis",
"(",
")",
".",
"connection_pool",
".",
"get_connection",
"(",
"'ping'",
")",
".",
"_sock",
".",
"getsockname",
"(",
")",
"[",
"0",
"]",
"self",
".",
"_host_identifier",
"=",
"'{}:{}'",
".",
"format",
"(",
"local_ip_addr",
",",
"os",
".",
"getpid",
"(",
")",
")",
"return",
"self",
".",
"_host_identifier"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Process.sigterm_handler
|
When we get term signal
if we are waiting and got a sigterm, we just exit.
if we have a child running, we pass the signal first to the child
then we exit.
:param signum:
:param frame:
:return:
|
singlebeat/beat.py
|
def sigterm_handler(self, signum, frame):
""" When we get term signal
if we are waiting and got a sigterm, we just exit.
if we have a child running, we pass the signal first to the child
then we exit.
:param signum:
:param frame:
:return:
"""
assert(self.state in ('WAITING', 'RUNNING', 'PAUSED'))
logger.debug("our state %s", self.state)
if self.state == 'WAITING':
return self.ioloop.stop()
if self.state == 'RUNNING':
logger.debug('already running sending signal to child - %s',
self.sprocess.pid)
os.kill(self.sprocess.pid, signum)
self.ioloop.stop()
|
def sigterm_handler(self, signum, frame):
""" When we get term signal
if we are waiting and got a sigterm, we just exit.
if we have a child running, we pass the signal first to the child
then we exit.
:param signum:
:param frame:
:return:
"""
assert(self.state in ('WAITING', 'RUNNING', 'PAUSED'))
logger.debug("our state %s", self.state)
if self.state == 'WAITING':
return self.ioloop.stop()
if self.state == 'RUNNING':
logger.debug('already running sending signal to child - %s',
self.sprocess.pid)
os.kill(self.sprocess.pid, signum)
self.ioloop.stop()
|
[
"When",
"we",
"get",
"term",
"signal",
"if",
"we",
"are",
"waiting",
"and",
"got",
"a",
"sigterm",
"we",
"just",
"exit",
".",
"if",
"we",
"have",
"a",
"child",
"running",
"we",
"pass",
"the",
"signal",
"first",
"to",
"the",
"child",
"then",
"we",
"exit",
"."
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L259-L278
|
[
"def",
"sigterm_handler",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"assert",
"(",
"self",
".",
"state",
"in",
"(",
"'WAITING'",
",",
"'RUNNING'",
",",
"'PAUSED'",
")",
")",
"logger",
".",
"debug",
"(",
"\"our state %s\"",
",",
"self",
".",
"state",
")",
"if",
"self",
".",
"state",
"==",
"'WAITING'",
":",
"return",
"self",
".",
"ioloop",
".",
"stop",
"(",
")",
"if",
"self",
".",
"state",
"==",
"'RUNNING'",
":",
"logger",
".",
"debug",
"(",
"'already running sending signal to child - %s'",
",",
"self",
".",
"sprocess",
".",
"pid",
")",
"os",
".",
"kill",
"(",
"self",
".",
"sprocess",
".",
"pid",
",",
"signum",
")",
"self",
".",
"ioloop",
".",
"stop",
"(",
")"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Process.cli_command_quit
|
\
kills the child and exits
|
singlebeat/beat.py
|
def cli_command_quit(self, msg):
"""\
kills the child and exits
"""
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.sprocess.proc.kill()
else:
sys.exit(0)
|
def cli_command_quit(self, msg):
"""\
kills the child and exits
"""
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.sprocess.proc.kill()
else:
sys.exit(0)
|
[
"\\",
"kills",
"the",
"child",
"and",
"exits"
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L318-L325
|
[
"def",
"cli_command_quit",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"state",
"==",
"State",
".",
"RUNNING",
"and",
"self",
".",
"sprocess",
"and",
"self",
".",
"sprocess",
".",
"proc",
":",
"self",
".",
"sprocess",
".",
"proc",
".",
"kill",
"(",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"0",
")"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Process.cli_command_pause
|
\
if we have a running child we kill it and set our state to paused
if we don't have a running child, we set our state to paused
this will pause all the nodes in single-beat cluster
its useful when you deploy some code and don't want your child to spawn
randomly
:param msg:
:return:
|
singlebeat/beat.py
|
def cli_command_pause(self, msg):
"""\
if we have a running child we kill it and set our state to paused
if we don't have a running child, we set our state to paused
this will pause all the nodes in single-beat cluster
its useful when you deploy some code and don't want your child to spawn
randomly
:param msg:
:return:
"""
info = ''
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.sprocess.set_exit_callback(self.proc_exit_cb_noop)
self.sprocess.proc.kill()
info = 'killed'
# TODO: check if process is really dead etc.
self.state = State.PAUSED
return info
|
def cli_command_pause(self, msg):
"""\
if we have a running child we kill it and set our state to paused
if we don't have a running child, we set our state to paused
this will pause all the nodes in single-beat cluster
its useful when you deploy some code and don't want your child to spawn
randomly
:param msg:
:return:
"""
info = ''
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.sprocess.set_exit_callback(self.proc_exit_cb_noop)
self.sprocess.proc.kill()
info = 'killed'
# TODO: check if process is really dead etc.
self.state = State.PAUSED
return info
|
[
"\\",
"if",
"we",
"have",
"a",
"running",
"child",
"we",
"kill",
"it",
"and",
"set",
"our",
"state",
"to",
"paused",
"if",
"we",
"don",
"t",
"have",
"a",
"running",
"child",
"we",
"set",
"our",
"state",
"to",
"paused",
"this",
"will",
"pause",
"all",
"the",
"nodes",
"in",
"single",
"-",
"beat",
"cluster"
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L327-L346
|
[
"def",
"cli_command_pause",
"(",
"self",
",",
"msg",
")",
":",
"info",
"=",
"''",
"if",
"self",
".",
"state",
"==",
"State",
".",
"RUNNING",
"and",
"self",
".",
"sprocess",
"and",
"self",
".",
"sprocess",
".",
"proc",
":",
"self",
".",
"sprocess",
".",
"set_exit_callback",
"(",
"self",
".",
"proc_exit_cb_noop",
")",
"self",
".",
"sprocess",
".",
"proc",
".",
"kill",
"(",
")",
"info",
"=",
"'killed'",
"# TODO: check if process is really dead etc.",
"self",
".",
"state",
"=",
"State",
".",
"PAUSED",
"return",
"info"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Process.cli_command_resume
|
\
sets state to waiting - so we resume spawning children
|
singlebeat/beat.py
|
def cli_command_resume(self, msg):
"""\
sets state to waiting - so we resume spawning children
"""
if self.state == State.PAUSED:
self.state = State.WAITING
|
def cli_command_resume(self, msg):
"""\
sets state to waiting - so we resume spawning children
"""
if self.state == State.PAUSED:
self.state = State.WAITING
|
[
"\\",
"sets",
"state",
"to",
"waiting",
"-",
"so",
"we",
"resume",
"spawning",
"children"
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L348-L353
|
[
"def",
"cli_command_resume",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"state",
"==",
"State",
".",
"PAUSED",
":",
"self",
".",
"state",
"=",
"State",
".",
"WAITING"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Process.cli_command_stop
|
\
stops the running child process - if its running
it will re-spawn in any single-beat node after sometime
:param msg:
:return:
|
singlebeat/beat.py
|
def cli_command_stop(self, msg):
"""\
stops the running child process - if its running
it will re-spawn in any single-beat node after sometime
:param msg:
:return:
"""
info = ''
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.state = State.PAUSED
self.sprocess.set_exit_callback(self.proc_exit_cb_state_set)
self.sprocess.proc.kill()
info = 'killed'
# TODO: check if process is really dead etc.
return info
|
def cli_command_stop(self, msg):
"""\
stops the running child process - if its running
it will re-spawn in any single-beat node after sometime
:param msg:
:return:
"""
info = ''
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.state = State.PAUSED
self.sprocess.set_exit_callback(self.proc_exit_cb_state_set)
self.sprocess.proc.kill()
info = 'killed'
# TODO: check if process is really dead etc.
return info
|
[
"\\",
"stops",
"the",
"running",
"child",
"process",
"-",
"if",
"its",
"running",
"it",
"will",
"re",
"-",
"spawn",
"in",
"any",
"single",
"-",
"beat",
"node",
"after",
"sometime"
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L355-L370
|
[
"def",
"cli_command_stop",
"(",
"self",
",",
"msg",
")",
":",
"info",
"=",
"''",
"if",
"self",
".",
"state",
"==",
"State",
".",
"RUNNING",
"and",
"self",
".",
"sprocess",
"and",
"self",
".",
"sprocess",
".",
"proc",
":",
"self",
".",
"state",
"=",
"State",
".",
"PAUSED",
"self",
".",
"sprocess",
".",
"set_exit_callback",
"(",
"self",
".",
"proc_exit_cb_state_set",
")",
"self",
".",
"sprocess",
".",
"proc",
".",
"kill",
"(",
")",
"info",
"=",
"'killed'",
"# TODO: check if process is really dead etc.",
"return",
"info"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Process.cli_command_restart
|
\
restart the subprocess
i. we set our state to RESTARTING - on restarting we still send heartbeat
ii. we kill the subprocess
iii. we start again
iv. if its started we set our state to RUNNING, else we set it to WAITING
:param msg:
:return:
|
singlebeat/beat.py
|
def cli_command_restart(self, msg):
"""\
restart the subprocess
i. we set our state to RESTARTING - on restarting we still send heartbeat
ii. we kill the subprocess
iii. we start again
iv. if its started we set our state to RUNNING, else we set it to WAITING
:param msg:
:return:
"""
info = ''
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.state = State.RESTARTING
self.sprocess.set_exit_callback(self.proc_exit_cb_restart)
self.sprocess.proc.kill()
info = 'killed'
# TODO: check if process is really dead etc.
return info
|
def cli_command_restart(self, msg):
"""\
restart the subprocess
i. we set our state to RESTARTING - on restarting we still send heartbeat
ii. we kill the subprocess
iii. we start again
iv. if its started we set our state to RUNNING, else we set it to WAITING
:param msg:
:return:
"""
info = ''
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.state = State.RESTARTING
self.sprocess.set_exit_callback(self.proc_exit_cb_restart)
self.sprocess.proc.kill()
info = 'killed'
# TODO: check if process is really dead etc.
return info
|
[
"\\",
"restart",
"the",
"subprocess",
"i",
".",
"we",
"set",
"our",
"state",
"to",
"RESTARTING",
"-",
"on",
"restarting",
"we",
"still",
"send",
"heartbeat",
"ii",
".",
"we",
"kill",
"the",
"subprocess",
"iii",
".",
"we",
"start",
"again",
"iv",
".",
"if",
"its",
"started",
"we",
"set",
"our",
"state",
"to",
"RUNNING",
"else",
"we",
"set",
"it",
"to",
"WAITING"
] |
ybrs/single-beat
|
python
|
https://github.com/ybrs/single-beat/blob/d036b62d2531710dfd806e9dc2a8d67c77616082/singlebeat/beat.py#L372-L390
|
[
"def",
"cli_command_restart",
"(",
"self",
",",
"msg",
")",
":",
"info",
"=",
"''",
"if",
"self",
".",
"state",
"==",
"State",
".",
"RUNNING",
"and",
"self",
".",
"sprocess",
"and",
"self",
".",
"sprocess",
".",
"proc",
":",
"self",
".",
"state",
"=",
"State",
".",
"RESTARTING",
"self",
".",
"sprocess",
".",
"set_exit_callback",
"(",
"self",
".",
"proc_exit_cb_restart",
")",
"self",
".",
"sprocess",
".",
"proc",
".",
"kill",
"(",
")",
"info",
"=",
"'killed'",
"# TODO: check if process is really dead etc.",
"return",
"info"
] |
d036b62d2531710dfd806e9dc2a8d67c77616082
|
test
|
Skype.getEvents
|
Retrieve a list of events since the last poll. Multiple calls may be needed to retrieve all events.
If no events occur, the API will block for up to 30 seconds, after which an empty list is returned. As soon as
an event is received in this time, it is returned immediately.
Returns:
:class:`.SkypeEvent` list: a list of events, possibly empty
|
skpy/main.py
|
def getEvents(self):
"""
Retrieve a list of events since the last poll. Multiple calls may be needed to retrieve all events.
If no events occur, the API will block for up to 30 seconds, after which an empty list is returned. As soon as
an event is received in this time, it is returned immediately.
Returns:
:class:`.SkypeEvent` list: a list of events, possibly empty
"""
events = []
for json in self.conn.endpoints["self"].getEvents():
events.append(SkypeEvent.fromRaw(self, json))
return events
|
def getEvents(self):
"""
Retrieve a list of events since the last poll. Multiple calls may be needed to retrieve all events.
If no events occur, the API will block for up to 30 seconds, after which an empty list is returned. As soon as
an event is received in this time, it is returned immediately.
Returns:
:class:`.SkypeEvent` list: a list of events, possibly empty
"""
events = []
for json in self.conn.endpoints["self"].getEvents():
events.append(SkypeEvent.fromRaw(self, json))
return events
|
[
"Retrieve",
"a",
"list",
"of",
"events",
"since",
"the",
"last",
"poll",
".",
"Multiple",
"calls",
"may",
"be",
"needed",
"to",
"retrieve",
"all",
"events",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L94-L107
|
[
"def",
"getEvents",
"(",
"self",
")",
":",
"events",
"=",
"[",
"]",
"for",
"json",
"in",
"self",
".",
"conn",
".",
"endpoints",
"[",
"\"self\"",
"]",
".",
"getEvents",
"(",
")",
":",
"events",
".",
"append",
"(",
"SkypeEvent",
".",
"fromRaw",
"(",
"self",
",",
"json",
")",
")",
"return",
"events"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
Skype.setPresence
|
Set the current user's presence on the network. Supports :attr:`.Status.Online`, :attr:`.Status.Busy` or
:attr:`.Status.Hidden` (shown as :attr:`.Status.Offline` to others).
Args:
status (.Status): new availability to display to contacts
|
skpy/main.py
|
def setPresence(self, status=SkypeUtils.Status.Online):
"""
Set the current user's presence on the network. Supports :attr:`.Status.Online`, :attr:`.Status.Busy` or
:attr:`.Status.Hidden` (shown as :attr:`.Status.Offline` to others).
Args:
status (.Status): new availability to display to contacts
"""
self.conn("PUT", "{0}/users/ME/presenceDocs/messagingService".format(self.conn.msgsHost),
auth=SkypeConnection.Auth.RegToken, json={"status": status.label})
|
def setPresence(self, status=SkypeUtils.Status.Online):
"""
Set the current user's presence on the network. Supports :attr:`.Status.Online`, :attr:`.Status.Busy` or
:attr:`.Status.Hidden` (shown as :attr:`.Status.Offline` to others).
Args:
status (.Status): new availability to display to contacts
"""
self.conn("PUT", "{0}/users/ME/presenceDocs/messagingService".format(self.conn.msgsHost),
auth=SkypeConnection.Auth.RegToken, json={"status": status.label})
|
[
"Set",
"the",
"current",
"user",
"s",
"presence",
"on",
"the",
"network",
".",
"Supports",
":",
"attr",
":",
".",
"Status",
".",
"Online",
":",
"attr",
":",
".",
"Status",
".",
"Busy",
"or",
":",
"attr",
":",
".",
"Status",
".",
"Hidden",
"(",
"shown",
"as",
":",
"attr",
":",
".",
"Status",
".",
"Offline",
"to",
"others",
")",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L109-L118
|
[
"def",
"setPresence",
"(",
"self",
",",
"status",
"=",
"SkypeUtils",
".",
"Status",
".",
"Online",
")",
":",
"self",
".",
"conn",
"(",
"\"PUT\"",
",",
"\"{0}/users/ME/presenceDocs/messagingService\"",
".",
"format",
"(",
"self",
".",
"conn",
".",
"msgsHost",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"json",
"=",
"{",
"\"status\"",
":",
"status",
".",
"label",
"}",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
Skype.setMood
|
Update the activity message for the current user.
Args:
mood (str): new mood message
|
skpy/main.py
|
def setMood(self, mood):
"""
Update the activity message for the current user.
Args:
mood (str): new mood message
"""
self.conn("POST", "{0}/users/{1}/profile/partial".format(SkypeConnection.API_USER, self.userId),
auth=SkypeConnection.Auth.SkypeToken, json={"payload": {"mood": mood or ""}})
self.user.mood = SkypeUser.Mood(plain=mood) if mood else None
|
def setMood(self, mood):
"""
Update the activity message for the current user.
Args:
mood (str): new mood message
"""
self.conn("POST", "{0}/users/{1}/profile/partial".format(SkypeConnection.API_USER, self.userId),
auth=SkypeConnection.Auth.SkypeToken, json={"payload": {"mood": mood or ""}})
self.user.mood = SkypeUser.Mood(plain=mood) if mood else None
|
[
"Update",
"the",
"activity",
"message",
"for",
"the",
"current",
"user",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L120-L129
|
[
"def",
"setMood",
"(",
"self",
",",
"mood",
")",
":",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/{1}/profile/partial\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_USER",
",",
"self",
".",
"userId",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
",",
"json",
"=",
"{",
"\"payload\"",
":",
"{",
"\"mood\"",
":",
"mood",
"or",
"\"\"",
"}",
"}",
")",
"self",
".",
"user",
".",
"mood",
"=",
"SkypeUser",
".",
"Mood",
"(",
"plain",
"=",
"mood",
")",
"if",
"mood",
"else",
"None"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
Skype.setAvatar
|
Update the profile picture for the current user.
Args:
image (file): a file-like object to read the image from
|
skpy/main.py
|
def setAvatar(self, image):
"""
Update the profile picture for the current user.
Args:
image (file): a file-like object to read the image from
"""
self.conn("PUT", "{0}/users/{1}/profile/avatar".format(SkypeConnection.API_USER, self.userId),
auth=SkypeConnection.Auth.SkypeToken, data=image.read())
|
def setAvatar(self, image):
"""
Update the profile picture for the current user.
Args:
image (file): a file-like object to read the image from
"""
self.conn("PUT", "{0}/users/{1}/profile/avatar".format(SkypeConnection.API_USER, self.userId),
auth=SkypeConnection.Auth.SkypeToken, data=image.read())
|
[
"Update",
"the",
"profile",
"picture",
"for",
"the",
"current",
"user",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L131-L139
|
[
"def",
"setAvatar",
"(",
"self",
",",
"image",
")",
":",
"self",
".",
"conn",
"(",
"\"PUT\"",
",",
"\"{0}/users/{1}/profile/avatar\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_USER",
",",
"self",
".",
"userId",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
",",
"data",
"=",
"image",
".",
"read",
"(",
")",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
Skype.getUrlMeta
|
Retrieve various metadata associated with a URL, as seen by Skype.
Args:
url (str): address to ping for info
Returns:
dict: metadata for the website queried
|
skpy/main.py
|
def getUrlMeta(self, url):
"""
Retrieve various metadata associated with a URL, as seen by Skype.
Args:
url (str): address to ping for info
Returns:
dict: metadata for the website queried
"""
return self.conn("GET", SkypeConnection.API_URL, params={"url": url},
auth=SkypeConnection.Auth.Authorize).json()
|
def getUrlMeta(self, url):
"""
Retrieve various metadata associated with a URL, as seen by Skype.
Args:
url (str): address to ping for info
Returns:
dict: metadata for the website queried
"""
return self.conn("GET", SkypeConnection.API_URL, params={"url": url},
auth=SkypeConnection.Auth.Authorize).json()
|
[
"Retrieve",
"various",
"metadata",
"associated",
"with",
"a",
"URL",
"as",
"seen",
"by",
"Skype",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L141-L152
|
[
"def",
"getUrlMeta",
"(",
"self",
",",
"url",
")",
":",
"return",
"self",
".",
"conn",
"(",
"\"GET\"",
",",
"SkypeConnection",
".",
"API_URL",
",",
"params",
"=",
"{",
"\"url\"",
":",
"url",
"}",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"Authorize",
")",
".",
"json",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeEventLoop.cycle
|
Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn.
Subclasses may override this method to alter loop functionality.
|
skpy/main.py
|
def cycle(self):
"""
Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn.
Subclasses may override this method to alter loop functionality.
"""
try:
events = self.getEvents()
except requests.ConnectionError:
return
for event in events:
self.onEvent(event)
if self.autoAck:
event.ack()
|
def cycle(self):
"""
Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn.
Subclasses may override this method to alter loop functionality.
"""
try:
events = self.getEvents()
except requests.ConnectionError:
return
for event in events:
self.onEvent(event)
if self.autoAck:
event.ack()
|
[
"Request",
"one",
"batch",
"of",
"events",
"from",
"Skype",
"calling",
":",
"meth",
":",
"onEvent",
"with",
"each",
"event",
"in",
"turn",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L185-L198
|
[
"def",
"cycle",
"(",
"self",
")",
":",
"try",
":",
"events",
"=",
"self",
".",
"getEvents",
"(",
")",
"except",
"requests",
".",
"ConnectionError",
":",
"return",
"for",
"event",
"in",
"events",
":",
"self",
".",
"onEvent",
"(",
"event",
")",
"if",
"self",
".",
"autoAck",
":",
"event",
".",
"ack",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeSettings.syncFlags
|
Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute.
|
skpy/main.py
|
def syncFlags(self):
"""
Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute.
"""
self.flags = set(self.skype.conn("GET", SkypeConnection.API_FLAGS,
auth=SkypeConnection.Auth.SkypeToken).json())
|
def syncFlags(self):
"""
Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute.
"""
self.flags = set(self.skype.conn("GET", SkypeConnection.API_FLAGS,
auth=SkypeConnection.Auth.SkypeToken).json())
|
[
"Update",
"the",
"cached",
"list",
"of",
"all",
"enabled",
"flags",
"and",
"store",
"it",
"in",
"the",
":",
"attr",
":",
"flags",
"attribute",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/main.py#L282-L287
|
[
"def",
"syncFlags",
"(",
"self",
")",
":",
"self",
".",
"flags",
"=",
"set",
"(",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"SkypeConnection",
".",
"API_FLAGS",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
")",
".",
"json",
"(",
")",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeContacts.contact
|
Retrieve all details for a specific contact, including fields such as birthday and mood.
Args:
id (str): user identifier to lookup
Returns:
SkypeContact: resulting contact object
|
skpy/user.py
|
def contact(self, id):
"""
Retrieve all details for a specific contact, including fields such as birthday and mood.
Args:
id (str): user identifier to lookup
Returns:
SkypeContact: resulting contact object
"""
try:
json = self.skype.conn("POST", "{0}/users/batch/profiles".format(SkypeConnection.API_USER),
json={"usernames": [id]}, auth=SkypeConnection.Auth.SkypeToken).json()
contact = SkypeContact.fromRaw(self.skype, json[0])
if contact.id not in self.contactIds:
self.contactIds.append(contact.id)
return self.merge(contact)
except SkypeApiException as e:
if len(e.args) >= 2 and getattr(e.args[1], "status_code", None) == 403:
# Not a contact, so no permission to retrieve information.
return None
raise
|
def contact(self, id):
"""
Retrieve all details for a specific contact, including fields such as birthday and mood.
Args:
id (str): user identifier to lookup
Returns:
SkypeContact: resulting contact object
"""
try:
json = self.skype.conn("POST", "{0}/users/batch/profiles".format(SkypeConnection.API_USER),
json={"usernames": [id]}, auth=SkypeConnection.Auth.SkypeToken).json()
contact = SkypeContact.fromRaw(self.skype, json[0])
if contact.id not in self.contactIds:
self.contactIds.append(contact.id)
return self.merge(contact)
except SkypeApiException as e:
if len(e.args) >= 2 and getattr(e.args[1], "status_code", None) == 403:
# Not a contact, so no permission to retrieve information.
return None
raise
|
[
"Retrieve",
"all",
"details",
"for",
"a",
"specific",
"contact",
"including",
"fields",
"such",
"as",
"birthday",
"and",
"mood",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/user.py#L388-L409
|
[
"def",
"contact",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"json",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/batch/profiles\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_USER",
")",
",",
"json",
"=",
"{",
"\"usernames\"",
":",
"[",
"id",
"]",
"}",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
")",
".",
"json",
"(",
")",
"contact",
"=",
"SkypeContact",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"json",
"[",
"0",
"]",
")",
"if",
"contact",
".",
"id",
"not",
"in",
"self",
".",
"contactIds",
":",
"self",
".",
"contactIds",
".",
"append",
"(",
"contact",
".",
"id",
")",
"return",
"self",
".",
"merge",
"(",
"contact",
")",
"except",
"SkypeApiException",
"as",
"e",
":",
"if",
"len",
"(",
"e",
".",
"args",
")",
">=",
"2",
"and",
"getattr",
"(",
"e",
".",
"args",
"[",
"1",
"]",
",",
"\"status_code\"",
",",
"None",
")",
"==",
"403",
":",
"# Not a contact, so no permission to retrieve information.",
"return",
"None",
"raise"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeContacts.user
|
Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object
|
skpy/user.py
|
def user(self, id):
"""
Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object
"""
json = self.skype.conn("POST", "{0}/batch/profiles".format(SkypeConnection.API_PROFILE),
auth=SkypeConnection.Auth.SkypeToken, json={"usernames": [id]}).json()
if json and "status" not in json[0]:
return self.merge(SkypeUser.fromRaw(self.skype, json[0]))
else:
return None
|
def user(self, id):
"""
Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object
"""
json = self.skype.conn("POST", "{0}/batch/profiles".format(SkypeConnection.API_PROFILE),
auth=SkypeConnection.Auth.SkypeToken, json={"usernames": [id]}).json()
if json and "status" not in json[0]:
return self.merge(SkypeUser.fromRaw(self.skype, json[0]))
else:
return None
|
[
"Retrieve",
"public",
"information",
"about",
"a",
"user",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/user.py#L411-L426
|
[
"def",
"user",
"(",
"self",
",",
"id",
")",
":",
"json",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/batch/profiles\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_PROFILE",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
",",
"json",
"=",
"{",
"\"usernames\"",
":",
"[",
"id",
"]",
"}",
")",
".",
"json",
"(",
")",
"if",
"json",
"and",
"\"status\"",
"not",
"in",
"json",
"[",
"0",
"]",
":",
"return",
"self",
".",
"merge",
"(",
"SkypeUser",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"json",
"[",
"0",
"]",
")",
")",
"else",
":",
"return",
"None"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeContacts.bots
|
Retrieve a list of all known bots.
Returns:
SkypeBotUser list: resulting bot user objects
|
skpy/user.py
|
def bots(self):
"""
Retrieve a list of all known bots.
Returns:
SkypeBotUser list: resulting bot user objects
"""
json = self.skype.conn("GET", "{0}/agents".format(SkypeConnection.API_BOT),
auth=SkypeConnection.Auth.SkypeToken).json().get("agentDescriptions", [])
return [self.merge(SkypeBotUser.fromRaw(self.skype, raw)) for raw in json]
|
def bots(self):
"""
Retrieve a list of all known bots.
Returns:
SkypeBotUser list: resulting bot user objects
"""
json = self.skype.conn("GET", "{0}/agents".format(SkypeConnection.API_BOT),
auth=SkypeConnection.Auth.SkypeToken).json().get("agentDescriptions", [])
return [self.merge(SkypeBotUser.fromRaw(self.skype, raw)) for raw in json]
|
[
"Retrieve",
"a",
"list",
"of",
"all",
"known",
"bots",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/user.py#L429-L438
|
[
"def",
"bots",
"(",
"self",
")",
":",
"json",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/agents\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_BOT",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"agentDescriptions\"",
",",
"[",
"]",
")",
"return",
"[",
"self",
".",
"merge",
"(",
"SkypeBotUser",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"raw",
")",
")",
"for",
"raw",
"in",
"json",
"]"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeContacts.bot
|
Retrieve a single bot.
Args:
id (str): UUID or username of the bot
Returns:
SkypeBotUser: resulting bot user object
|
skpy/user.py
|
def bot(self, id):
"""
Retrieve a single bot.
Args:
id (str): UUID or username of the bot
Returns:
SkypeBotUser: resulting bot user object
"""
json = self.skype.conn("GET", "{0}/agents".format(SkypeConnection.API_BOT), params={"agentId": id},
auth=SkypeConnection.Auth.SkypeToken).json().get("agentDescriptions", [])
return self.merge(SkypeBotUser.fromRaw(self.skype, json[0])) if json else None
|
def bot(self, id):
"""
Retrieve a single bot.
Args:
id (str): UUID or username of the bot
Returns:
SkypeBotUser: resulting bot user object
"""
json = self.skype.conn("GET", "{0}/agents".format(SkypeConnection.API_BOT), params={"agentId": id},
auth=SkypeConnection.Auth.SkypeToken).json().get("agentDescriptions", [])
return self.merge(SkypeBotUser.fromRaw(self.skype, json[0])) if json else None
|
[
"Retrieve",
"a",
"single",
"bot",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/user.py#L440-L452
|
[
"def",
"bot",
"(",
"self",
",",
"id",
")",
":",
"json",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/agents\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_BOT",
")",
",",
"params",
"=",
"{",
"\"agentId\"",
":",
"id",
"}",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"agentDescriptions\"",
",",
"[",
"]",
")",
"return",
"self",
".",
"merge",
"(",
"SkypeBotUser",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"json",
"[",
"0",
"]",
")",
")",
"if",
"json",
"else",
"None"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeContacts.search
|
Search the Skype Directory for a user.
Args:
query (str): name to search for
Returns:
SkypeUser list: collection of possible results
|
skpy/user.py
|
def search(self, query):
"""
Search the Skype Directory for a user.
Args:
query (str): name to search for
Returns:
SkypeUser list: collection of possible results
"""
results = self.skype.conn("GET", SkypeConnection.API_DIRECTORY,
auth=SkypeConnection.Auth.SkypeToken,
params={"searchstring": query, "requestId": "0"}).json().get("results", [])
return [SkypeUser.fromRaw(self.skype, json.get("nodeProfileData", {})) for json in results]
|
def search(self, query):
"""
Search the Skype Directory for a user.
Args:
query (str): name to search for
Returns:
SkypeUser list: collection of possible results
"""
results = self.skype.conn("GET", SkypeConnection.API_DIRECTORY,
auth=SkypeConnection.Auth.SkypeToken,
params={"searchstring": query, "requestId": "0"}).json().get("results", [])
return [SkypeUser.fromRaw(self.skype, json.get("nodeProfileData", {})) for json in results]
|
[
"Search",
"the",
"Skype",
"Directory",
"for",
"a",
"user",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/user.py#L455-L468
|
[
"def",
"search",
"(",
"self",
",",
"query",
")",
":",
"results",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"SkypeConnection",
".",
"API_DIRECTORY",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
",",
"params",
"=",
"{",
"\"searchstring\"",
":",
"query",
",",
"\"requestId\"",
":",
"\"0\"",
"}",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"results\"",
",",
"[",
"]",
")",
"return",
"[",
"SkypeUser",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"json",
".",
"get",
"(",
"\"nodeProfileData\"",
",",
"{",
"}",
")",
")",
"for",
"json",
"in",
"results",
"]"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeContacts.requests
|
Retrieve any pending contact requests.
Returns:
:class:`SkypeRequest` list: collection of requests
|
skpy/user.py
|
def requests(self):
"""
Retrieve any pending contact requests.
Returns:
:class:`SkypeRequest` list: collection of requests
"""
requests = []
for json in self.skype.conn("GET", "{0}/users/{1}/invites"
.format(SkypeConnection.API_CONTACTS, self.skype.userId),
auth=SkypeConnection.Auth.SkypeToken).json().get("invite_list", []):
for invite in json.get("invites", []):
# Copy user identifier to each invite message.
invite["userId"] = SkypeUtils.noPrefix(json.get("mri"))
requests.append(SkypeRequest.fromRaw(self.skype, invite))
return requests
|
def requests(self):
"""
Retrieve any pending contact requests.
Returns:
:class:`SkypeRequest` list: collection of requests
"""
requests = []
for json in self.skype.conn("GET", "{0}/users/{1}/invites"
.format(SkypeConnection.API_CONTACTS, self.skype.userId),
auth=SkypeConnection.Auth.SkypeToken).json().get("invite_list", []):
for invite in json.get("invites", []):
# Copy user identifier to each invite message.
invite["userId"] = SkypeUtils.noPrefix(json.get("mri"))
requests.append(SkypeRequest.fromRaw(self.skype, invite))
return requests
|
[
"Retrieve",
"any",
"pending",
"contact",
"requests",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/user.py#L470-L485
|
[
"def",
"requests",
"(",
"self",
")",
":",
"requests",
"=",
"[",
"]",
"for",
"json",
"in",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/users/{1}/invites\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_CONTACTS",
",",
"self",
".",
"skype",
".",
"userId",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"SkypeToken",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"invite_list\"",
",",
"[",
"]",
")",
":",
"for",
"invite",
"in",
"json",
".",
"get",
"(",
"\"invites\"",
",",
"[",
"]",
")",
":",
"# Copy user identifier to each invite message.",
"invite",
"[",
"\"userId\"",
"]",
"=",
"SkypeUtils",
".",
"noPrefix",
"(",
"json",
".",
"get",
"(",
"\"mri\"",
")",
")",
"requests",
".",
"append",
"(",
"SkypeRequest",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"invite",
")",
")",
"return",
"requests"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeObj.fromRaw
|
Create a new instance based on the raw properties of an API response.
This can be overridden to automatically create subclass instances based on the raw content.
Args:
skype (Skype): parent Skype instance
raw (dict): raw object, as provided by the API
Returns:
SkypeObj: the new class instance
|
skpy/core.py
|
def fromRaw(cls, skype=None, raw={}):
"""
Create a new instance based on the raw properties of an API response.
This can be overridden to automatically create subclass instances based on the raw content.
Args:
skype (Skype): parent Skype instance
raw (dict): raw object, as provided by the API
Returns:
SkypeObj: the new class instance
"""
return cls(skype, raw, **cls.rawToFields(raw))
|
def fromRaw(cls, skype=None, raw={}):
"""
Create a new instance based on the raw properties of an API response.
This can be overridden to automatically create subclass instances based on the raw content.
Args:
skype (Skype): parent Skype instance
raw (dict): raw object, as provided by the API
Returns:
SkypeObj: the new class instance
"""
return cls(skype, raw, **cls.rawToFields(raw))
|
[
"Create",
"a",
"new",
"instance",
"based",
"on",
"the",
"raw",
"properties",
"of",
"an",
"API",
"response",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/core.py#L48-L61
|
[
"def",
"fromRaw",
"(",
"cls",
",",
"skype",
"=",
"None",
",",
"raw",
"=",
"{",
"}",
")",
":",
"return",
"cls",
"(",
"skype",
",",
"raw",
",",
"*",
"*",
"cls",
".",
"rawToFields",
"(",
"raw",
")",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeObj.merge
|
Copy properties from other into self, skipping ``None`` values. Also merges the raw data.
Args:
other (SkypeObj): second object to copy fields from
|
skpy/core.py
|
def merge(self, other):
"""
Copy properties from other into self, skipping ``None`` values. Also merges the raw data.
Args:
other (SkypeObj): second object to copy fields from
"""
for attr in self.attrs:
if not getattr(other, attr, None) is None:
setattr(self, attr, getattr(other, attr))
if other.raw:
if not self.raw:
self.raw = {}
self.raw.update(other.raw)
|
def merge(self, other):
"""
Copy properties from other into self, skipping ``None`` values. Also merges the raw data.
Args:
other (SkypeObj): second object to copy fields from
"""
for attr in self.attrs:
if not getattr(other, attr, None) is None:
setattr(self, attr, getattr(other, attr))
if other.raw:
if not self.raw:
self.raw = {}
self.raw.update(other.raw)
|
[
"Copy",
"properties",
"from",
"other",
"into",
"self",
"skipping",
"None",
"values",
".",
"Also",
"merges",
"the",
"raw",
"data",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/core.py#L63-L76
|
[
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"for",
"attr",
"in",
"self",
".",
"attrs",
":",
"if",
"not",
"getattr",
"(",
"other",
",",
"attr",
",",
"None",
")",
"is",
"None",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"getattr",
"(",
"other",
",",
"attr",
")",
")",
"if",
"other",
".",
"raw",
":",
"if",
"not",
"self",
".",
"raw",
":",
"self",
".",
"raw",
"=",
"{",
"}",
"self",
".",
"raw",
".",
"update",
"(",
"other",
".",
"raw",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeObjs.merge
|
Add a given object to the cache, or update an existing entry to include more fields.
Args:
obj (SkypeObj): object to add to the cache
|
skpy/core.py
|
def merge(self, obj):
"""
Add a given object to the cache, or update an existing entry to include more fields.
Args:
obj (SkypeObj): object to add to the cache
"""
if obj.id in self.cache:
self.cache[obj.id].merge(obj)
else:
self.cache[obj.id] = obj
return self.cache[obj.id]
|
def merge(self, obj):
"""
Add a given object to the cache, or update an existing entry to include more fields.
Args:
obj (SkypeObj): object to add to the cache
"""
if obj.id in self.cache:
self.cache[obj.id].merge(obj)
else:
self.cache[obj.id] = obj
return self.cache[obj.id]
|
[
"Add",
"a",
"given",
"object",
"to",
"the",
"cache",
"or",
"update",
"an",
"existing",
"entry",
"to",
"include",
"more",
"fields",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/core.py#L155-L166
|
[
"def",
"merge",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"id",
"in",
"self",
".",
"cache",
":",
"self",
".",
"cache",
"[",
"obj",
".",
"id",
"]",
".",
"merge",
"(",
"obj",
")",
"else",
":",
"self",
".",
"cache",
"[",
"obj",
".",
"id",
"]",
"=",
"obj",
"return",
"self",
".",
"cache",
"[",
"obj",
".",
"id",
"]"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.handle
|
Method decorator: if a given status code is received, re-authenticate and try again.
Args:
codes (int list): status codes to respond to
regToken (bool): whether to try retrieving a new token on error
Returns:
method: decorator function, ready to apply to other methods
|
skpy/conn.py
|
def handle(*codes, **kwargs):
"""
Method decorator: if a given status code is received, re-authenticate and try again.
Args:
codes (int list): status codes to respond to
regToken (bool): whether to try retrieving a new token on error
Returns:
method: decorator function, ready to apply to other methods
"""
regToken = kwargs.get("regToken", False)
subscribe = kwargs.get("subscribe")
def decorator(fn):
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except SkypeApiException as e:
if isinstance(e.args[1], requests.Response) and e.args[1].status_code in codes:
conn = self if isinstance(self, SkypeConnection) else self.conn
if regToken:
conn.getRegToken()
if subscribe:
conn.endpoints[subscribe].subscribe()
return fn(self, *args, **kwargs)
raise
return wrapper
return decorator
|
def handle(*codes, **kwargs):
"""
Method decorator: if a given status code is received, re-authenticate and try again.
Args:
codes (int list): status codes to respond to
regToken (bool): whether to try retrieving a new token on error
Returns:
method: decorator function, ready to apply to other methods
"""
regToken = kwargs.get("regToken", False)
subscribe = kwargs.get("subscribe")
def decorator(fn):
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except SkypeApiException as e:
if isinstance(e.args[1], requests.Response) and e.args[1].status_code in codes:
conn = self if isinstance(self, SkypeConnection) else self.conn
if regToken:
conn.getRegToken()
if subscribe:
conn.endpoints[subscribe].subscribe()
return fn(self, *args, **kwargs)
raise
return wrapper
return decorator
|
[
"Method",
"decorator",
":",
"if",
"a",
"given",
"status",
"code",
"is",
"received",
"re",
"-",
"authenticate",
"and",
"try",
"again",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L59-L89
|
[
"def",
"handle",
"(",
"*",
"codes",
",",
"*",
"*",
"kwargs",
")",
":",
"regToken",
"=",
"kwargs",
".",
"get",
"(",
"\"regToken\"",
",",
"False",
")",
"subscribe",
"=",
"kwargs",
".",
"get",
"(",
"\"subscribe\"",
")",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"fn",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"SkypeApiException",
"as",
"e",
":",
"if",
"isinstance",
"(",
"e",
".",
"args",
"[",
"1",
"]",
",",
"requests",
".",
"Response",
")",
"and",
"e",
".",
"args",
"[",
"1",
"]",
".",
"status_code",
"in",
"codes",
":",
"conn",
"=",
"self",
"if",
"isinstance",
"(",
"self",
",",
"SkypeConnection",
")",
"else",
"self",
".",
"conn",
"if",
"regToken",
":",
"conn",
".",
"getRegToken",
"(",
")",
"if",
"subscribe",
":",
"conn",
".",
"endpoints",
"[",
"subscribe",
"]",
".",
"subscribe",
"(",
")",
"return",
"fn",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"raise",
"return",
"wrapper",
"return",
"decorator"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.externalCall
|
Make a public API call without a connected :class:`.Skype` instance.
The obvious implications are that no authenticated calls are possible, though this allows accessing some public
APIs such as join URL lookups.
Args:
method (str): HTTP request method
url (str): full URL to connect to
codes (int list): expected HTTP response codes for success
kwargs (dict): any extra parameters to pass to :func:`requests.request`
Returns:
requests.Response: response object provided by :mod:`requests`
Raises:
.SkypeAuthException: if an authentication rate limit is reached
.SkypeApiException: if a successful status code is not received
|
skpy/conn.py
|
def externalCall(cls, method, url, codes=(200, 201, 204, 207), **kwargs):
"""
Make a public API call without a connected :class:`.Skype` instance.
The obvious implications are that no authenticated calls are possible, though this allows accessing some public
APIs such as join URL lookups.
Args:
method (str): HTTP request method
url (str): full URL to connect to
codes (int list): expected HTTP response codes for success
kwargs (dict): any extra parameters to pass to :func:`requests.request`
Returns:
requests.Response: response object provided by :mod:`requests`
Raises:
.SkypeAuthException: if an authentication rate limit is reached
.SkypeApiException: if a successful status code is not received
"""
if os.getenv("SKPY_DEBUG_HTTP"):
print("<= [{0}] {1} {2}".format(datetime.now().strftime("%d/%m %H:%M:%S"), method, url))
print(pformat(kwargs))
resp = cls.extSess.request(method, url, **kwargs)
if os.getenv("SKPY_DEBUG_HTTP"):
print("=> [{0}] {1}".format(datetime.now().strftime("%d/%m %H:%M:%S"), resp.status_code))
print(pformat(dict(resp.headers)))
try:
print(pformat(resp.json()))
except ValueError:
print(resp.text)
if resp.status_code not in codes:
raise SkypeApiException("{0} response from {1} {2}".format(resp.status_code, method, url), resp)
return resp
|
def externalCall(cls, method, url, codes=(200, 201, 204, 207), **kwargs):
"""
Make a public API call without a connected :class:`.Skype` instance.
The obvious implications are that no authenticated calls are possible, though this allows accessing some public
APIs such as join URL lookups.
Args:
method (str): HTTP request method
url (str): full URL to connect to
codes (int list): expected HTTP response codes for success
kwargs (dict): any extra parameters to pass to :func:`requests.request`
Returns:
requests.Response: response object provided by :mod:`requests`
Raises:
.SkypeAuthException: if an authentication rate limit is reached
.SkypeApiException: if a successful status code is not received
"""
if os.getenv("SKPY_DEBUG_HTTP"):
print("<= [{0}] {1} {2}".format(datetime.now().strftime("%d/%m %H:%M:%S"), method, url))
print(pformat(kwargs))
resp = cls.extSess.request(method, url, **kwargs)
if os.getenv("SKPY_DEBUG_HTTP"):
print("=> [{0}] {1}".format(datetime.now().strftime("%d/%m %H:%M:%S"), resp.status_code))
print(pformat(dict(resp.headers)))
try:
print(pformat(resp.json()))
except ValueError:
print(resp.text)
if resp.status_code not in codes:
raise SkypeApiException("{0} response from {1} {2}".format(resp.status_code, method, url), resp)
return resp
|
[
"Make",
"a",
"public",
"API",
"call",
"without",
"a",
"connected",
":",
"class",
":",
".",
"Skype",
"instance",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L92-L125
|
[
"def",
"externalCall",
"(",
"cls",
",",
"method",
",",
"url",
",",
"codes",
"=",
"(",
"200",
",",
"201",
",",
"204",
",",
"207",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"\"SKPY_DEBUG_HTTP\"",
")",
":",
"print",
"(",
"\"<= [{0}] {1} {2}\"",
".",
"format",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%d/%m %H:%M:%S\"",
")",
",",
"method",
",",
"url",
")",
")",
"print",
"(",
"pformat",
"(",
"kwargs",
")",
")",
"resp",
"=",
"cls",
".",
"extSess",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
"if",
"os",
".",
"getenv",
"(",
"\"SKPY_DEBUG_HTTP\"",
")",
":",
"print",
"(",
"\"=> [{0}] {1}\"",
".",
"format",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%d/%m %H:%M:%S\"",
")",
",",
"resp",
".",
"status_code",
")",
")",
"print",
"(",
"pformat",
"(",
"dict",
"(",
"resp",
".",
"headers",
")",
")",
")",
"try",
":",
"print",
"(",
"pformat",
"(",
"resp",
".",
"json",
"(",
")",
")",
")",
"except",
"ValueError",
":",
"print",
"(",
"resp",
".",
"text",
")",
"if",
"resp",
".",
"status_code",
"not",
"in",
"codes",
":",
"raise",
"SkypeApiException",
"(",
"\"{0} response from {1} {2}\"",
".",
"format",
"(",
"resp",
".",
"status_code",
",",
"method",
",",
"url",
")",
",",
"resp",
")",
"return",
"resp"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.syncStateCall
|
Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination.
In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the
response, subsequent calls go to the latest URL instead.
Args:
method (str): HTTP request method
url (str): full URL to connect to
params (dict): query parameters to include in the URL
kwargs (dict): any extra parameters to pass to :meth:`__call__`
|
skpy/conn.py
|
def syncStateCall(self, method, url, params={}, **kwargs):
"""
Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination.
In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the
response, subsequent calls go to the latest URL instead.
Args:
method (str): HTTP request method
url (str): full URL to connect to
params (dict): query parameters to include in the URL
kwargs (dict): any extra parameters to pass to :meth:`__call__`
"""
try:
states = self.syncStates[(method, url)]
except KeyError:
states = self.syncStates[(method, url)] = []
if states:
# We have a state link, use it to replace the URL and query string.
url = states[-1]
params = {}
resp = self(method, url, params=params, **kwargs)
try:
json = resp.json()
except ValueError:
# Don't do anything if not a JSON response.
pass
else:
# If a state link exists in the response, store it for later.
state = json.get("_metadata", {}).get("syncState")
if state:
states.append(state)
return resp
|
def syncStateCall(self, method, url, params={}, **kwargs):
"""
Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination.
In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the
response, subsequent calls go to the latest URL instead.
Args:
method (str): HTTP request method
url (str): full URL to connect to
params (dict): query parameters to include in the URL
kwargs (dict): any extra parameters to pass to :meth:`__call__`
"""
try:
states = self.syncStates[(method, url)]
except KeyError:
states = self.syncStates[(method, url)] = []
if states:
# We have a state link, use it to replace the URL and query string.
url = states[-1]
params = {}
resp = self(method, url, params=params, **kwargs)
try:
json = resp.json()
except ValueError:
# Don't do anything if not a JSON response.
pass
else:
# If a state link exists in the response, store it for later.
state = json.get("_metadata", {}).get("syncState")
if state:
states.append(state)
return resp
|
[
"Follow",
"and",
"track",
"sync",
"state",
"URLs",
"provided",
"by",
"an",
"API",
"endpoint",
"in",
"order",
"to",
"implicitly",
"handle",
"pagination",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L222-L254
|
[
"def",
"syncStateCall",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"states",
"=",
"self",
".",
"syncStates",
"[",
"(",
"method",
",",
"url",
")",
"]",
"except",
"KeyError",
":",
"states",
"=",
"self",
".",
"syncStates",
"[",
"(",
"method",
",",
"url",
")",
"]",
"=",
"[",
"]",
"if",
"states",
":",
"# We have a state link, use it to replace the URL and query string.",
"url",
"=",
"states",
"[",
"-",
"1",
"]",
"params",
"=",
"{",
"}",
"resp",
"=",
"self",
"(",
"method",
",",
"url",
",",
"params",
"=",
"params",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"json",
"=",
"resp",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"# Don't do anything if not a JSON response.",
"pass",
"else",
":",
"# If a state link exists in the response, store it for later.",
"state",
"=",
"json",
".",
"get",
"(",
"\"_metadata\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"syncState\"",
")",
"if",
"state",
":",
"states",
".",
"append",
"(",
"state",
")",
"return",
"resp"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.setUserPwd
|
Replace the stub :meth:`getSkypeToken` method with one that connects via the Microsoft account flow using the
given credentials. Avoids storing the account password in an accessible way.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
|
skpy/conn.py
|
def setUserPwd(self, user, pwd):
"""
Replace the stub :meth:`getSkypeToken` method with one that connects via the Microsoft account flow using the
given credentials. Avoids storing the account password in an accessible way.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
"""
def getSkypeToken(self):
self.liveLogin(user, pwd)
self.getSkypeToken = MethodType(getSkypeToken, self)
|
def setUserPwd(self, user, pwd):
"""
Replace the stub :meth:`getSkypeToken` method with one that connects via the Microsoft account flow using the
given credentials. Avoids storing the account password in an accessible way.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
"""
def getSkypeToken(self):
self.liveLogin(user, pwd)
self.getSkypeToken = MethodType(getSkypeToken, self)
|
[
"Replace",
"the",
"stub",
":",
"meth",
":",
"getSkypeToken",
"method",
"with",
"one",
"that",
"connects",
"via",
"the",
"Microsoft",
"account",
"flow",
"using",
"the",
"given",
"credentials",
".",
"Avoids",
"storing",
"the",
"account",
"password",
"in",
"an",
"accessible",
"way",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L256-L267
|
[
"def",
"setUserPwd",
"(",
"self",
",",
"user",
",",
"pwd",
")",
":",
"def",
"getSkypeToken",
"(",
"self",
")",
":",
"self",
".",
"liveLogin",
"(",
"user",
",",
"pwd",
")",
"self",
".",
"getSkypeToken",
"=",
"MethodType",
"(",
"getSkypeToken",
",",
"self",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.readToken
|
Attempt to re-establish a connection using previously acquired tokens.
If the Skype token is valid but the registration token is invalid, a new endpoint will be registered.
Raises:
.SkypeAuthException: if the token file cannot be used to authenticate
|
skpy/conn.py
|
def readToken(self):
"""
Attempt to re-establish a connection using previously acquired tokens.
If the Skype token is valid but the registration token is invalid, a new endpoint will be registered.
Raises:
.SkypeAuthException: if the token file cannot be used to authenticate
"""
if not self.tokenFile:
raise SkypeAuthException("No token file specified")
try:
with open(self.tokenFile, "r") as f:
lines = f.read().splitlines()
except OSError:
raise SkypeAuthException("Token file doesn't exist or not readable")
try:
user, skypeToken, skypeExpiry, regToken, regExpiry, msgsHost = lines
skypeExpiry = datetime.fromtimestamp(int(skypeExpiry))
regExpiry = datetime.fromtimestamp(int(regExpiry))
except ValueError:
raise SkypeAuthException("Token file is malformed")
if datetime.now() >= skypeExpiry:
raise SkypeAuthException("Token file has expired")
self.userId = user
self.tokens["skype"] = skypeToken
self.tokenExpiry["skype"] = skypeExpiry
if datetime.now() < regExpiry:
self.tokens["reg"] = regToken
self.tokenExpiry["reg"] = regExpiry
self.msgsHost = msgsHost
else:
self.getRegToken()
|
def readToken(self):
"""
Attempt to re-establish a connection using previously acquired tokens.
If the Skype token is valid but the registration token is invalid, a new endpoint will be registered.
Raises:
.SkypeAuthException: if the token file cannot be used to authenticate
"""
if not self.tokenFile:
raise SkypeAuthException("No token file specified")
try:
with open(self.tokenFile, "r") as f:
lines = f.read().splitlines()
except OSError:
raise SkypeAuthException("Token file doesn't exist or not readable")
try:
user, skypeToken, skypeExpiry, regToken, regExpiry, msgsHost = lines
skypeExpiry = datetime.fromtimestamp(int(skypeExpiry))
regExpiry = datetime.fromtimestamp(int(regExpiry))
except ValueError:
raise SkypeAuthException("Token file is malformed")
if datetime.now() >= skypeExpiry:
raise SkypeAuthException("Token file has expired")
self.userId = user
self.tokens["skype"] = skypeToken
self.tokenExpiry["skype"] = skypeExpiry
if datetime.now() < regExpiry:
self.tokens["reg"] = regToken
self.tokenExpiry["reg"] = regExpiry
self.msgsHost = msgsHost
else:
self.getRegToken()
|
[
"Attempt",
"to",
"re",
"-",
"establish",
"a",
"connection",
"using",
"previously",
"acquired",
"tokens",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L278-L310
|
[
"def",
"readToken",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tokenFile",
":",
"raise",
"SkypeAuthException",
"(",
"\"No token file specified\"",
")",
"try",
":",
"with",
"open",
"(",
"self",
".",
"tokenFile",
",",
"\"r\"",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"except",
"OSError",
":",
"raise",
"SkypeAuthException",
"(",
"\"Token file doesn't exist or not readable\"",
")",
"try",
":",
"user",
",",
"skypeToken",
",",
"skypeExpiry",
",",
"regToken",
",",
"regExpiry",
",",
"msgsHost",
"=",
"lines",
"skypeExpiry",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"skypeExpiry",
")",
")",
"regExpiry",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"regExpiry",
")",
")",
"except",
"ValueError",
":",
"raise",
"SkypeAuthException",
"(",
"\"Token file is malformed\"",
")",
"if",
"datetime",
".",
"now",
"(",
")",
">=",
"skypeExpiry",
":",
"raise",
"SkypeAuthException",
"(",
"\"Token file has expired\"",
")",
"self",
".",
"userId",
"=",
"user",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
"=",
"skypeToken",
"self",
".",
"tokenExpiry",
"[",
"\"skype\"",
"]",
"=",
"skypeExpiry",
"if",
"datetime",
".",
"now",
"(",
")",
"<",
"regExpiry",
":",
"self",
".",
"tokens",
"[",
"\"reg\"",
"]",
"=",
"regToken",
"self",
".",
"tokenExpiry",
"[",
"\"reg\"",
"]",
"=",
"regExpiry",
"self",
".",
"msgsHost",
"=",
"msgsHost",
"else",
":",
"self",
".",
"getRegToken",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.writeToken
|
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
|
skpy/conn.py
|
def writeToken(self):
"""
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
"""
# Write token file privately.
with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
# When opening files via os, truncation must be done manually.
f.truncate()
f.write(self.userId + "\n")
f.write(self.tokens["skype"] + "\n")
f.write(str(int(time.mktime(self.tokenExpiry["skype"].timetuple()))) + "\n")
f.write(self.tokens["reg"] + "\n")
f.write(str(int(time.mktime(self.tokenExpiry["reg"].timetuple()))) + "\n")
f.write(self.msgsHost + "\n")
|
def writeToken(self):
"""
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
"""
# Write token file privately.
with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
# When opening files via os, truncation must be done manually.
f.truncate()
f.write(self.userId + "\n")
f.write(self.tokens["skype"] + "\n")
f.write(str(int(time.mktime(self.tokenExpiry["skype"].timetuple()))) + "\n")
f.write(self.tokens["reg"] + "\n")
f.write(str(int(time.mktime(self.tokenExpiry["reg"].timetuple()))) + "\n")
f.write(self.msgsHost + "\n")
|
[
"Store",
"details",
"of",
"the",
"current",
"connection",
"in",
"the",
"named",
"file",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L312-L327
|
[
"def",
"writeToken",
"(",
"self",
")",
":",
"# Write token file privately.",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"self",
".",
"tokenFile",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
",",
"0o600",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"# When opening files via os, truncation must be done manually.",
"f",
".",
"truncate",
"(",
")",
"f",
".",
"write",
"(",
"self",
".",
"userId",
"+",
"\"\\n\"",
")",
"f",
".",
"write",
"(",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
"+",
"\"\\n\"",
")",
"f",
".",
"write",
"(",
"str",
"(",
"int",
"(",
"time",
".",
"mktime",
"(",
"self",
".",
"tokenExpiry",
"[",
"\"skype\"",
"]",
".",
"timetuple",
"(",
")",
")",
")",
")",
"+",
"\"\\n\"",
")",
"f",
".",
"write",
"(",
"self",
".",
"tokens",
"[",
"\"reg\"",
"]",
"+",
"\"\\n\"",
")",
"f",
".",
"write",
"(",
"str",
"(",
"int",
"(",
"time",
".",
"mktime",
"(",
"self",
".",
"tokenExpiry",
"[",
"\"reg\"",
"]",
".",
"timetuple",
"(",
")",
")",
")",
")",
"+",
"\"\\n\"",
")",
"f",
".",
"write",
"(",
"self",
".",
"msgsHost",
"+",
"\"\\n\"",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.verifyToken
|
Ensure the authentication token for the given auth method is still valid.
Args:
auth (Auth): authentication type to check
Raises:
.SkypeAuthException: if Skype auth is required, and the current token has expired and can't be renewed
|
skpy/conn.py
|
def verifyToken(self, auth):
"""
Ensure the authentication token for the given auth method is still valid.
Args:
auth (Auth): authentication type to check
Raises:
.SkypeAuthException: if Skype auth is required, and the current token has expired and can't be renewed
"""
if auth in (self.Auth.SkypeToken, self.Auth.Authorize):
if "skype" not in self.tokenExpiry or datetime.now() >= self.tokenExpiry["skype"]:
if not hasattr(self, "getSkypeToken"):
raise SkypeAuthException("Skype token expired, and no password specified")
self.getSkypeToken()
elif auth == self.Auth.RegToken:
if "reg" not in self.tokenExpiry or datetime.now() >= self.tokenExpiry["reg"]:
self.getRegToken()
|
def verifyToken(self, auth):
"""
Ensure the authentication token for the given auth method is still valid.
Args:
auth (Auth): authentication type to check
Raises:
.SkypeAuthException: if Skype auth is required, and the current token has expired and can't be renewed
"""
if auth in (self.Auth.SkypeToken, self.Auth.Authorize):
if "skype" not in self.tokenExpiry or datetime.now() >= self.tokenExpiry["skype"]:
if not hasattr(self, "getSkypeToken"):
raise SkypeAuthException("Skype token expired, and no password specified")
self.getSkypeToken()
elif auth == self.Auth.RegToken:
if "reg" not in self.tokenExpiry or datetime.now() >= self.tokenExpiry["reg"]:
self.getRegToken()
|
[
"Ensure",
"the",
"authentication",
"token",
"for",
"the",
"given",
"auth",
"method",
"is",
"still",
"valid",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L329-L346
|
[
"def",
"verifyToken",
"(",
"self",
",",
"auth",
")",
":",
"if",
"auth",
"in",
"(",
"self",
".",
"Auth",
".",
"SkypeToken",
",",
"self",
".",
"Auth",
".",
"Authorize",
")",
":",
"if",
"\"skype\"",
"not",
"in",
"self",
".",
"tokenExpiry",
"or",
"datetime",
".",
"now",
"(",
")",
">=",
"self",
".",
"tokenExpiry",
"[",
"\"skype\"",
"]",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"getSkypeToken\"",
")",
":",
"raise",
"SkypeAuthException",
"(",
"\"Skype token expired, and no password specified\"",
")",
"self",
".",
"getSkypeToken",
"(",
")",
"elif",
"auth",
"==",
"self",
".",
"Auth",
".",
"RegToken",
":",
"if",
"\"reg\"",
"not",
"in",
"self",
".",
"tokenExpiry",
"or",
"datetime",
".",
"now",
"(",
")",
">=",
"self",
".",
"tokenExpiry",
"[",
"\"reg\"",
"]",
":",
"self",
".",
"getRegToken",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.liveLogin
|
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft accounts with two-factor authentication enabled are not supported, and will cause a
:class:`.SkypeAuthException` to be raised. See the exception definitions for other possible causes.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def liveLogin(self, user, pwd):
"""
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft accounts with two-factor authentication enabled are not supported, and will cause a
:class:`.SkypeAuthException` to be raised. See the exception definitions for other possible causes.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
self.tokens["skype"], self.tokenExpiry["skype"] = SkypeLiveAuthProvider(self).auth(user, pwd)
self.getUserId()
self.getRegToken()
|
def liveLogin(self, user, pwd):
"""
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft accounts with two-factor authentication enabled are not supported, and will cause a
:class:`.SkypeAuthException` to be raised. See the exception definitions for other possible causes.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
self.tokens["skype"], self.tokenExpiry["skype"] = SkypeLiveAuthProvider(self).auth(user, pwd)
self.getUserId()
self.getRegToken()
|
[
"Obtain",
"connection",
"parameters",
"from",
"the",
"Microsoft",
"account",
"login",
"page",
"and",
"perform",
"a",
"login",
"with",
"the",
"given",
"email",
"address",
"or",
"Skype",
"username",
"and",
"its",
"password",
".",
"This",
"emulates",
"a",
"login",
"to",
"Skype",
"for",
"Web",
"on",
"login",
".",
"live",
".",
"com",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L348-L370
|
[
"def",
"liveLogin",
"(",
"self",
",",
"user",
",",
"pwd",
")",
":",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
",",
"self",
".",
"tokenExpiry",
"[",
"\"skype\"",
"]",
"=",
"SkypeLiveAuthProvider",
"(",
"self",
")",
".",
"auth",
"(",
"user",
",",
"pwd",
")",
"self",
".",
"getUserId",
"(",
")",
"self",
".",
"getRegToken",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.guestLogin
|
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public join URL for conversation, or identifier from it
name (str): display name as shown to other participants
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def guestLogin(self, url, name):
"""
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public join URL for conversation, or identifier from it
name (str): display name as shown to other participants
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
self.tokens["skype"], self.tokenExpiry["skype"] = SkypeGuestAuthProvider(self).auth(url, name)
self.getUserId()
self.getRegToken()
|
def guestLogin(self, url, name):
"""
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public join URL for conversation, or identifier from it
name (str): display name as shown to other participants
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
self.tokens["skype"], self.tokenExpiry["skype"] = SkypeGuestAuthProvider(self).auth(url, name)
self.getUserId()
self.getRegToken()
|
[
"Connect",
"to",
"Skype",
"as",
"a",
"guest",
"joining",
"a",
"given",
"conversation",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L372-L389
|
[
"def",
"guestLogin",
"(",
"self",
",",
"url",
",",
"name",
")",
":",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
",",
"self",
".",
"tokenExpiry",
"[",
"\"skype\"",
"]",
"=",
"SkypeGuestAuthProvider",
"(",
"self",
")",
".",
"auth",
"(",
"url",
",",
"name",
")",
"self",
".",
"getUserId",
"(",
")",
"self",
".",
"getRegToken",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.refreshSkypeToken
|
Take the existing Skype token and refresh it, to extend the expiry time without other credentials.
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def refreshSkypeToken(self):
"""
Take the existing Skype token and refresh it, to extend the expiry time without other credentials.
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
self.tokens["skype"], self.tokenExpiry["skype"] = SkypeRefreshAuthProvider(self).auth(self.tokens["skype"])
self.getRegToken()
|
def refreshSkypeToken(self):
"""
Take the existing Skype token and refresh it, to extend the expiry time without other credentials.
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
self.tokens["skype"], self.tokenExpiry["skype"] = SkypeRefreshAuthProvider(self).auth(self.tokens["skype"])
self.getRegToken()
|
[
"Take",
"the",
"existing",
"Skype",
"token",
"and",
"refresh",
"it",
"to",
"extend",
"the",
"expiry",
"time",
"without",
"other",
"credentials",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L400-L409
|
[
"def",
"refreshSkypeToken",
"(",
"self",
")",
":",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
",",
"self",
".",
"tokenExpiry",
"[",
"\"skype\"",
"]",
"=",
"SkypeRefreshAuthProvider",
"(",
"self",
")",
".",
"auth",
"(",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
")",
"self",
".",
"getRegToken",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.getUserId
|
Ask Skype for the authenticated user's identifier, and store it on the connection object.
|
skpy/conn.py
|
def getUserId(self):
"""
Ask Skype for the authenticated user's identifier, and store it on the connection object.
"""
self.userId = self("GET", "{0}/users/self/profile".format(self.API_USER),
auth=self.Auth.SkypeToken).json().get("username")
|
def getUserId(self):
"""
Ask Skype for the authenticated user's identifier, and store it on the connection object.
"""
self.userId = self("GET", "{0}/users/self/profile".format(self.API_USER),
auth=self.Auth.SkypeToken).json().get("username")
|
[
"Ask",
"Skype",
"for",
"the",
"authenticated",
"user",
"s",
"identifier",
"and",
"store",
"it",
"on",
"the",
"connection",
"object",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L411-L416
|
[
"def",
"getUserId",
"(",
"self",
")",
":",
"self",
".",
"userId",
"=",
"self",
"(",
"\"GET\"",
",",
"\"{0}/users/self/profile\"",
".",
"format",
"(",
"self",
".",
"API_USER",
")",
",",
"auth",
"=",
"self",
".",
"Auth",
".",
"SkypeToken",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"username\"",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.getRegToken
|
Acquire a new registration token.
Once successful, all tokens and expiry times are written to the token file (if specified on initialisation).
|
skpy/conn.py
|
def getRegToken(self):
"""
Acquire a new registration token.
Once successful, all tokens and expiry times are written to the token file (if specified on initialisation).
"""
self.verifyToken(self.Auth.SkypeToken)
token, expiry, msgsHost, endpoint = SkypeRegistrationTokenProvider(self).auth(self.tokens["skype"])
self.tokens["reg"] = token
self.tokenExpiry["reg"] = expiry
self.msgsHost = msgsHost
if endpoint:
endpoint.config()
self.endpoints["main"] = endpoint
self.syncEndpoints()
if self.tokenFile:
self.writeToken()
|
def getRegToken(self):
"""
Acquire a new registration token.
Once successful, all tokens and expiry times are written to the token file (if specified on initialisation).
"""
self.verifyToken(self.Auth.SkypeToken)
token, expiry, msgsHost, endpoint = SkypeRegistrationTokenProvider(self).auth(self.tokens["skype"])
self.tokens["reg"] = token
self.tokenExpiry["reg"] = expiry
self.msgsHost = msgsHost
if endpoint:
endpoint.config()
self.endpoints["main"] = endpoint
self.syncEndpoints()
if self.tokenFile:
self.writeToken()
|
[
"Acquire",
"a",
"new",
"registration",
"token",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L418-L434
|
[
"def",
"getRegToken",
"(",
"self",
")",
":",
"self",
".",
"verifyToken",
"(",
"self",
".",
"Auth",
".",
"SkypeToken",
")",
"token",
",",
"expiry",
",",
"msgsHost",
",",
"endpoint",
"=",
"SkypeRegistrationTokenProvider",
"(",
"self",
")",
".",
"auth",
"(",
"self",
".",
"tokens",
"[",
"\"skype\"",
"]",
")",
"self",
".",
"tokens",
"[",
"\"reg\"",
"]",
"=",
"token",
"self",
".",
"tokenExpiry",
"[",
"\"reg\"",
"]",
"=",
"expiry",
"self",
".",
"msgsHost",
"=",
"msgsHost",
"if",
"endpoint",
":",
"endpoint",
".",
"config",
"(",
")",
"self",
".",
"endpoints",
"[",
"\"main\"",
"]",
"=",
"endpoint",
"self",
".",
"syncEndpoints",
"(",
")",
"if",
"self",
".",
"tokenFile",
":",
"self",
".",
"writeToken",
"(",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeConnection.syncEndpoints
|
Retrieve all current endpoints for the connected user.
|
skpy/conn.py
|
def syncEndpoints(self):
"""
Retrieve all current endpoints for the connected user.
"""
self.endpoints["all"] = []
for json in self("GET", "{0}/users/ME/presenceDocs/messagingService".format(self.msgsHost),
params={"view": "expanded"}, auth=self.Auth.RegToken).json().get("endpointPresenceDocs", []):
id = json.get("link", "").split("/")[7]
self.endpoints["all"].append(SkypeEndpoint(self, id))
|
def syncEndpoints(self):
"""
Retrieve all current endpoints for the connected user.
"""
self.endpoints["all"] = []
for json in self("GET", "{0}/users/ME/presenceDocs/messagingService".format(self.msgsHost),
params={"view": "expanded"}, auth=self.Auth.RegToken).json().get("endpointPresenceDocs", []):
id = json.get("link", "").split("/")[7]
self.endpoints["all"].append(SkypeEndpoint(self, id))
|
[
"Retrieve",
"all",
"current",
"endpoints",
"for",
"the",
"connected",
"user",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L436-L444
|
[
"def",
"syncEndpoints",
"(",
"self",
")",
":",
"self",
".",
"endpoints",
"[",
"\"all\"",
"]",
"=",
"[",
"]",
"for",
"json",
"in",
"self",
"(",
"\"GET\"",
",",
"\"{0}/users/ME/presenceDocs/messagingService\"",
".",
"format",
"(",
"self",
".",
"msgsHost",
")",
",",
"params",
"=",
"{",
"\"view\"",
":",
"\"expanded\"",
"}",
",",
"auth",
"=",
"self",
".",
"Auth",
".",
"RegToken",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"endpointPresenceDocs\"",
",",
"[",
"]",
")",
":",
"id",
"=",
"json",
".",
"get",
"(",
"\"link\"",
",",
"\"\"",
")",
".",
"split",
"(",
"\"/\"",
")",
"[",
"7",
"]",
"self",
".",
"endpoints",
"[",
"\"all\"",
"]",
".",
"append",
"(",
"SkypeEndpoint",
"(",
"self",
",",
"id",
")",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeAPIAuthProvider.auth
|
Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on
``api.skype.com``.
Args:
user (str): username of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def auth(self, user, pwd):
"""
Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on
``api.skype.com``.
Args:
user (str): username of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
# Wrap up the credentials ready to send.
pwdHash = base64.b64encode(hashlib.md5((user + "\nskyper\n" + pwd).encode("utf-8")).digest()).decode("utf-8")
json = self.conn("POST", "{0}/login/skypetoken".format(SkypeConnection.API_USER),
json={"username": user, "passwordHash": pwdHash, "scopes": "client"}).json()
if "skypetoken" not in json:
raise SkypeAuthException("Couldn't retrieve Skype token from response")
expiry = None
if "expiresIn" in json:
expiry = datetime.fromtimestamp(int(time.time()) + int(json["expiresIn"]))
return json["skypetoken"], expiry
|
def auth(self, user, pwd):
"""
Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on
``api.skype.com``.
Args:
user (str): username of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
# Wrap up the credentials ready to send.
pwdHash = base64.b64encode(hashlib.md5((user + "\nskyper\n" + pwd).encode("utf-8")).digest()).decode("utf-8")
json = self.conn("POST", "{0}/login/skypetoken".format(SkypeConnection.API_USER),
json={"username": user, "passwordHash": pwdHash, "scopes": "client"}).json()
if "skypetoken" not in json:
raise SkypeAuthException("Couldn't retrieve Skype token from response")
expiry = None
if "expiresIn" in json:
expiry = datetime.fromtimestamp(int(time.time()) + int(json["expiresIn"]))
return json["skypetoken"], expiry
|
[
"Perform",
"a",
"login",
"with",
"the",
"given",
"Skype",
"username",
"and",
"its",
"password",
".",
"This",
"emulates",
"a",
"login",
"to",
"Skype",
"for",
"Web",
"on",
"api",
".",
"skype",
".",
"com",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L474-L499
|
[
"def",
"auth",
"(",
"self",
",",
"user",
",",
"pwd",
")",
":",
"# Wrap up the credentials ready to send.",
"pwdHash",
"=",
"base64",
".",
"b64encode",
"(",
"hashlib",
".",
"md5",
"(",
"(",
"user",
"+",
"\"\\nskyper\\n\"",
"+",
"pwd",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"json",
"=",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/login/skypetoken\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_USER",
")",
",",
"json",
"=",
"{",
"\"username\"",
":",
"user",
",",
"\"passwordHash\"",
":",
"pwdHash",
",",
"\"scopes\"",
":",
"\"client\"",
"}",
")",
".",
"json",
"(",
")",
"if",
"\"skypetoken\"",
"not",
"in",
"json",
":",
"raise",
"SkypeAuthException",
"(",
"\"Couldn't retrieve Skype token from response\"",
")",
"expiry",
"=",
"None",
"if",
"\"expiresIn\"",
"in",
"json",
":",
"expiry",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"+",
"int",
"(",
"json",
"[",
"\"expiresIn\"",
"]",
")",
")",
"return",
"json",
"[",
"\"skypetoken\"",
"]",
",",
"expiry"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeLiveAuthProvider.checkUser
|
Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists
|
skpy/conn.py
|
def checkUser(self, user):
"""
Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists
"""
return not self.conn("POST", "{0}/GetCredentialType.srf".format(SkypeConnection.API_MSACC),
json={"username": user}).json().get("IfExistsResult")
|
def checkUser(self, user):
"""
Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists
"""
return not self.conn("POST", "{0}/GetCredentialType.srf".format(SkypeConnection.API_MSACC),
json={"username": user}).json().get("IfExistsResult")
|
[
"Query",
"a",
"username",
"or",
"email",
"address",
"to",
"see",
"if",
"a",
"corresponding",
"Microsoft",
"account",
"exists",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L507-L518
|
[
"def",
"checkUser",
"(",
"self",
",",
"user",
")",
":",
"return",
"not",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/GetCredentialType.srf\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_MSACC",
")",
",",
"json",
"=",
"{",
"\"username\"",
":",
"user",
"}",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"IfExistsResult\"",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeLiveAuthProvider.auth
|
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft accounts with two-factor authentication enabled are not supported, and will cause a
:class:`.SkypeAuthException` to be raised. See the exception definitions for other possible causes.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def auth(self, user, pwd):
"""
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft accounts with two-factor authentication enabled are not supported, and will cause a
:class:`.SkypeAuthException` to be raised. See the exception definitions for other possible causes.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
# Do the authentication dance.
params = self.getParams()
t = self.sendCreds(user, pwd, params)
return self.getToken(t)
|
def auth(self, user, pwd):
"""
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft accounts with two-factor authentication enabled are not supported, and will cause a
:class:`.SkypeAuthException` to be raised. See the exception definitions for other possible causes.
Args:
user (str): username or email address of the connecting account
pwd (str): password of the connecting account
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
# Do the authentication dance.
params = self.getParams()
t = self.sendCreds(user, pwd, params)
return self.getToken(t)
|
[
"Obtain",
"connection",
"parameters",
"from",
"the",
"Microsoft",
"account",
"login",
"page",
"and",
"perform",
"a",
"login",
"with",
"the",
"given",
"email",
"address",
"or",
"Skype",
"username",
"and",
"its",
"password",
".",
"This",
"emulates",
"a",
"login",
"to",
"Skype",
"for",
"Web",
"on",
"login",
".",
"live",
".",
"com",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L520-L543
|
[
"def",
"auth",
"(",
"self",
",",
"user",
",",
"pwd",
")",
":",
"# Do the authentication dance.",
"params",
"=",
"self",
".",
"getParams",
"(",
")",
"t",
"=",
"self",
".",
"sendCreds",
"(",
"user",
",",
"pwd",
",",
"params",
")",
"return",
"self",
".",
"getToken",
"(",
"t",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeGuestAuthProvider.auth
|
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public join URL for conversation, or identifier from it
name (str): display name as shown to other participants
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def auth(self, url, name):
"""
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public join URL for conversation, or identifier from it
name (str): display name as shown to other participants
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
urlId = url.split("/")[-1]
# Pretend to be Chrome on Windows (required to avoid "unsupported device" messages).
agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " \
"Chrome/33.0.1750.117 Safari/537.36"
cookies = self.conn("GET", "{0}/{1}".format(SkypeConnection.API_JOIN, urlId),
headers={"User-Agent": agent}).cookies
ids = self.conn("POST", "{0}/api/v2/conversation/".format(SkypeConnection.API_JOIN),
json={"shortId": urlId, "type": "wl"}).json()
token = self.conn("POST", "{0}/api/v1/users/guests".format(SkypeConnection.API_JOIN),
headers={"csrf_token": cookies.get("csrf_token"),
"X-Skype-Request-Id": cookies.get("launcher_session_id")},
json={"flowId": cookies.get("launcher_session_id"),
"shortId": urlId,
"longId": ids.get("Long"),
"threadId": ids.get("Resource"),
"name": name}).json().get("skypetoken")
# Assume the token lasts 24 hours, as a guest account only lasts that long anyway.
expiry = datetime.now() + timedelta(days=1)
return token, expiry
|
def auth(self, url, name):
"""
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public join URL for conversation, or identifier from it
name (str): display name as shown to other participants
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
urlId = url.split("/")[-1]
# Pretend to be Chrome on Windows (required to avoid "unsupported device" messages).
agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " \
"Chrome/33.0.1750.117 Safari/537.36"
cookies = self.conn("GET", "{0}/{1}".format(SkypeConnection.API_JOIN, urlId),
headers={"User-Agent": agent}).cookies
ids = self.conn("POST", "{0}/api/v2/conversation/".format(SkypeConnection.API_JOIN),
json={"shortId": urlId, "type": "wl"}).json()
token = self.conn("POST", "{0}/api/v1/users/guests".format(SkypeConnection.API_JOIN),
headers={"csrf_token": cookies.get("csrf_token"),
"X-Skype-Request-Id": cookies.get("launcher_session_id")},
json={"flowId": cookies.get("launcher_session_id"),
"shortId": urlId,
"longId": ids.get("Long"),
"threadId": ids.get("Resource"),
"name": name}).json().get("skypetoken")
# Assume the token lasts 24 hours, as a guest account only lasts that long anyway.
expiry = datetime.now() + timedelta(days=1)
return token, expiry
|
[
"Connect",
"to",
"Skype",
"as",
"a",
"guest",
"joining",
"a",
"given",
"conversation",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L602-L638
|
[
"def",
"auth",
"(",
"self",
",",
"url",
",",
"name",
")",
":",
"urlId",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"# Pretend to be Chrome on Windows (required to avoid \"unsupported device\" messages).",
"agent",
"=",
"\"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \"",
"\"Chrome/33.0.1750.117 Safari/537.36\"",
"cookies",
"=",
"self",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/{1}\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_JOIN",
",",
"urlId",
")",
",",
"headers",
"=",
"{",
"\"User-Agent\"",
":",
"agent",
"}",
")",
".",
"cookies",
"ids",
"=",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/api/v2/conversation/\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_JOIN",
")",
",",
"json",
"=",
"{",
"\"shortId\"",
":",
"urlId",
",",
"\"type\"",
":",
"\"wl\"",
"}",
")",
".",
"json",
"(",
")",
"token",
"=",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/api/v1/users/guests\"",
".",
"format",
"(",
"SkypeConnection",
".",
"API_JOIN",
")",
",",
"headers",
"=",
"{",
"\"csrf_token\"",
":",
"cookies",
".",
"get",
"(",
"\"csrf_token\"",
")",
",",
"\"X-Skype-Request-Id\"",
":",
"cookies",
".",
"get",
"(",
"\"launcher_session_id\"",
")",
"}",
",",
"json",
"=",
"{",
"\"flowId\"",
":",
"cookies",
".",
"get",
"(",
"\"launcher_session_id\"",
")",
",",
"\"shortId\"",
":",
"urlId",
",",
"\"longId\"",
":",
"ids",
".",
"get",
"(",
"\"Long\"",
")",
",",
"\"threadId\"",
":",
"ids",
".",
"get",
"(",
"\"Resource\"",
")",
",",
"\"name\"",
":",
"name",
"}",
")",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"skypetoken\"",
")",
"# Assume the token lasts 24 hours, as a guest account only lasts that long anyway.",
"expiry",
"=",
"datetime",
".",
"now",
"(",
")",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
"return",
"token",
",",
"expiry"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeRefreshAuthProvider.auth
|
Take an existing Skype token and refresh it, to extend the expiry time without other credentials.
Args:
token (str): existing Skype token
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def auth(self, token):
"""
Take an existing Skype token and refresh it, to extend the expiry time without other credentials.
Args:
token (str): existing Skype token
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
t = self.sendToken(token)
return self.getToken(t)
|
def auth(self, token):
"""
Take an existing Skype token and refresh it, to extend the expiry time without other credentials.
Args:
token (str): existing Skype token
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
t = self.sendToken(token)
return self.getToken(t)
|
[
"Take",
"an",
"existing",
"Skype",
"token",
"and",
"refresh",
"it",
"to",
"extend",
"the",
"expiry",
"time",
"without",
"other",
"credentials",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L646-L661
|
[
"def",
"auth",
"(",
"self",
",",
"token",
")",
":",
"t",
"=",
"self",
".",
"sendToken",
"(",
"token",
")",
"return",
"self",
".",
"getToken",
"(",
"t",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeRegistrationTokenProvider.auth
|
Request a new registration token using a current Skype token.
Args:
skypeToken (str): existing Skype token
Returns:
(str, datetime.datetime, str, SkypeEndpoint) tuple: registration token, associated expiry if known,
resulting endpoint hostname, endpoint if provided
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
|
skpy/conn.py
|
def auth(self, skypeToken):
"""
Request a new registration token using a current Skype token.
Args:
skypeToken (str): existing Skype token
Returns:
(str, datetime.datetime, str, SkypeEndpoint) tuple: registration token, associated expiry if known,
resulting endpoint hostname, endpoint if provided
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
token = expiry = endpoint = None
msgsHost = SkypeConnection.API_MSGSHOST
while not token:
secs = int(time.time())
hash = self.getMac256Hash(str(secs))
headers = {"LockAndKey": "appId=msmsgs@msnmsgr.com; time={0}; lockAndKeyResponse={1}".format(secs, hash),
"Authentication": "skypetoken=" + skypeToken, "BehaviorOverride": "redirectAs404"}
endpointResp = self.conn("POST", "{0}/users/ME/endpoints".format(msgsHost), codes=(200, 201, 404),
headers=headers, json={"endpointFeatures": "Agent"})
regTokenHead = endpointResp.headers.get("Set-RegistrationToken")
locHead = endpointResp.headers.get("Location")
if locHead:
locParts = re.search(r"(https://[^/]+/v1)/users/ME/endpoints(/(%7B[a-z0-9\-]+%7D))?", locHead).groups()
if locParts[2]:
endpoint = SkypeEndpoint(self.conn, locParts[2].replace("%7B", "{").replace("%7D", "}"))
if not locParts[0] == msgsHost:
# Skype is requiring the use of a different hostname.
msgsHost = locHead.rsplit("/", 4 if locParts[2] else 3)[0]
# Don't accept the token if present, we need to re-register first.
continue
if regTokenHead:
token = re.search(r"(registrationToken=[a-z0-9\+/=]+)", regTokenHead, re.I).group(1)
regExpiry = re.search(r"expires=(\d+)", regTokenHead).group(1)
expiry = datetime.fromtimestamp(int(regExpiry))
regEndMatch = re.search(r"endpointId=({[a-z0-9\-]+})", regTokenHead)
if regEndMatch:
endpoint = SkypeEndpoint(self.conn, regEndMatch.group(1))
if not endpoint and endpointResp.status_code == 200 and endpointResp.json():
# Use the most recent endpoint listed in the JSON response.
endpoint = SkypeEndpoint(self.conn, endpointResp.json()[0]["id"])
return token, expiry, msgsHost, endpoint
|
def auth(self, skypeToken):
"""
Request a new registration token using a current Skype token.
Args:
skypeToken (str): existing Skype token
Returns:
(str, datetime.datetime, str, SkypeEndpoint) tuple: registration token, associated expiry if known,
resulting endpoint hostname, endpoint if provided
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
token = expiry = endpoint = None
msgsHost = SkypeConnection.API_MSGSHOST
while not token:
secs = int(time.time())
hash = self.getMac256Hash(str(secs))
headers = {"LockAndKey": "appId=msmsgs@msnmsgr.com; time={0}; lockAndKeyResponse={1}".format(secs, hash),
"Authentication": "skypetoken=" + skypeToken, "BehaviorOverride": "redirectAs404"}
endpointResp = self.conn("POST", "{0}/users/ME/endpoints".format(msgsHost), codes=(200, 201, 404),
headers=headers, json={"endpointFeatures": "Agent"})
regTokenHead = endpointResp.headers.get("Set-RegistrationToken")
locHead = endpointResp.headers.get("Location")
if locHead:
locParts = re.search(r"(https://[^/]+/v1)/users/ME/endpoints(/(%7B[a-z0-9\-]+%7D))?", locHead).groups()
if locParts[2]:
endpoint = SkypeEndpoint(self.conn, locParts[2].replace("%7B", "{").replace("%7D", "}"))
if not locParts[0] == msgsHost:
# Skype is requiring the use of a different hostname.
msgsHost = locHead.rsplit("/", 4 if locParts[2] else 3)[0]
# Don't accept the token if present, we need to re-register first.
continue
if regTokenHead:
token = re.search(r"(registrationToken=[a-z0-9\+/=]+)", regTokenHead, re.I).group(1)
regExpiry = re.search(r"expires=(\d+)", regTokenHead).group(1)
expiry = datetime.fromtimestamp(int(regExpiry))
regEndMatch = re.search(r"endpointId=({[a-z0-9\-]+})", regTokenHead)
if regEndMatch:
endpoint = SkypeEndpoint(self.conn, regEndMatch.group(1))
if not endpoint and endpointResp.status_code == 200 and endpointResp.json():
# Use the most recent endpoint listed in the JSON response.
endpoint = SkypeEndpoint(self.conn, endpointResp.json()[0]["id"])
return token, expiry, msgsHost, endpoint
|
[
"Request",
"a",
"new",
"registration",
"token",
"using",
"a",
"current",
"Skype",
"token",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L701-L746
|
[
"def",
"auth",
"(",
"self",
",",
"skypeToken",
")",
":",
"token",
"=",
"expiry",
"=",
"endpoint",
"=",
"None",
"msgsHost",
"=",
"SkypeConnection",
".",
"API_MSGSHOST",
"while",
"not",
"token",
":",
"secs",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"hash",
"=",
"self",
".",
"getMac256Hash",
"(",
"str",
"(",
"secs",
")",
")",
"headers",
"=",
"{",
"\"LockAndKey\"",
":",
"\"appId=msmsgs@msnmsgr.com; time={0}; lockAndKeyResponse={1}\"",
".",
"format",
"(",
"secs",
",",
"hash",
")",
",",
"\"Authentication\"",
":",
"\"skypetoken=\"",
"+",
"skypeToken",
",",
"\"BehaviorOverride\"",
":",
"\"redirectAs404\"",
"}",
"endpointResp",
"=",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/ME/endpoints\"",
".",
"format",
"(",
"msgsHost",
")",
",",
"codes",
"=",
"(",
"200",
",",
"201",
",",
"404",
")",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"{",
"\"endpointFeatures\"",
":",
"\"Agent\"",
"}",
")",
"regTokenHead",
"=",
"endpointResp",
".",
"headers",
".",
"get",
"(",
"\"Set-RegistrationToken\"",
")",
"locHead",
"=",
"endpointResp",
".",
"headers",
".",
"get",
"(",
"\"Location\"",
")",
"if",
"locHead",
":",
"locParts",
"=",
"re",
".",
"search",
"(",
"r\"(https://[^/]+/v1)/users/ME/endpoints(/(%7B[a-z0-9\\-]+%7D))?\"",
",",
"locHead",
")",
".",
"groups",
"(",
")",
"if",
"locParts",
"[",
"2",
"]",
":",
"endpoint",
"=",
"SkypeEndpoint",
"(",
"self",
".",
"conn",
",",
"locParts",
"[",
"2",
"]",
".",
"replace",
"(",
"\"%7B\"",
",",
"\"{\"",
")",
".",
"replace",
"(",
"\"%7D\"",
",",
"\"}\"",
")",
")",
"if",
"not",
"locParts",
"[",
"0",
"]",
"==",
"msgsHost",
":",
"# Skype is requiring the use of a different hostname.",
"msgsHost",
"=",
"locHead",
".",
"rsplit",
"(",
"\"/\"",
",",
"4",
"if",
"locParts",
"[",
"2",
"]",
"else",
"3",
")",
"[",
"0",
"]",
"# Don't accept the token if present, we need to re-register first.",
"continue",
"if",
"regTokenHead",
":",
"token",
"=",
"re",
".",
"search",
"(",
"r\"(registrationToken=[a-z0-9\\+/=]+)\"",
",",
"regTokenHead",
",",
"re",
".",
"I",
")",
".",
"group",
"(",
"1",
")",
"regExpiry",
"=",
"re",
".",
"search",
"(",
"r\"expires=(\\d+)\"",
",",
"regTokenHead",
")",
".",
"group",
"(",
"1",
")",
"expiry",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"regExpiry",
")",
")",
"regEndMatch",
"=",
"re",
".",
"search",
"(",
"r\"endpointId=({[a-z0-9\\-]+})\"",
",",
"regTokenHead",
")",
"if",
"regEndMatch",
":",
"endpoint",
"=",
"SkypeEndpoint",
"(",
"self",
".",
"conn",
",",
"regEndMatch",
".",
"group",
"(",
"1",
")",
")",
"if",
"not",
"endpoint",
"and",
"endpointResp",
".",
"status_code",
"==",
"200",
"and",
"endpointResp",
".",
"json",
"(",
")",
":",
"# Use the most recent endpoint listed in the JSON response.",
"endpoint",
"=",
"SkypeEndpoint",
"(",
"self",
".",
"conn",
",",
"endpointResp",
".",
"json",
"(",
")",
"[",
"0",
"]",
"[",
"\"id\"",
"]",
")",
"return",
"token",
",",
"expiry",
",",
"msgsHost",
",",
"endpoint"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeRegistrationTokenProvider.getMac256Hash
|
Generate the lock-and-key response, needed to acquire registration tokens.
|
skpy/conn.py
|
def getMac256Hash(challenge, appId="msmsgs@msnmsgr.com", key="Q1P7W2E4J9R8U3S5"):
"""
Generate the lock-and-key response, needed to acquire registration tokens.
"""
clearText = challenge + appId
clearText += "0" * (8 - len(clearText) % 8)
def int32ToHexString(n):
hexChars = "0123456789abcdef"
hexString = ""
for i in range(4):
hexString += hexChars[(n >> (i * 8 + 4)) & 15]
hexString += hexChars[(n >> (i * 8)) & 15]
return hexString
def int64Xor(a, b):
sA = "{0:b}".format(a)
sB = "{0:b}".format(b)
sC = ""
sD = ""
diff = abs(len(sA) - len(sB))
for i in range(diff):
sD += "0"
if len(sA) < len(sB):
sD += sA
sA = sD
elif len(sB) < len(sA):
sD += sB
sB = sD
for i in range(len(sA)):
sC += "0" if sA[i] == sB[i] else "1"
return int(sC, 2)
def cS64(pdwData, pInHash):
MODULUS = 2147483647
CS64_a = pInHash[0] & MODULUS
CS64_b = pInHash[1] & MODULUS
CS64_c = pInHash[2] & MODULUS
CS64_d = pInHash[3] & MODULUS
CS64_e = 242854337
pos = 0
qwDatum = 0
qwMAC = 0
qwSum = 0
for i in range(len(pdwData) // 2):
qwDatum = int(pdwData[pos])
pos += 1
qwDatum *= CS64_e
qwDatum = qwDatum % MODULUS
qwMAC += qwDatum
qwMAC *= CS64_a
qwMAC += CS64_b
qwMAC = qwMAC % MODULUS
qwSum += qwMAC
qwMAC += int(pdwData[pos])
pos += 1
qwMAC *= CS64_c
qwMAC += CS64_d
qwMAC = qwMAC % MODULUS
qwSum += qwMAC
qwMAC += CS64_b
qwMAC = qwMAC % MODULUS
qwSum += CS64_d
qwSum = qwSum % MODULUS
return [qwMAC, qwSum]
cchClearText = len(clearText) // 4
pClearText = []
for i in range(cchClearText):
pClearText = pClearText[:i] + [0] + pClearText[i:]
for pos in range(4):
pClearText[i] += ord(clearText[4 * i + pos]) * (256 ** pos)
sha256Hash = [0, 0, 0, 0]
hash = hashlib.sha256((challenge + key).encode("utf-8")).hexdigest().upper()
for i in range(len(sha256Hash)):
sha256Hash[i] = 0
for pos in range(4):
dpos = 8 * i + pos * 2
sha256Hash[i] += int(hash[dpos:dpos + 2], 16) * (256 ** pos)
macHash = cS64(pClearText, sha256Hash)
macParts = [macHash[0], macHash[1], macHash[0], macHash[1]]
return "".join(map(int32ToHexString, map(int64Xor, sha256Hash, macParts)))
|
def getMac256Hash(challenge, appId="msmsgs@msnmsgr.com", key="Q1P7W2E4J9R8U3S5"):
"""
Generate the lock-and-key response, needed to acquire registration tokens.
"""
clearText = challenge + appId
clearText += "0" * (8 - len(clearText) % 8)
def int32ToHexString(n):
hexChars = "0123456789abcdef"
hexString = ""
for i in range(4):
hexString += hexChars[(n >> (i * 8 + 4)) & 15]
hexString += hexChars[(n >> (i * 8)) & 15]
return hexString
def int64Xor(a, b):
sA = "{0:b}".format(a)
sB = "{0:b}".format(b)
sC = ""
sD = ""
diff = abs(len(sA) - len(sB))
for i in range(diff):
sD += "0"
if len(sA) < len(sB):
sD += sA
sA = sD
elif len(sB) < len(sA):
sD += sB
sB = sD
for i in range(len(sA)):
sC += "0" if sA[i] == sB[i] else "1"
return int(sC, 2)
def cS64(pdwData, pInHash):
MODULUS = 2147483647
CS64_a = pInHash[0] & MODULUS
CS64_b = pInHash[1] & MODULUS
CS64_c = pInHash[2] & MODULUS
CS64_d = pInHash[3] & MODULUS
CS64_e = 242854337
pos = 0
qwDatum = 0
qwMAC = 0
qwSum = 0
for i in range(len(pdwData) // 2):
qwDatum = int(pdwData[pos])
pos += 1
qwDatum *= CS64_e
qwDatum = qwDatum % MODULUS
qwMAC += qwDatum
qwMAC *= CS64_a
qwMAC += CS64_b
qwMAC = qwMAC % MODULUS
qwSum += qwMAC
qwMAC += int(pdwData[pos])
pos += 1
qwMAC *= CS64_c
qwMAC += CS64_d
qwMAC = qwMAC % MODULUS
qwSum += qwMAC
qwMAC += CS64_b
qwMAC = qwMAC % MODULUS
qwSum += CS64_d
qwSum = qwSum % MODULUS
return [qwMAC, qwSum]
cchClearText = len(clearText) // 4
pClearText = []
for i in range(cchClearText):
pClearText = pClearText[:i] + [0] + pClearText[i:]
for pos in range(4):
pClearText[i] += ord(clearText[4 * i + pos]) * (256 ** pos)
sha256Hash = [0, 0, 0, 0]
hash = hashlib.sha256((challenge + key).encode("utf-8")).hexdigest().upper()
for i in range(len(sha256Hash)):
sha256Hash[i] = 0
for pos in range(4):
dpos = 8 * i + pos * 2
sha256Hash[i] += int(hash[dpos:dpos + 2], 16) * (256 ** pos)
macHash = cS64(pClearText, sha256Hash)
macParts = [macHash[0], macHash[1], macHash[0], macHash[1]]
return "".join(map(int32ToHexString, map(int64Xor, sha256Hash, macParts)))
|
[
"Generate",
"the",
"lock",
"-",
"and",
"-",
"key",
"response",
"needed",
"to",
"acquire",
"registration",
"tokens",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L749-L830
|
[
"def",
"getMac256Hash",
"(",
"challenge",
",",
"appId",
"=",
"\"msmsgs@msnmsgr.com\"",
",",
"key",
"=",
"\"Q1P7W2E4J9R8U3S5\"",
")",
":",
"clearText",
"=",
"challenge",
"+",
"appId",
"clearText",
"+=",
"\"0\"",
"*",
"(",
"8",
"-",
"len",
"(",
"clearText",
")",
"%",
"8",
")",
"def",
"int32ToHexString",
"(",
"n",
")",
":",
"hexChars",
"=",
"\"0123456789abcdef\"",
"hexString",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"hexString",
"+=",
"hexChars",
"[",
"(",
"n",
">>",
"(",
"i",
"*",
"8",
"+",
"4",
")",
")",
"&",
"15",
"]",
"hexString",
"+=",
"hexChars",
"[",
"(",
"n",
">>",
"(",
"i",
"*",
"8",
")",
")",
"&",
"15",
"]",
"return",
"hexString",
"def",
"int64Xor",
"(",
"a",
",",
"b",
")",
":",
"sA",
"=",
"\"{0:b}\"",
".",
"format",
"(",
"a",
")",
"sB",
"=",
"\"{0:b}\"",
".",
"format",
"(",
"b",
")",
"sC",
"=",
"\"\"",
"sD",
"=",
"\"\"",
"diff",
"=",
"abs",
"(",
"len",
"(",
"sA",
")",
"-",
"len",
"(",
"sB",
")",
")",
"for",
"i",
"in",
"range",
"(",
"diff",
")",
":",
"sD",
"+=",
"\"0\"",
"if",
"len",
"(",
"sA",
")",
"<",
"len",
"(",
"sB",
")",
":",
"sD",
"+=",
"sA",
"sA",
"=",
"sD",
"elif",
"len",
"(",
"sB",
")",
"<",
"len",
"(",
"sA",
")",
":",
"sD",
"+=",
"sB",
"sB",
"=",
"sD",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sA",
")",
")",
":",
"sC",
"+=",
"\"0\"",
"if",
"sA",
"[",
"i",
"]",
"==",
"sB",
"[",
"i",
"]",
"else",
"\"1\"",
"return",
"int",
"(",
"sC",
",",
"2",
")",
"def",
"cS64",
"(",
"pdwData",
",",
"pInHash",
")",
":",
"MODULUS",
"=",
"2147483647",
"CS64_a",
"=",
"pInHash",
"[",
"0",
"]",
"&",
"MODULUS",
"CS64_b",
"=",
"pInHash",
"[",
"1",
"]",
"&",
"MODULUS",
"CS64_c",
"=",
"pInHash",
"[",
"2",
"]",
"&",
"MODULUS",
"CS64_d",
"=",
"pInHash",
"[",
"3",
"]",
"&",
"MODULUS",
"CS64_e",
"=",
"242854337",
"pos",
"=",
"0",
"qwDatum",
"=",
"0",
"qwMAC",
"=",
"0",
"qwSum",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"pdwData",
")",
"//",
"2",
")",
":",
"qwDatum",
"=",
"int",
"(",
"pdwData",
"[",
"pos",
"]",
")",
"pos",
"+=",
"1",
"qwDatum",
"*=",
"CS64_e",
"qwDatum",
"=",
"qwDatum",
"%",
"MODULUS",
"qwMAC",
"+=",
"qwDatum",
"qwMAC",
"*=",
"CS64_a",
"qwMAC",
"+=",
"CS64_b",
"qwMAC",
"=",
"qwMAC",
"%",
"MODULUS",
"qwSum",
"+=",
"qwMAC",
"qwMAC",
"+=",
"int",
"(",
"pdwData",
"[",
"pos",
"]",
")",
"pos",
"+=",
"1",
"qwMAC",
"*=",
"CS64_c",
"qwMAC",
"+=",
"CS64_d",
"qwMAC",
"=",
"qwMAC",
"%",
"MODULUS",
"qwSum",
"+=",
"qwMAC",
"qwMAC",
"+=",
"CS64_b",
"qwMAC",
"=",
"qwMAC",
"%",
"MODULUS",
"qwSum",
"+=",
"CS64_d",
"qwSum",
"=",
"qwSum",
"%",
"MODULUS",
"return",
"[",
"qwMAC",
",",
"qwSum",
"]",
"cchClearText",
"=",
"len",
"(",
"clearText",
")",
"//",
"4",
"pClearText",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"cchClearText",
")",
":",
"pClearText",
"=",
"pClearText",
"[",
":",
"i",
"]",
"+",
"[",
"0",
"]",
"+",
"pClearText",
"[",
"i",
":",
"]",
"for",
"pos",
"in",
"range",
"(",
"4",
")",
":",
"pClearText",
"[",
"i",
"]",
"+=",
"ord",
"(",
"clearText",
"[",
"4",
"*",
"i",
"+",
"pos",
"]",
")",
"*",
"(",
"256",
"**",
"pos",
")",
"sha256Hash",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"hash",
"=",
"hashlib",
".",
"sha256",
"(",
"(",
"challenge",
"+",
"key",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
".",
"upper",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sha256Hash",
")",
")",
":",
"sha256Hash",
"[",
"i",
"]",
"=",
"0",
"for",
"pos",
"in",
"range",
"(",
"4",
")",
":",
"dpos",
"=",
"8",
"*",
"i",
"+",
"pos",
"*",
"2",
"sha256Hash",
"[",
"i",
"]",
"+=",
"int",
"(",
"hash",
"[",
"dpos",
":",
"dpos",
"+",
"2",
"]",
",",
"16",
")",
"*",
"(",
"256",
"**",
"pos",
")",
"macHash",
"=",
"cS64",
"(",
"pClearText",
",",
"sha256Hash",
")",
"macParts",
"=",
"[",
"macHash",
"[",
"0",
"]",
",",
"macHash",
"[",
"1",
"]",
",",
"macHash",
"[",
"0",
"]",
",",
"macHash",
"[",
"1",
"]",
"]",
"return",
"\"\"",
".",
"join",
"(",
"map",
"(",
"int32ToHexString",
",",
"map",
"(",
"int64Xor",
",",
"sha256Hash",
",",
"macParts",
")",
")",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeEndpoint.config
|
Configure this endpoint to allow setting presence.
Args:
name (str): display name for this endpoint
|
skpy/conn.py
|
def config(self, name="skype"):
"""
Configure this endpoint to allow setting presence.
Args:
name (str): display name for this endpoint
"""
self.conn("PUT", "{0}/users/ME/endpoints/{1}/presenceDocs/messagingService"
.format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken,
json={"id": "messagingService",
"type": "EndpointPresenceDoc",
"selfLink": "uri",
"privateInfo": {"epname": name},
"publicInfo": {"capabilities": "",
"type": 1,
"skypeNameVersion": "skype.com",
"nodeInfo": "xx",
"version": "908/1.30.0.128"}})
|
def config(self, name="skype"):
"""
Configure this endpoint to allow setting presence.
Args:
name (str): display name for this endpoint
"""
self.conn("PUT", "{0}/users/ME/endpoints/{1}/presenceDocs/messagingService"
.format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken,
json={"id": "messagingService",
"type": "EndpointPresenceDoc",
"selfLink": "uri",
"privateInfo": {"epname": name},
"publicInfo": {"capabilities": "",
"type": 1,
"skypeNameVersion": "skype.com",
"nodeInfo": "xx",
"version": "908/1.30.0.128"}})
|
[
"Configure",
"this",
"endpoint",
"to",
"allow",
"setting",
"presence",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L857-L875
|
[
"def",
"config",
"(",
"self",
",",
"name",
"=",
"\"skype\"",
")",
":",
"self",
".",
"conn",
"(",
"\"PUT\"",
",",
"\"{0}/users/ME/endpoints/{1}/presenceDocs/messagingService\"",
".",
"format",
"(",
"self",
".",
"conn",
".",
"msgsHost",
",",
"self",
".",
"id",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"json",
"=",
"{",
"\"id\"",
":",
"\"messagingService\"",
",",
"\"type\"",
":",
"\"EndpointPresenceDoc\"",
",",
"\"selfLink\"",
":",
"\"uri\"",
",",
"\"privateInfo\"",
":",
"{",
"\"epname\"",
":",
"name",
"}",
",",
"\"publicInfo\"",
":",
"{",
"\"capabilities\"",
":",
"\"\"",
",",
"\"type\"",
":",
"1",
",",
"\"skypeNameVersion\"",
":",
"\"skype.com\"",
",",
"\"nodeInfo\"",
":",
"\"xx\"",
",",
"\"version\"",
":",
"\"908/1.30.0.128\"",
"}",
"}",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeEndpoint.ping
|
Send a keep-alive request for the endpoint.
Args:
timeout (int): maximum amount of time for the endpoint to stay active
|
skpy/conn.py
|
def ping(self, timeout=12):
"""
Send a keep-alive request for the endpoint.
Args:
timeout (int): maximum amount of time for the endpoint to stay active
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/active".format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken, json={"timeout": timeout})
|
def ping(self, timeout=12):
"""
Send a keep-alive request for the endpoint.
Args:
timeout (int): maximum amount of time for the endpoint to stay active
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/active".format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken, json={"timeout": timeout})
|
[
"Send",
"a",
"keep",
"-",
"alive",
"request",
"for",
"the",
"endpoint",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L877-L885
|
[
"def",
"ping",
"(",
"self",
",",
"timeout",
"=",
"12",
")",
":",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/ME/endpoints/{1}/active\"",
".",
"format",
"(",
"self",
".",
"conn",
".",
"msgsHost",
",",
"self",
".",
"id",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"json",
"=",
"{",
"\"timeout\"",
":",
"timeout",
"}",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeEndpoint.subscribe
|
Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`.
|
skpy/conn.py
|
def subscribe(self):
"""
Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`.
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/subscriptions".format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken,
json={"interestedResources": ["/v1/threads/ALL",
"/v1/users/ME/contacts/ALL",
"/v1/users/ME/conversations/ALL/messages",
"/v1/users/ME/conversations/ALL/properties"],
"template": "raw",
"channelType": "httpLongPoll"})
self.subscribed = True
|
def subscribe(self):
"""
Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`.
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/subscriptions".format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken,
json={"interestedResources": ["/v1/threads/ALL",
"/v1/users/ME/contacts/ALL",
"/v1/users/ME/conversations/ALL/messages",
"/v1/users/ME/conversations/ALL/properties"],
"template": "raw",
"channelType": "httpLongPoll"})
self.subscribed = True
|
[
"Subscribe",
"to",
"contact",
"and",
"conversation",
"events",
".",
"These",
"are",
"accessible",
"through",
":",
"meth",
":",
"getEvents",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L887-L899
|
[
"def",
"subscribe",
"(",
"self",
")",
":",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/ME/endpoints/{1}/subscriptions\"",
".",
"format",
"(",
"self",
".",
"conn",
".",
"msgsHost",
",",
"self",
".",
"id",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"json",
"=",
"{",
"\"interestedResources\"",
":",
"[",
"\"/v1/threads/ALL\"",
",",
"\"/v1/users/ME/contacts/ALL\"",
",",
"\"/v1/users/ME/conversations/ALL/messages\"",
",",
"\"/v1/users/ME/conversations/ALL/properties\"",
"]",
",",
"\"template\"",
":",
"\"raw\"",
",",
"\"channelType\"",
":",
"\"httpLongPoll\"",
"}",
")",
"self",
".",
"subscribed",
"=",
"True"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeChats.recent
|
Retrieve a selection of conversations with the most recent activity, and store them in the cache.
Each conversation is only retrieved once, so subsequent calls will retrieve older conversations.
Returns:
:class:`SkypeChat` list: collection of recent conversations
|
skpy/chat.py
|
def recent(self):
"""
Retrieve a selection of conversations with the most recent activity, and store them in the cache.
Each conversation is only retrieved once, so subsequent calls will retrieve older conversations.
Returns:
:class:`SkypeChat` list: collection of recent conversations
"""
url = "{0}/users/ME/conversations".format(self.skype.conn.msgsHost)
params = {"startTime": 0,
"view": "msnp24Equivalent",
"targetType": "Passport|Skype|Lync|Thread"}
resp = self.skype.conn.syncStateCall("GET", url, params, auth=SkypeConnection.Auth.RegToken).json()
chats = {}
for json in resp.get("conversations", []):
cls = SkypeSingleChat
if "threadProperties" in json:
info = self.skype.conn("GET", "{0}/threads/{1}".format(self.skype.conn.msgsHost, json.get("id")),
auth=SkypeConnection.Auth.RegToken,
params={"view": "msnp24Equivalent"}).json()
json.update(info)
cls = SkypeGroupChat
chats[json.get("id")] = self.merge(cls.fromRaw(self.skype, json))
return chats
|
def recent(self):
"""
Retrieve a selection of conversations with the most recent activity, and store them in the cache.
Each conversation is only retrieved once, so subsequent calls will retrieve older conversations.
Returns:
:class:`SkypeChat` list: collection of recent conversations
"""
url = "{0}/users/ME/conversations".format(self.skype.conn.msgsHost)
params = {"startTime": 0,
"view": "msnp24Equivalent",
"targetType": "Passport|Skype|Lync|Thread"}
resp = self.skype.conn.syncStateCall("GET", url, params, auth=SkypeConnection.Auth.RegToken).json()
chats = {}
for json in resp.get("conversations", []):
cls = SkypeSingleChat
if "threadProperties" in json:
info = self.skype.conn("GET", "{0}/threads/{1}".format(self.skype.conn.msgsHost, json.get("id")),
auth=SkypeConnection.Auth.RegToken,
params={"view": "msnp24Equivalent"}).json()
json.update(info)
cls = SkypeGroupChat
chats[json.get("id")] = self.merge(cls.fromRaw(self.skype, json))
return chats
|
[
"Retrieve",
"a",
"selection",
"of",
"conversations",
"with",
"the",
"most",
"recent",
"activity",
"and",
"store",
"them",
"in",
"the",
"cache",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/chat.py#L397-L421
|
[
"def",
"recent",
"(",
"self",
")",
":",
"url",
"=",
"\"{0}/users/ME/conversations\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"conn",
".",
"msgsHost",
")",
"params",
"=",
"{",
"\"startTime\"",
":",
"0",
",",
"\"view\"",
":",
"\"msnp24Equivalent\"",
",",
"\"targetType\"",
":",
"\"Passport|Skype|Lync|Thread\"",
"}",
"resp",
"=",
"self",
".",
"skype",
".",
"conn",
".",
"syncStateCall",
"(",
"\"GET\"",
",",
"url",
",",
"params",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
")",
".",
"json",
"(",
")",
"chats",
"=",
"{",
"}",
"for",
"json",
"in",
"resp",
".",
"get",
"(",
"\"conversations\"",
",",
"[",
"]",
")",
":",
"cls",
"=",
"SkypeSingleChat",
"if",
"\"threadProperties\"",
"in",
"json",
":",
"info",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/threads/{1}\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"conn",
".",
"msgsHost",
",",
"json",
".",
"get",
"(",
"\"id\"",
")",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"params",
"=",
"{",
"\"view\"",
":",
"\"msnp24Equivalent\"",
"}",
")",
".",
"json",
"(",
")",
"json",
".",
"update",
"(",
"info",
")",
"cls",
"=",
"SkypeGroupChat",
"chats",
"[",
"json",
".",
"get",
"(",
"\"id\"",
")",
"]",
"=",
"self",
".",
"merge",
"(",
"cls",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"json",
")",
")",
"return",
"chats"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeChats.chat
|
Get a single conversation by identifier.
Args:
id (str): single or group chat identifier
|
skpy/chat.py
|
def chat(self, id):
"""
Get a single conversation by identifier.
Args:
id (str): single or group chat identifier
"""
json = self.skype.conn("GET", "{0}/users/ME/conversations/{1}".format(self.skype.conn.msgsHost, id),
auth=SkypeConnection.Auth.RegToken, params={"view": "msnp24Equivalent"}).json()
cls = SkypeSingleChat
if "threadProperties" in json:
info = self.skype.conn("GET", "{0}/threads/{1}".format(self.skype.conn.msgsHost, json.get("id")),
auth=SkypeConnection.Auth.RegToken, params={"view": "msnp24Equivalent"}).json()
json.update(info)
cls = SkypeGroupChat
return self.merge(cls.fromRaw(self.skype, json))
|
def chat(self, id):
"""
Get a single conversation by identifier.
Args:
id (str): single or group chat identifier
"""
json = self.skype.conn("GET", "{0}/users/ME/conversations/{1}".format(self.skype.conn.msgsHost, id),
auth=SkypeConnection.Auth.RegToken, params={"view": "msnp24Equivalent"}).json()
cls = SkypeSingleChat
if "threadProperties" in json:
info = self.skype.conn("GET", "{0}/threads/{1}".format(self.skype.conn.msgsHost, json.get("id")),
auth=SkypeConnection.Auth.RegToken, params={"view": "msnp24Equivalent"}).json()
json.update(info)
cls = SkypeGroupChat
return self.merge(cls.fromRaw(self.skype, json))
|
[
"Get",
"a",
"single",
"conversation",
"by",
"identifier",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/chat.py#L423-L438
|
[
"def",
"chat",
"(",
"self",
",",
"id",
")",
":",
"json",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/users/ME/conversations/{1}\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"conn",
".",
"msgsHost",
",",
"id",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"params",
"=",
"{",
"\"view\"",
":",
"\"msnp24Equivalent\"",
"}",
")",
".",
"json",
"(",
")",
"cls",
"=",
"SkypeSingleChat",
"if",
"\"threadProperties\"",
"in",
"json",
":",
"info",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"GET\"",
",",
"\"{0}/threads/{1}\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"conn",
".",
"msgsHost",
",",
"json",
".",
"get",
"(",
"\"id\"",
")",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"params",
"=",
"{",
"\"view\"",
":",
"\"msnp24Equivalent\"",
"}",
")",
".",
"json",
"(",
")",
"json",
".",
"update",
"(",
"info",
")",
"cls",
"=",
"SkypeGroupChat",
"return",
"self",
".",
"merge",
"(",
"cls",
".",
"fromRaw",
"(",
"self",
".",
"skype",
",",
"json",
")",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeChats.create
|
Create a new group chat with the given users.
The current user is automatically added to the conversation as an admin. Any other admin identifiers must also
be present in the member list.
Args:
members (str list): user identifiers to initially join the conversation
admins (str list): user identifiers to gain admin privileges
|
skpy/chat.py
|
def create(self, members=(), admins=()):
"""
Create a new group chat with the given users.
The current user is automatically added to the conversation as an admin. Any other admin identifiers must also
be present in the member list.
Args:
members (str list): user identifiers to initially join the conversation
admins (str list): user identifiers to gain admin privileges
"""
memberObjs = [{"id": "8:{0}".format(self.skype.userId), "role": "Admin"}]
for id in members:
if id == self.skype.userId:
continue
memberObjs.append({"id": "8:{0}".format(id), "role": "Admin" if id in admins else "User"})
resp = self.skype.conn("POST", "{0}/threads".format(self.skype.conn.msgsHost),
auth=SkypeConnection.Auth.RegToken, json={"members": memberObjs})
return self.chat(resp.headers["Location"].rsplit("/", 1)[1])
|
def create(self, members=(), admins=()):
"""
Create a new group chat with the given users.
The current user is automatically added to the conversation as an admin. Any other admin identifiers must also
be present in the member list.
Args:
members (str list): user identifiers to initially join the conversation
admins (str list): user identifiers to gain admin privileges
"""
memberObjs = [{"id": "8:{0}".format(self.skype.userId), "role": "Admin"}]
for id in members:
if id == self.skype.userId:
continue
memberObjs.append({"id": "8:{0}".format(id), "role": "Admin" if id in admins else "User"})
resp = self.skype.conn("POST", "{0}/threads".format(self.skype.conn.msgsHost),
auth=SkypeConnection.Auth.RegToken, json={"members": memberObjs})
return self.chat(resp.headers["Location"].rsplit("/", 1)[1])
|
[
"Create",
"a",
"new",
"group",
"chat",
"with",
"the",
"given",
"users",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/chat.py#L440-L458
|
[
"def",
"create",
"(",
"self",
",",
"members",
"=",
"(",
")",
",",
"admins",
"=",
"(",
")",
")",
":",
"memberObjs",
"=",
"[",
"{",
"\"id\"",
":",
"\"8:{0}\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"userId",
")",
",",
"\"role\"",
":",
"\"Admin\"",
"}",
"]",
"for",
"id",
"in",
"members",
":",
"if",
"id",
"==",
"self",
".",
"skype",
".",
"userId",
":",
"continue",
"memberObjs",
".",
"append",
"(",
"{",
"\"id\"",
":",
"\"8:{0}\"",
".",
"format",
"(",
"id",
")",
",",
"\"role\"",
":",
"\"Admin\"",
"if",
"id",
"in",
"admins",
"else",
"\"User\"",
"}",
")",
"resp",
"=",
"self",
".",
"skype",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/threads\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"conn",
".",
"msgsHost",
")",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
"RegToken",
",",
"json",
"=",
"{",
"\"members\"",
":",
"memberObjs",
"}",
")",
"return",
"self",
".",
"chat",
"(",
"resp",
".",
"headers",
"[",
"\"Location\"",
"]",
".",
"rsplit",
"(",
"\"/\"",
",",
"1",
")",
"[",
"1",
"]",
")"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeChats.urlToIds
|
Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``
|
skpy/chat.py
|
def urlToIds(url):
"""
Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``
"""
urlId = url.split("/")[-1]
convUrl = "https://join.skype.com/api/v2/conversation/"
json = SkypeConnection.externalCall("POST", convUrl, json={"shortId": urlId, "type": "wl"}).json()
return {"id": json.get("Resource"),
"long": json.get("Id"),
"blob": json.get("ChatBlob")}
|
def urlToIds(url):
"""
Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``
"""
urlId = url.split("/")[-1]
convUrl = "https://join.skype.com/api/v2/conversation/"
json = SkypeConnection.externalCall("POST", convUrl, json={"shortId": urlId, "type": "wl"}).json()
return {"id": json.get("Resource"),
"long": json.get("Id"),
"blob": json.get("ChatBlob")}
|
[
"Resolve",
"a",
"join",
".",
"skype",
".",
"com",
"URL",
"and",
"returns",
"various",
"identifiers",
"for",
"the",
"group",
"conversation",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/chat.py#L462-L477
|
[
"def",
"urlToIds",
"(",
"url",
")",
":",
"urlId",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"convUrl",
"=",
"\"https://join.skype.com/api/v2/conversation/\"",
"json",
"=",
"SkypeConnection",
".",
"externalCall",
"(",
"\"POST\"",
",",
"convUrl",
",",
"json",
"=",
"{",
"\"shortId\"",
":",
"urlId",
",",
"\"type\"",
":",
"\"wl\"",
"}",
")",
".",
"json",
"(",
")",
"return",
"{",
"\"id\"",
":",
"json",
".",
"get",
"(",
"\"Resource\"",
")",
",",
"\"long\"",
":",
"json",
".",
"get",
"(",
"\"Id\"",
")",
",",
"\"blob\"",
":",
"json",
".",
"get",
"(",
"\"ChatBlob\"",
")",
"}"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.userToId
|
Extract the username from a contact URL.
Matches addresses containing ``users/<user>`` or ``users/ME/contacts/<user>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
|
skpy/util.py
|
def userToId(url):
"""
Extract the username from a contact URL.
Matches addresses containing ``users/<user>`` or ``users/ME/contacts/<user>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"users(/ME/contacts)?/[0-9]+:([^/]+)", url)
return match.group(2) if match else None
|
def userToId(url):
"""
Extract the username from a contact URL.
Matches addresses containing ``users/<user>`` or ``users/ME/contacts/<user>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"users(/ME/contacts)?/[0-9]+:([^/]+)", url)
return match.group(2) if match else None
|
[
"Extract",
"the",
"username",
"from",
"a",
"contact",
"URL",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L54-L67
|
[
"def",
"userToId",
"(",
"url",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r\"users(/ME/contacts)?/[0-9]+:([^/]+)\"",
",",
"url",
")",
"return",
"match",
".",
"group",
"(",
"2",
")",
"if",
"match",
"else",
"None"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.chatToId
|
Extract the conversation ID from a conversation URL.
Matches addresses containing ``conversations/<chat>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
|
skpy/util.py
|
def chatToId(url):
"""
Extract the conversation ID from a conversation URL.
Matches addresses containing ``conversations/<chat>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"conversations/([0-9]+:[^/]+)", url)
return match.group(1) if match else None
|
def chatToId(url):
"""
Extract the conversation ID from a conversation URL.
Matches addresses containing ``conversations/<chat>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"conversations/([0-9]+:[^/]+)", url)
return match.group(1) if match else None
|
[
"Extract",
"the",
"conversation",
"ID",
"from",
"a",
"conversation",
"URL",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L70-L83
|
[
"def",
"chatToId",
"(",
"url",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r\"conversations/([0-9]+:[^/]+)\"",
",",
"url",
")",
"return",
"match",
".",
"group",
"(",
"1",
")",
"if",
"match",
"else",
"None"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.initAttrs
|
Class decorator: automatically generate an ``__init__`` method that expects args from cls.attrs and stores them.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
|
skpy/util.py
|
def initAttrs(cls):
"""
Class decorator: automatically generate an ``__init__`` method that expects args from cls.attrs and stores them.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
"""
def __init__(self, skype=None, raw=None, *args, **kwargs):
super(cls, self).__init__(skype, raw)
# Merge args into kwargs based on cls.attrs.
for i in range(len(args)):
kwargs[cls.attrs[i]] = args[i]
# Disallow any unknown kwargs.
unknown = set(kwargs) - set(cls.attrs)
if unknown:
unknownDesc = "an unexpected keyword argument" if len(unknown) == 1 else "unexpected keyword arguments"
unknownList = ", ".join("'{0}'".format(k) for k in sorted(unknown))
raise TypeError("__init__() got {0} {1}".format(unknownDesc, unknownList))
# Set each attribute from kwargs, or use the default if not specified.
for k in cls.attrs:
setattr(self, k, kwargs.get(k, cls.defaults.get(k)))
# Add the init method to the class.
setattr(cls, "__init__", __init__)
return cls
|
def initAttrs(cls):
"""
Class decorator: automatically generate an ``__init__`` method that expects args from cls.attrs and stores them.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
"""
def __init__(self, skype=None, raw=None, *args, **kwargs):
super(cls, self).__init__(skype, raw)
# Merge args into kwargs based on cls.attrs.
for i in range(len(args)):
kwargs[cls.attrs[i]] = args[i]
# Disallow any unknown kwargs.
unknown = set(kwargs) - set(cls.attrs)
if unknown:
unknownDesc = "an unexpected keyword argument" if len(unknown) == 1 else "unexpected keyword arguments"
unknownList = ", ".join("'{0}'".format(k) for k in sorted(unknown))
raise TypeError("__init__() got {0} {1}".format(unknownDesc, unknownList))
# Set each attribute from kwargs, or use the default if not specified.
for k in cls.attrs:
setattr(self, k, kwargs.get(k, cls.defaults.get(k)))
# Add the init method to the class.
setattr(cls, "__init__", __init__)
return cls
|
[
"Class",
"decorator",
":",
"automatically",
"generate",
"an",
"__init__",
"method",
"that",
"expects",
"args",
"from",
"cls",
".",
"attrs",
"and",
"stores",
"them",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L94-L121
|
[
"def",
"initAttrs",
"(",
"cls",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"skype",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"cls",
",",
"self",
")",
".",
"__init__",
"(",
"skype",
",",
"raw",
")",
"# Merge args into kwargs based on cls.attrs.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"args",
")",
")",
":",
"kwargs",
"[",
"cls",
".",
"attrs",
"[",
"i",
"]",
"]",
"=",
"args",
"[",
"i",
"]",
"# Disallow any unknown kwargs.",
"unknown",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"cls",
".",
"attrs",
")",
"if",
"unknown",
":",
"unknownDesc",
"=",
"\"an unexpected keyword argument\"",
"if",
"len",
"(",
"unknown",
")",
"==",
"1",
"else",
"\"unexpected keyword arguments\"",
"unknownList",
"=",
"\", \"",
".",
"join",
"(",
"\"'{0}'\"",
".",
"format",
"(",
"k",
")",
"for",
"k",
"in",
"sorted",
"(",
"unknown",
")",
")",
"raise",
"TypeError",
"(",
"\"__init__() got {0} {1}\"",
".",
"format",
"(",
"unknownDesc",
",",
"unknownList",
")",
")",
"# Set each attribute from kwargs, or use the default if not specified.",
"for",
"k",
"in",
"cls",
".",
"attrs",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"kwargs",
".",
"get",
"(",
"k",
",",
"cls",
".",
"defaults",
".",
"get",
"(",
"k",
")",
")",
")",
"# Add the init method to the class.",
"setattr",
"(",
"cls",
",",
"\"__init__\"",
",",
"__init__",
")",
"return",
"cls"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.convertIds
|
Class decorator: add helper methods to convert identifier properties into SkypeObjs.
Args:
types (str list): simple field types to add properties for (``user``, ``users`` or ``chat``)
user (str list): attribute names to treat as single user identifier fields
users (str list): attribute names to treat as user identifier lists
chat (str list): attribute names to treat as chat identifier fields
Returns:
method: decorator function, ready to apply to other methods
|
skpy/util.py
|
def convertIds(*types, **kwargs):
"""
Class decorator: add helper methods to convert identifier properties into SkypeObjs.
Args:
types (str list): simple field types to add properties for (``user``, ``users`` or ``chat``)
user (str list): attribute names to treat as single user identifier fields
users (str list): attribute names to treat as user identifier lists
chat (str list): attribute names to treat as chat identifier fields
Returns:
method: decorator function, ready to apply to other methods
"""
user = kwargs.get("user", ())
users = kwargs.get("users", ())
chat = kwargs.get("chat", ())
def userObj(self, field):
return self.skype.contacts[getattr(self, field)]
def userObjs(self, field):
return (self.skype.contacts[id] for id in getattr(self, field))
def chatObj(self, field):
return self.skype.chats[getattr(self, field)]
def attach(cls, fn, field, idField):
"""
Generate the property object and attach it to the class.
Args:
cls (type): class to attach the property to
fn (method): function to be attached
field (str): attribute name for the new property
idField (str): reference field to retrieve identifier from
"""
setattr(cls, field, property(functools.wraps(fn)(functools.partial(fn, field=idField))))
def wrapper(cls):
# Shorthand identifiers, e.g. @convertIds("user", "chat").
for type in types:
if type == "user":
attach(cls, userObj, "user", "userId")
elif type == "users":
attach(cls, userObjs, "users", "userIds")
elif type == "chat":
attach(cls, chatObj, "chat", "chatId")
# Custom field names, e.g. @convertIds(user=["creator"]).
for field in user:
attach(cls, userObj, field, "{0}Id".format(field))
for field in users:
attach(cls, userObjs, "{0}s".format(field), "{0}Ids".format(field))
for field in chat:
attach(cls, chatObj, field, "{0}Id".format(field))
return cls
return wrapper
|
def convertIds(*types, **kwargs):
"""
Class decorator: add helper methods to convert identifier properties into SkypeObjs.
Args:
types (str list): simple field types to add properties for (``user``, ``users`` or ``chat``)
user (str list): attribute names to treat as single user identifier fields
users (str list): attribute names to treat as user identifier lists
chat (str list): attribute names to treat as chat identifier fields
Returns:
method: decorator function, ready to apply to other methods
"""
user = kwargs.get("user", ())
users = kwargs.get("users", ())
chat = kwargs.get("chat", ())
def userObj(self, field):
return self.skype.contacts[getattr(self, field)]
def userObjs(self, field):
return (self.skype.contacts[id] for id in getattr(self, field))
def chatObj(self, field):
return self.skype.chats[getattr(self, field)]
def attach(cls, fn, field, idField):
"""
Generate the property object and attach it to the class.
Args:
cls (type): class to attach the property to
fn (method): function to be attached
field (str): attribute name for the new property
idField (str): reference field to retrieve identifier from
"""
setattr(cls, field, property(functools.wraps(fn)(functools.partial(fn, field=idField))))
def wrapper(cls):
# Shorthand identifiers, e.g. @convertIds("user", "chat").
for type in types:
if type == "user":
attach(cls, userObj, "user", "userId")
elif type == "users":
attach(cls, userObjs, "users", "userIds")
elif type == "chat":
attach(cls, chatObj, "chat", "chatId")
# Custom field names, e.g. @convertIds(user=["creator"]).
for field in user:
attach(cls, userObj, field, "{0}Id".format(field))
for field in users:
attach(cls, userObjs, "{0}s".format(field), "{0}Ids".format(field))
for field in chat:
attach(cls, chatObj, field, "{0}Id".format(field))
return cls
return wrapper
|
[
"Class",
"decorator",
":",
"add",
"helper",
"methods",
"to",
"convert",
"identifier",
"properties",
"into",
"SkypeObjs",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L124-L180
|
[
"def",
"convertIds",
"(",
"*",
"types",
",",
"*",
"*",
"kwargs",
")",
":",
"user",
"=",
"kwargs",
".",
"get",
"(",
"\"user\"",
",",
"(",
")",
")",
"users",
"=",
"kwargs",
".",
"get",
"(",
"\"users\"",
",",
"(",
")",
")",
"chat",
"=",
"kwargs",
".",
"get",
"(",
"\"chat\"",
",",
"(",
")",
")",
"def",
"userObj",
"(",
"self",
",",
"field",
")",
":",
"return",
"self",
".",
"skype",
".",
"contacts",
"[",
"getattr",
"(",
"self",
",",
"field",
")",
"]",
"def",
"userObjs",
"(",
"self",
",",
"field",
")",
":",
"return",
"(",
"self",
".",
"skype",
".",
"contacts",
"[",
"id",
"]",
"for",
"id",
"in",
"getattr",
"(",
"self",
",",
"field",
")",
")",
"def",
"chatObj",
"(",
"self",
",",
"field",
")",
":",
"return",
"self",
".",
"skype",
".",
"chats",
"[",
"getattr",
"(",
"self",
",",
"field",
")",
"]",
"def",
"attach",
"(",
"cls",
",",
"fn",
",",
"field",
",",
"idField",
")",
":",
"\"\"\"\n Generate the property object and attach it to the class.\n\n Args:\n cls (type): class to attach the property to\n fn (method): function to be attached\n field (str): attribute name for the new property\n idField (str): reference field to retrieve identifier from\n \"\"\"",
"setattr",
"(",
"cls",
",",
"field",
",",
"property",
"(",
"functools",
".",
"wraps",
"(",
"fn",
")",
"(",
"functools",
".",
"partial",
"(",
"fn",
",",
"field",
"=",
"idField",
")",
")",
")",
")",
"def",
"wrapper",
"(",
"cls",
")",
":",
"# Shorthand identifiers, e.g. @convertIds(\"user\", \"chat\").",
"for",
"type",
"in",
"types",
":",
"if",
"type",
"==",
"\"user\"",
":",
"attach",
"(",
"cls",
",",
"userObj",
",",
"\"user\"",
",",
"\"userId\"",
")",
"elif",
"type",
"==",
"\"users\"",
":",
"attach",
"(",
"cls",
",",
"userObjs",
",",
"\"users\"",
",",
"\"userIds\"",
")",
"elif",
"type",
"==",
"\"chat\"",
":",
"attach",
"(",
"cls",
",",
"chatObj",
",",
"\"chat\"",
",",
"\"chatId\"",
")",
"# Custom field names, e.g. @convertIds(user=[\"creator\"]).",
"for",
"field",
"in",
"user",
":",
"attach",
"(",
"cls",
",",
"userObj",
",",
"field",
",",
"\"{0}Id\"",
".",
"format",
"(",
"field",
")",
")",
"for",
"field",
"in",
"users",
":",
"attach",
"(",
"cls",
",",
"userObjs",
",",
"\"{0}s\"",
".",
"format",
"(",
"field",
")",
",",
"\"{0}Ids\"",
".",
"format",
"(",
"field",
")",
")",
"for",
"field",
"in",
"chat",
":",
"attach",
"(",
"cls",
",",
"chatObj",
",",
"field",
",",
"\"{0}Id\"",
".",
"format",
"(",
"field",
")",
")",
"return",
"cls",
"return",
"wrapper"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.truthyAttrs
|
Class decorator: override __bool__ to set truthiness based on any attr being present.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
|
skpy/util.py
|
def truthyAttrs(cls):
"""
Class decorator: override __bool__ to set truthiness based on any attr being present.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
"""
def __bool__(self):
return bool(any(getattr(self, attr) for attr in self.attrs))
cls.__bool__ = cls.__nonzero__ = __bool__
return cls
|
def truthyAttrs(cls):
"""
Class decorator: override __bool__ to set truthiness based on any attr being present.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
"""
def __bool__(self):
return bool(any(getattr(self, attr) for attr in self.attrs))
cls.__bool__ = cls.__nonzero__ = __bool__
return cls
|
[
"Class",
"decorator",
":",
"override",
"__bool__",
"to",
"set",
"truthiness",
"based",
"on",
"any",
"attr",
"being",
"present",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L183-L197
|
[
"def",
"truthyAttrs",
"(",
"cls",
")",
":",
"def",
"__bool__",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"any",
"(",
"getattr",
"(",
"self",
",",
"attr",
")",
"for",
"attr",
"in",
"self",
".",
"attrs",
")",
")",
"cls",
".",
"__bool__",
"=",
"cls",
".",
"__nonzero__",
"=",
"__bool__",
"return",
"cls"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.cacheResult
|
Method decorator: calculate the value on first access, produce the cached value thereafter.
If the function takes arguments, the cache is a dictionary using all arguments as the key.
Args:
fn (method): function to decorate
Returns:
method: wrapper function with caching
|
skpy/util.py
|
def cacheResult(fn):
"""
Method decorator: calculate the value on first access, produce the cached value thereafter.
If the function takes arguments, the cache is a dictionary using all arguments as the key.
Args:
fn (method): function to decorate
Returns:
method: wrapper function with caching
"""
cache = {}
@functools.wraps(fn)
def wrapper(*args, **kwargs):
# Imperfect key generation (args may be passed as kwargs, so multiple ways to represent one key).
key = args + tuple(kwargs.items())
# Order of operations here tries to minimise use of exceptions.
try:
# Don't call the function here, as it may throw a TypeError itself (or from incorrect arguments).
if key in cache:
return cache[key]
except TypeError:
# Key is not hashable, so we can't cache with these args -- just return the result.
return fn(*args, **kwargs)
# Not yet cached, so generate the result and store it.
cache[key] = fn(*args, **kwargs)
return cache[key]
# Make cache accessible externally.
wrapper.cache = cache
return wrapper
|
def cacheResult(fn):
"""
Method decorator: calculate the value on first access, produce the cached value thereafter.
If the function takes arguments, the cache is a dictionary using all arguments as the key.
Args:
fn (method): function to decorate
Returns:
method: wrapper function with caching
"""
cache = {}
@functools.wraps(fn)
def wrapper(*args, **kwargs):
# Imperfect key generation (args may be passed as kwargs, so multiple ways to represent one key).
key = args + tuple(kwargs.items())
# Order of operations here tries to minimise use of exceptions.
try:
# Don't call the function here, as it may throw a TypeError itself (or from incorrect arguments).
if key in cache:
return cache[key]
except TypeError:
# Key is not hashable, so we can't cache with these args -- just return the result.
return fn(*args, **kwargs)
# Not yet cached, so generate the result and store it.
cache[key] = fn(*args, **kwargs)
return cache[key]
# Make cache accessible externally.
wrapper.cache = cache
return wrapper
|
[
"Method",
"decorator",
":",
"calculate",
"the",
"value",
"on",
"first",
"access",
"produce",
"the",
"cached",
"value",
"thereafter",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L200-L232
|
[
"def",
"cacheResult",
"(",
"fn",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Imperfect key generation (args may be passed as kwargs, so multiple ways to represent one key).",
"key",
"=",
"args",
"+",
"tuple",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
"# Order of operations here tries to minimise use of exceptions.",
"try",
":",
"# Don't call the function here, as it may throw a TypeError itself (or from incorrect arguments).",
"if",
"key",
"in",
"cache",
":",
"return",
"cache",
"[",
"key",
"]",
"except",
"TypeError",
":",
"# Key is not hashable, so we can't cache with these args -- just return the result.",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Not yet cached, so generate the result and store it.",
"cache",
"[",
"key",
"]",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"cache",
"[",
"key",
"]",
"# Make cache accessible externally.",
"wrapper",
".",
"cache",
"=",
"cache",
"return",
"wrapper"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
SkypeUtils.exhaust
|
Repeatedly call a function, starting with init, until false-y, yielding each item in turn.
The ``transform`` parameter can be used to map a collection to another format, for example iterating over a
:class:`dict` by value rather than key.
Use with state-synced functions to retrieve all results.
Args:
fn (method): function to call
transform (method): secondary function to convert result into an iterable
args (list): positional arguments to pass to ``fn``
kwargs (dict): keyword arguments to pass to ``fn``
Returns:
generator: generator of objects produced from the method
|
skpy/util.py
|
def exhaust(fn, transform=None, *args, **kwargs):
"""
Repeatedly call a function, starting with init, until false-y, yielding each item in turn.
The ``transform`` parameter can be used to map a collection to another format, for example iterating over a
:class:`dict` by value rather than key.
Use with state-synced functions to retrieve all results.
Args:
fn (method): function to call
transform (method): secondary function to convert result into an iterable
args (list): positional arguments to pass to ``fn``
kwargs (dict): keyword arguments to pass to ``fn``
Returns:
generator: generator of objects produced from the method
"""
while True:
iterRes = fn(*args, **kwargs)
if iterRes:
for item in transform(iterRes) if transform else iterRes:
yield item
else:
break
|
def exhaust(fn, transform=None, *args, **kwargs):
"""
Repeatedly call a function, starting with init, until false-y, yielding each item in turn.
The ``transform`` parameter can be used to map a collection to another format, for example iterating over a
:class:`dict` by value rather than key.
Use with state-synced functions to retrieve all results.
Args:
fn (method): function to call
transform (method): secondary function to convert result into an iterable
args (list): positional arguments to pass to ``fn``
kwargs (dict): keyword arguments to pass to ``fn``
Returns:
generator: generator of objects produced from the method
"""
while True:
iterRes = fn(*args, **kwargs)
if iterRes:
for item in transform(iterRes) if transform else iterRes:
yield item
else:
break
|
[
"Repeatedly",
"call",
"a",
"function",
"starting",
"with",
"init",
"until",
"false",
"-",
"y",
"yielding",
"each",
"item",
"in",
"turn",
"."
] |
Terrance/SkPy
|
python
|
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L235-L259
|
[
"def",
"exhaust",
"(",
"fn",
",",
"transform",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"iterRes",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"iterRes",
":",
"for",
"item",
"in",
"transform",
"(",
"iterRes",
")",
"if",
"transform",
"else",
"iterRes",
":",
"yield",
"item",
"else",
":",
"break"
] |
0f9489c94e8ec4d3effab4314497428872a80ad1
|
test
|
u
|
Return unicode text, no matter what
|
frontmatter/util.py
|
def u(text, encoding='utf-8'):
"Return unicode text, no matter what"
if isinstance(text, six.binary_type):
text = text.decode(encoding)
# it's already unicode
text = text.replace('\r\n', '\n')
return text
|
def u(text, encoding='utf-8'):
"Return unicode text, no matter what"
if isinstance(text, six.binary_type):
text = text.decode(encoding)
# it's already unicode
text = text.replace('\r\n', '\n')
return text
|
[
"Return",
"unicode",
"text",
"no",
"matter",
"what"
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/util.py#L7-L15
|
[
"def",
"u",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"binary_type",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"encoding",
")",
"# it's already unicode",
"text",
"=",
"text",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"return",
"text"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
detect_format
|
Figure out which handler to use, based on metadata.
Returns a handler instance or None.
``text`` should be unicode text about to be parsed.
``handlers`` is a dictionary where keys are opening delimiters
and values are handler instances.
|
frontmatter/__init__.py
|
def detect_format(text, handlers):
"""
Figure out which handler to use, based on metadata.
Returns a handler instance or None.
``text`` should be unicode text about to be parsed.
``handlers`` is a dictionary where keys are opening delimiters
and values are handler instances.
"""
for pattern, handler in handlers.items():
if pattern.match(text):
return handler
# nothing matched, give nothing back
return None
|
def detect_format(text, handlers):
"""
Figure out which handler to use, based on metadata.
Returns a handler instance or None.
``text`` should be unicode text about to be parsed.
``handlers`` is a dictionary where keys are opening delimiters
and values are handler instances.
"""
for pattern, handler in handlers.items():
if pattern.match(text):
return handler
# nothing matched, give nothing back
return None
|
[
"Figure",
"out",
"which",
"handler",
"to",
"use",
"based",
"on",
"metadata",
".",
"Returns",
"a",
"handler",
"instance",
"or",
"None",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L34-L49
|
[
"def",
"detect_format",
"(",
"text",
",",
"handlers",
")",
":",
"for",
"pattern",
",",
"handler",
"in",
"handlers",
".",
"items",
"(",
")",
":",
"if",
"pattern",
".",
"match",
"(",
"text",
")",
":",
"return",
"handler",
"# nothing matched, give nothing back",
"return",
"None"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
parse
|
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
>>> with open('tests/hello-world.markdown') as f:
... metadata, content = frontmatter.parse(f.read())
>>> print(metadata['title'])
Hello, world!
|
frontmatter/__init__.py
|
def parse(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
>>> with open('tests/hello-world.markdown') as f:
... metadata, content = frontmatter.parse(f.read())
>>> print(metadata['title'])
Hello, world!
"""
# ensure unicode first
text = u(text, encoding).strip()
# metadata starts with defaults
metadata = defaults.copy()
# this will only run if a handler hasn't been set higher up
handler = handler or detect_format(text, handlers)
if handler is None:
return metadata, text
# split on the delimiters
try:
fm, content = handler.split(text)
except ValueError:
# if we can't split, bail
return metadata, text
# parse, now that we have frontmatter
fm = handler.load(fm)
if isinstance(fm, dict):
metadata.update(fm)
return metadata, content.strip()
|
def parse(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
>>> with open('tests/hello-world.markdown') as f:
... metadata, content = frontmatter.parse(f.read())
>>> print(metadata['title'])
Hello, world!
"""
# ensure unicode first
text = u(text, encoding).strip()
# metadata starts with defaults
metadata = defaults.copy()
# this will only run if a handler hasn't been set higher up
handler = handler or detect_format(text, handlers)
if handler is None:
return metadata, text
# split on the delimiters
try:
fm, content = handler.split(text)
except ValueError:
# if we can't split, bail
return metadata, text
# parse, now that we have frontmatter
fm = handler.load(fm)
if isinstance(fm, dict):
metadata.update(fm)
return metadata, content.strip()
|
[
"Parse",
"text",
"with",
"frontmatter",
"return",
"metadata",
"and",
"content",
".",
"Pass",
"in",
"optional",
"metadata",
"defaults",
"as",
"keyword",
"args",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L52-L91
|
[
"def",
"parse",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"defaults",
")",
":",
"# ensure unicode first",
"text",
"=",
"u",
"(",
"text",
",",
"encoding",
")",
".",
"strip",
"(",
")",
"# metadata starts with defaults",
"metadata",
"=",
"defaults",
".",
"copy",
"(",
")",
"# this will only run if a handler hasn't been set higher up",
"handler",
"=",
"handler",
"or",
"detect_format",
"(",
"text",
",",
"handlers",
")",
"if",
"handler",
"is",
"None",
":",
"return",
"metadata",
",",
"text",
"# split on the delimiters",
"try",
":",
"fm",
",",
"content",
"=",
"handler",
".",
"split",
"(",
"text",
")",
"except",
"ValueError",
":",
"# if we can't split, bail",
"return",
"metadata",
",",
"text",
"# parse, now that we have frontmatter",
"fm",
"=",
"handler",
".",
"load",
"(",
"fm",
")",
"if",
"isinstance",
"(",
"fm",
",",
"dict",
")",
":",
"metadata",
".",
"update",
"(",
"fm",
")",
"return",
"metadata",
",",
"content",
".",
"strip",
"(",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
load
|
Load and parse a file-like object or filename,
return a :py:class:`post <frontmatter.Post>`.
::
>>> post = frontmatter.load('tests/hello-world.markdown')
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.load(f)
|
frontmatter/__init__.py
|
def load(fd, encoding='utf-8', handler=None, **defaults):
"""
Load and parse a file-like object or filename,
return a :py:class:`post <frontmatter.Post>`.
::
>>> post = frontmatter.load('tests/hello-world.markdown')
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.load(f)
"""
if hasattr(fd, 'read'):
text = fd.read()
else:
with codecs.open(fd, 'r', encoding) as f:
text = f.read()
handler = handler or detect_format(text, handlers)
return loads(text, encoding, handler, **defaults)
|
def load(fd, encoding='utf-8', handler=None, **defaults):
"""
Load and parse a file-like object or filename,
return a :py:class:`post <frontmatter.Post>`.
::
>>> post = frontmatter.load('tests/hello-world.markdown')
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.load(f)
"""
if hasattr(fd, 'read'):
text = fd.read()
else:
with codecs.open(fd, 'r', encoding) as f:
text = f.read()
handler = handler or detect_format(text, handlers)
return loads(text, encoding, handler, **defaults)
|
[
"Load",
"and",
"parse",
"a",
"file",
"-",
"like",
"object",
"or",
"filename",
"return",
"a",
":",
"py",
":",
"class",
":",
"post",
"<frontmatter",
".",
"Post",
">",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L94-L114
|
[
"def",
"load",
"(",
"fd",
",",
"encoding",
"=",
"'utf-8'",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"defaults",
")",
":",
"if",
"hasattr",
"(",
"fd",
",",
"'read'",
")",
":",
"text",
"=",
"fd",
".",
"read",
"(",
")",
"else",
":",
"with",
"codecs",
".",
"open",
"(",
"fd",
",",
"'r'",
",",
"encoding",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
"handler",
"=",
"handler",
"or",
"detect_format",
"(",
"text",
",",
"handlers",
")",
"return",
"loads",
"(",
"text",
",",
"encoding",
",",
"handler",
",",
"*",
"*",
"defaults",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
loads
|
Parse text (binary or unicode) and return a :py:class:`post <frontmatter.Post>`.
::
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.loads(f.read())
|
frontmatter/__init__.py
|
def loads(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text (binary or unicode) and return a :py:class:`post <frontmatter.Post>`.
::
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.loads(f.read())
"""
text = u(text, encoding)
handler = handler or detect_format(text, handlers)
metadata, content = parse(text, encoding, handler, **defaults)
return Post(content, handler, **metadata)
|
def loads(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text (binary or unicode) and return a :py:class:`post <frontmatter.Post>`.
::
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.loads(f.read())
"""
text = u(text, encoding)
handler = handler or detect_format(text, handlers)
metadata, content = parse(text, encoding, handler, **defaults)
return Post(content, handler, **metadata)
|
[
"Parse",
"text",
"(",
"binary",
"or",
"unicode",
")",
"and",
"return",
"a",
":",
"py",
":",
"class",
":",
"post",
"<frontmatter",
".",
"Post",
">",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L117-L130
|
[
"def",
"loads",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"defaults",
")",
":",
"text",
"=",
"u",
"(",
"text",
",",
"encoding",
")",
"handler",
"=",
"handler",
"or",
"detect_format",
"(",
"text",
",",
"handlers",
")",
"metadata",
",",
"content",
"=",
"parse",
"(",
"text",
",",
"encoding",
",",
"handler",
",",
"*",
"*",
"defaults",
")",
"return",
"Post",
"(",
"content",
",",
"handler",
",",
"*",
"*",
"metadata",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
dump
|
Serialize :py:class:`post <frontmatter.Post>` to a string and write to a file-like object.
Text will be encoded on the way out (utf-8 by default).
::
>>> from io import BytesIO
>>> f = BytesIO()
>>> frontmatter.dump(post, f)
>>> print(f.getvalue())
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
|
frontmatter/__init__.py
|
def dump(post, fd, encoding='utf-8', handler=None, **kwargs):
"""
Serialize :py:class:`post <frontmatter.Post>` to a string and write to a file-like object.
Text will be encoded on the way out (utf-8 by default).
::
>>> from io import BytesIO
>>> f = BytesIO()
>>> frontmatter.dump(post, f)
>>> print(f.getvalue())
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
"""
content = dumps(post, handler, **kwargs)
if hasattr(fd, 'write'):
fd.write(content.encode(encoding))
else:
with codecs.open(fd, 'w', encoding) as f:
f.write(content)
|
def dump(post, fd, encoding='utf-8', handler=None, **kwargs):
"""
Serialize :py:class:`post <frontmatter.Post>` to a string and write to a file-like object.
Text will be encoded on the way out (utf-8 by default).
::
>>> from io import BytesIO
>>> f = BytesIO()
>>> frontmatter.dump(post, f)
>>> print(f.getvalue())
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
"""
content = dumps(post, handler, **kwargs)
if hasattr(fd, 'write'):
fd.write(content.encode(encoding))
else:
with codecs.open(fd, 'w', encoding) as f:
f.write(content)
|
[
"Serialize",
":",
"py",
":",
"class",
":",
"post",
"<frontmatter",
".",
"Post",
">",
"to",
"a",
"string",
"and",
"write",
"to",
"a",
"file",
"-",
"like",
"object",
".",
"Text",
"will",
"be",
"encoded",
"on",
"the",
"way",
"out",
"(",
"utf",
"-",
"8",
"by",
"default",
")",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L133-L159
|
[
"def",
"dump",
"(",
"post",
",",
"fd",
",",
"encoding",
"=",
"'utf-8'",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"dumps",
"(",
"post",
",",
"handler",
",",
"*",
"*",
"kwargs",
")",
"if",
"hasattr",
"(",
"fd",
",",
"'write'",
")",
":",
"fd",
".",
"write",
"(",
"content",
".",
"encode",
"(",
"encoding",
")",
")",
"else",
":",
"with",
"codecs",
".",
"open",
"(",
"fd",
",",
"'w'",
",",
"encoding",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
dumps
|
Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument will override ``post.handler``, with
:py:class:`YAMLHandler <frontmatter.default_handlers.YAMLHandler>` used as
a default.
::
>>> print(frontmatter.dumps(post))
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
|
frontmatter/__init__.py
|
def dumps(post, handler=None, **kwargs):
"""
Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument will override ``post.handler``, with
:py:class:`YAMLHandler <frontmatter.default_handlers.YAMLHandler>` used as
a default.
::
>>> print(frontmatter.dumps(post))
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
"""
if handler is None:
handler = getattr(post, 'handler', None) or YAMLHandler()
start_delimiter = kwargs.pop('start_delimiter', handler.START_DELIMITER)
end_delimiter = kwargs.pop('end_delimiter', handler.END_DELIMITER)
metadata = handler.export(post.metadata, **kwargs)
return POST_TEMPLATE.format(
metadata=metadata, content=post.content,
start_delimiter=start_delimiter,
end_delimiter=end_delimiter).strip()
|
def dumps(post, handler=None, **kwargs):
"""
Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument will override ``post.handler``, with
:py:class:`YAMLHandler <frontmatter.default_handlers.YAMLHandler>` used as
a default.
::
>>> print(frontmatter.dumps(post))
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
"""
if handler is None:
handler = getattr(post, 'handler', None) or YAMLHandler()
start_delimiter = kwargs.pop('start_delimiter', handler.START_DELIMITER)
end_delimiter = kwargs.pop('end_delimiter', handler.END_DELIMITER)
metadata = handler.export(post.metadata, **kwargs)
return POST_TEMPLATE.format(
metadata=metadata, content=post.content,
start_delimiter=start_delimiter,
end_delimiter=end_delimiter).strip()
|
[
"Serialize",
"a",
":",
"py",
":",
"class",
":",
"post",
"<frontmatter",
".",
"Post",
">",
"to",
"a",
"string",
"and",
"return",
"text",
".",
"This",
"always",
"returns",
"unicode",
"text",
"which",
"can",
"then",
"be",
"encoded",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L162-L193
|
[
"def",
"dumps",
"(",
"post",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"handler",
"is",
"None",
":",
"handler",
"=",
"getattr",
"(",
"post",
",",
"'handler'",
",",
"None",
")",
"or",
"YAMLHandler",
"(",
")",
"start_delimiter",
"=",
"kwargs",
".",
"pop",
"(",
"'start_delimiter'",
",",
"handler",
".",
"START_DELIMITER",
")",
"end_delimiter",
"=",
"kwargs",
".",
"pop",
"(",
"'end_delimiter'",
",",
"handler",
".",
"END_DELIMITER",
")",
"metadata",
"=",
"handler",
".",
"export",
"(",
"post",
".",
"metadata",
",",
"*",
"*",
"kwargs",
")",
"return",
"POST_TEMPLATE",
".",
"format",
"(",
"metadata",
"=",
"metadata",
",",
"content",
"=",
"post",
".",
"content",
",",
"start_delimiter",
"=",
"start_delimiter",
",",
"end_delimiter",
"=",
"end_delimiter",
")",
".",
"strip",
"(",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
Post.to_dict
|
Post as a dict, for serializing
|
frontmatter/__init__.py
|
def to_dict(self):
"Post as a dict, for serializing"
d = self.metadata.copy()
d['content'] = self.content
return d
|
def to_dict(self):
"Post as a dict, for serializing"
d = self.metadata.copy()
d['content'] = self.content
return d
|
[
"Post",
"as",
"a",
"dict",
"for",
"serializing"
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/__init__.py#L249-L253
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"metadata",
".",
"copy",
"(",
")",
"d",
"[",
"'content'",
"]",
"=",
"self",
".",
"content",
"return",
"d"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
YAMLHandler.load
|
Parse YAML front matter. This uses yaml.SafeLoader by default.
|
frontmatter/default_handlers.py
|
def load(self, fm, **kwargs):
"""
Parse YAML front matter. This uses yaml.SafeLoader by default.
"""
kwargs.setdefault('Loader', SafeLoader)
return yaml.load(fm, **kwargs)
|
def load(self, fm, **kwargs):
"""
Parse YAML front matter. This uses yaml.SafeLoader by default.
"""
kwargs.setdefault('Loader', SafeLoader)
return yaml.load(fm, **kwargs)
|
[
"Parse",
"YAML",
"front",
"matter",
".",
"This",
"uses",
"yaml",
".",
"SafeLoader",
"by",
"default",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/default_handlers.py#L202-L207
|
[
"def",
"load",
"(",
"self",
",",
"fm",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'Loader'",
",",
"SafeLoader",
")",
"return",
"yaml",
".",
"load",
"(",
"fm",
",",
"*",
"*",
"kwargs",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
YAMLHandler.export
|
Export metadata as YAML. This uses yaml.SafeDumper by default.
|
frontmatter/default_handlers.py
|
def export(self, metadata, **kwargs):
"""
Export metadata as YAML. This uses yaml.SafeDumper by default.
"""
kwargs.setdefault('Dumper', SafeDumper)
kwargs.setdefault('default_flow_style', False)
kwargs.setdefault('allow_unicode', True)
metadata = yaml.dump(metadata, **kwargs).strip()
return u(metadata)
|
def export(self, metadata, **kwargs):
"""
Export metadata as YAML. This uses yaml.SafeDumper by default.
"""
kwargs.setdefault('Dumper', SafeDumper)
kwargs.setdefault('default_flow_style', False)
kwargs.setdefault('allow_unicode', True)
metadata = yaml.dump(metadata, **kwargs).strip()
return u(metadata)
|
[
"Export",
"metadata",
"as",
"YAML",
".",
"This",
"uses",
"yaml",
".",
"SafeDumper",
"by",
"default",
"."
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/default_handlers.py#L209-L218
|
[
"def",
"export",
"(",
"self",
",",
"metadata",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'Dumper'",
",",
"SafeDumper",
")",
"kwargs",
".",
"setdefault",
"(",
"'default_flow_style'",
",",
"False",
")",
"kwargs",
".",
"setdefault",
"(",
"'allow_unicode'",
",",
"True",
")",
"metadata",
"=",
"yaml",
".",
"dump",
"(",
"metadata",
",",
"*",
"*",
"kwargs",
")",
".",
"strip",
"(",
")",
"return",
"u",
"(",
"metadata",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
JSONHandler.export
|
Turn metadata into JSON
|
frontmatter/default_handlers.py
|
def export(self, metadata, **kwargs):
"Turn metadata into JSON"
kwargs.setdefault('indent', 4)
metadata = json.dumps(metadata, **kwargs)
return u(metadata)
|
def export(self, metadata, **kwargs):
"Turn metadata into JSON"
kwargs.setdefault('indent', 4)
metadata = json.dumps(metadata, **kwargs)
return u(metadata)
|
[
"Turn",
"metadata",
"into",
"JSON"
] |
eyeseast/python-frontmatter
|
python
|
https://github.com/eyeseast/python-frontmatter/blob/c318e583c48599eb597e0ad59c5d972258c3febc/frontmatter/default_handlers.py#L238-L242
|
[
"def",
"export",
"(",
"self",
",",
"metadata",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'indent'",
",",
"4",
")",
"metadata",
"=",
"json",
".",
"dumps",
"(",
"metadata",
",",
"*",
"*",
"kwargs",
")",
"return",
"u",
"(",
"metadata",
")"
] |
c318e583c48599eb597e0ad59c5d972258c3febc
|
test
|
WikiList._match
|
Return the match object for the current list.
|
wikitextparser/_wikilist.py
|
def _match(self):
"""Return the match object for the current list."""
cache_match, cache_string = self._match_cache
string = self.string
if cache_string == string:
return cache_match
cache_match = fullmatch(
LIST_PATTERN_FORMAT.replace(b'{pattern}', self.pattern.encode()),
self._shadow,
MULTILINE,
)
self._match_cache = cache_match, string
return cache_match
|
def _match(self):
"""Return the match object for the current list."""
cache_match, cache_string = self._match_cache
string = self.string
if cache_string == string:
return cache_match
cache_match = fullmatch(
LIST_PATTERN_FORMAT.replace(b'{pattern}', self.pattern.encode()),
self._shadow,
MULTILINE,
)
self._match_cache = cache_match, string
return cache_match
|
[
"Return",
"the",
"match",
"object",
"for",
"the",
"current",
"list",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikilist.py#L53-L65
|
[
"def",
"_match",
"(",
"self",
")",
":",
"cache_match",
",",
"cache_string",
"=",
"self",
".",
"_match_cache",
"string",
"=",
"self",
".",
"string",
"if",
"cache_string",
"==",
"string",
":",
"return",
"cache_match",
"cache_match",
"=",
"fullmatch",
"(",
"LIST_PATTERN_FORMAT",
".",
"replace",
"(",
"b'{pattern}'",
",",
"self",
".",
"pattern",
".",
"encode",
"(",
")",
")",
",",
"self",
".",
"_shadow",
",",
"MULTILINE",
",",
")",
"self",
".",
"_match_cache",
"=",
"cache_match",
",",
"string",
"return",
"cache_match"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiList.items
|
Return items as a list of strings.
Don't include sub-items and the start pattern.
|
wikitextparser/_wikilist.py
|
def items(self) -> List[str]:
"""Return items as a list of strings.
Don't include sub-items and the start pattern.
"""
items = [] # type: List[str]
append = items.append
string = self.string
match = self._match
ms = match.start()
for s, e in match.spans('item'):
append(string[s - ms:e - ms])
return items
|
def items(self) -> List[str]:
"""Return items as a list of strings.
Don't include sub-items and the start pattern.
"""
items = [] # type: List[str]
append = items.append
string = self.string
match = self._match
ms = match.start()
for s, e in match.spans('item'):
append(string[s - ms:e - ms])
return items
|
[
"Return",
"items",
"as",
"a",
"list",
"of",
"strings",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikilist.py#L68-L80
|
[
"def",
"items",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"items",
"=",
"[",
"]",
"# type: List[str]",
"append",
"=",
"items",
".",
"append",
"string",
"=",
"self",
".",
"string",
"match",
"=",
"self",
".",
"_match",
"ms",
"=",
"match",
".",
"start",
"(",
")",
"for",
"s",
",",
"e",
"in",
"match",
".",
"spans",
"(",
"'item'",
")",
":",
"append",
"(",
"string",
"[",
"s",
"-",
"ms",
":",
"e",
"-",
"ms",
"]",
")",
"return",
"items"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiList.sublists
|
Return the Lists inside the item with the given index.
:param i: The index if the item which its sub-lists are desired.
The performance is likely to be better if `i` is None.
:param pattern: The starting symbol for the desired sub-lists.
The `pattern` of the current list will be automatically added
as prefix.
Although this parameter is optional, but specifying it can improve
the performance.
|
wikitextparser/_wikilist.py
|
def sublists(
self, i: int = None, pattern: str = None
) -> List['WikiList']:
"""Return the Lists inside the item with the given index.
:param i: The index if the item which its sub-lists are desired.
The performance is likely to be better if `i` is None.
:param pattern: The starting symbol for the desired sub-lists.
The `pattern` of the current list will be automatically added
as prefix.
Although this parameter is optional, but specifying it can improve
the performance.
"""
patterns = (r'\#', r'\*', '[:;]') if pattern is None \
else (pattern,) # type: Tuple[str, ...]
self_pattern = self.pattern
lists = self.lists
sublists = [] # type: List['WikiList']
sublists_append = sublists.append
if i is None:
# Any sublist is acceptable
for pattern in patterns:
for lst in lists(self_pattern + pattern):
sublists_append(lst)
return sublists
# Only return sub-lists that are within the given item
match = self._match
fullitem_spans = match.spans('fullitem')
ss = self._span[0]
ms = match.start()
s, e = fullitem_spans[i]
e -= ms - ss
s -= ms - ss
for pattern in patterns:
for lst in lists(self_pattern + pattern):
# noinspection PyProtectedMember
ls, le = lst._span
if s < ls and le <= e:
sublists_append(lst)
return sublists
|
def sublists(
self, i: int = None, pattern: str = None
) -> List['WikiList']:
"""Return the Lists inside the item with the given index.
:param i: The index if the item which its sub-lists are desired.
The performance is likely to be better if `i` is None.
:param pattern: The starting symbol for the desired sub-lists.
The `pattern` of the current list will be automatically added
as prefix.
Although this parameter is optional, but specifying it can improve
the performance.
"""
patterns = (r'\#', r'\*', '[:;]') if pattern is None \
else (pattern,) # type: Tuple[str, ...]
self_pattern = self.pattern
lists = self.lists
sublists = [] # type: List['WikiList']
sublists_append = sublists.append
if i is None:
# Any sublist is acceptable
for pattern in patterns:
for lst in lists(self_pattern + pattern):
sublists_append(lst)
return sublists
# Only return sub-lists that are within the given item
match = self._match
fullitem_spans = match.spans('fullitem')
ss = self._span[0]
ms = match.start()
s, e = fullitem_spans[i]
e -= ms - ss
s -= ms - ss
for pattern in patterns:
for lst in lists(self_pattern + pattern):
# noinspection PyProtectedMember
ls, le = lst._span
if s < ls and le <= e:
sublists_append(lst)
return sublists
|
[
"Return",
"the",
"Lists",
"inside",
"the",
"item",
"with",
"the",
"given",
"index",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikilist.py#L102-L142
|
[
"def",
"sublists",
"(",
"self",
",",
"i",
":",
"int",
"=",
"None",
",",
"pattern",
":",
"str",
"=",
"None",
")",
"->",
"List",
"[",
"'WikiList'",
"]",
":",
"patterns",
"=",
"(",
"r'\\#'",
",",
"r'\\*'",
",",
"'[:;]'",
")",
"if",
"pattern",
"is",
"None",
"else",
"(",
"pattern",
",",
")",
"# type: Tuple[str, ...]",
"self_pattern",
"=",
"self",
".",
"pattern",
"lists",
"=",
"self",
".",
"lists",
"sublists",
"=",
"[",
"]",
"# type: List['WikiList']",
"sublists_append",
"=",
"sublists",
".",
"append",
"if",
"i",
"is",
"None",
":",
"# Any sublist is acceptable",
"for",
"pattern",
"in",
"patterns",
":",
"for",
"lst",
"in",
"lists",
"(",
"self_pattern",
"+",
"pattern",
")",
":",
"sublists_append",
"(",
"lst",
")",
"return",
"sublists",
"# Only return sub-lists that are within the given item",
"match",
"=",
"self",
".",
"_match",
"fullitem_spans",
"=",
"match",
".",
"spans",
"(",
"'fullitem'",
")",
"ss",
"=",
"self",
".",
"_span",
"[",
"0",
"]",
"ms",
"=",
"match",
".",
"start",
"(",
")",
"s",
",",
"e",
"=",
"fullitem_spans",
"[",
"i",
"]",
"e",
"-=",
"ms",
"-",
"ss",
"s",
"-=",
"ms",
"-",
"ss",
"for",
"pattern",
"in",
"patterns",
":",
"for",
"lst",
"in",
"lists",
"(",
"self_pattern",
"+",
"pattern",
")",
":",
"# noinspection PyProtectedMember",
"ls",
",",
"le",
"=",
"lst",
".",
"_span",
"if",
"s",
"<",
"ls",
"and",
"le",
"<=",
"e",
":",
"sublists_append",
"(",
"lst",
")",
"return",
"sublists"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiList.convert
|
Convert to another list type by replacing starting pattern.
|
wikitextparser/_wikilist.py
|
def convert(self, newstart: str) -> None:
"""Convert to another list type by replacing starting pattern."""
match = self._match
ms = match.start()
for s, e in reversed(match.spans('pattern')):
self[s - ms:e - ms] = newstart
self.pattern = escape(newstart)
|
def convert(self, newstart: str) -> None:
"""Convert to another list type by replacing starting pattern."""
match = self._match
ms = match.start()
for s, e in reversed(match.spans('pattern')):
self[s - ms:e - ms] = newstart
self.pattern = escape(newstart)
|
[
"Convert",
"to",
"another",
"list",
"type",
"by",
"replacing",
"starting",
"pattern",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikilist.py#L144-L150
|
[
"def",
"convert",
"(",
"self",
",",
"newstart",
":",
"str",
")",
"->",
"None",
":",
"match",
"=",
"self",
".",
"_match",
"ms",
"=",
"match",
".",
"start",
"(",
")",
"for",
"s",
",",
"e",
"in",
"reversed",
"(",
"match",
".",
"spans",
"(",
"'pattern'",
")",
")",
":",
"self",
"[",
"s",
"-",
"ms",
":",
"e",
"-",
"ms",
"]",
"=",
"newstart",
"self",
".",
"pattern",
"=",
"escape",
"(",
"newstart",
")"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
SubWikiTextWithArgs.arguments
|
Parse template content. Create self.name and self.arguments.
|
wikitextparser/_parser_function.py
|
def arguments(self) -> List[Argument]:
"""Parse template content. Create self.name and self.arguments."""
shadow = self._shadow
split_spans = self._args_matcher(shadow).spans('arg')
if not split_spans:
return []
arguments = []
arguments_append = arguments.append
type_to_spans = self._type_to_spans
ss, se = span = self._span
type_ = id(span)
lststr = self._lststr
string = lststr[0]
arg_spans = type_to_spans.setdefault(type_, [])
span_tuple_to_span_get = {(s[0], s[1]): s for s in arg_spans}.get
for arg_self_start, arg_self_end in split_spans:
s, e = arg_span = [ss + arg_self_start, ss + arg_self_end]
old_span = span_tuple_to_span_get((s, e))
if old_span is None:
insort(arg_spans, arg_span)
else:
arg_span = old_span
arg = Argument(lststr, type_to_spans, arg_span, type_)
arg._shadow_cache = (
string[s:e], shadow[arg_self_start:arg_self_end])
arguments_append(arg)
return arguments
|
def arguments(self) -> List[Argument]:
"""Parse template content. Create self.name and self.arguments."""
shadow = self._shadow
split_spans = self._args_matcher(shadow).spans('arg')
if not split_spans:
return []
arguments = []
arguments_append = arguments.append
type_to_spans = self._type_to_spans
ss, se = span = self._span
type_ = id(span)
lststr = self._lststr
string = lststr[0]
arg_spans = type_to_spans.setdefault(type_, [])
span_tuple_to_span_get = {(s[0], s[1]): s for s in arg_spans}.get
for arg_self_start, arg_self_end in split_spans:
s, e = arg_span = [ss + arg_self_start, ss + arg_self_end]
old_span = span_tuple_to_span_get((s, e))
if old_span is None:
insort(arg_spans, arg_span)
else:
arg_span = old_span
arg = Argument(lststr, type_to_spans, arg_span, type_)
arg._shadow_cache = (
string[s:e], shadow[arg_self_start:arg_self_end])
arguments_append(arg)
return arguments
|
[
"Parse",
"template",
"content",
".",
"Create",
"self",
".",
"name",
"and",
"self",
".",
"arguments",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_parser_function.py#L28-L54
|
[
"def",
"arguments",
"(",
"self",
")",
"->",
"List",
"[",
"Argument",
"]",
":",
"shadow",
"=",
"self",
".",
"_shadow",
"split_spans",
"=",
"self",
".",
"_args_matcher",
"(",
"shadow",
")",
".",
"spans",
"(",
"'arg'",
")",
"if",
"not",
"split_spans",
":",
"return",
"[",
"]",
"arguments",
"=",
"[",
"]",
"arguments_append",
"=",
"arguments",
".",
"append",
"type_to_spans",
"=",
"self",
".",
"_type_to_spans",
"ss",
",",
"se",
"=",
"span",
"=",
"self",
".",
"_span",
"type_",
"=",
"id",
"(",
"span",
")",
"lststr",
"=",
"self",
".",
"_lststr",
"string",
"=",
"lststr",
"[",
"0",
"]",
"arg_spans",
"=",
"type_to_spans",
".",
"setdefault",
"(",
"type_",
",",
"[",
"]",
")",
"span_tuple_to_span_get",
"=",
"{",
"(",
"s",
"[",
"0",
"]",
",",
"s",
"[",
"1",
"]",
")",
":",
"s",
"for",
"s",
"in",
"arg_spans",
"}",
".",
"get",
"for",
"arg_self_start",
",",
"arg_self_end",
"in",
"split_spans",
":",
"s",
",",
"e",
"=",
"arg_span",
"=",
"[",
"ss",
"+",
"arg_self_start",
",",
"ss",
"+",
"arg_self_end",
"]",
"old_span",
"=",
"span_tuple_to_span_get",
"(",
"(",
"s",
",",
"e",
")",
")",
"if",
"old_span",
"is",
"None",
":",
"insort",
"(",
"arg_spans",
",",
"arg_span",
")",
"else",
":",
"arg_span",
"=",
"old_span",
"arg",
"=",
"Argument",
"(",
"lststr",
",",
"type_to_spans",
",",
"arg_span",
",",
"type_",
")",
"arg",
".",
"_shadow_cache",
"=",
"(",
"string",
"[",
"s",
":",
"e",
"]",
",",
"shadow",
"[",
"arg_self_start",
":",
"arg_self_end",
"]",
")",
"arguments_append",
"(",
"arg",
")",
"return",
"arguments"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
SubWikiTextWithArgs.lists
|
Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Argument and use the `lists` method of that argument instead.
|
wikitextparser/_parser_function.py
|
def lists(self, pattern: str = None) -> List[WikiList]:
"""Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Argument and use the `lists` method of that argument instead.
"""
return [
lst for arg in self.arguments for lst in arg.lists(pattern) if lst]
|
def lists(self, pattern: str = None) -> List[WikiList]:
"""Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Argument and use the `lists` method of that argument instead.
"""
return [
lst for arg in self.arguments for lst in arg.lists(pattern) if lst]
|
[
"Return",
"the",
"lists",
"in",
"all",
"arguments",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_parser_function.py#L56-L63
|
[
"def",
"lists",
"(",
"self",
",",
"pattern",
":",
"str",
"=",
"None",
")",
"->",
"List",
"[",
"WikiList",
"]",
":",
"return",
"[",
"lst",
"for",
"arg",
"in",
"self",
".",
"arguments",
"for",
"lst",
"in",
"arg",
".",
"lists",
"(",
"pattern",
")",
"if",
"lst",
"]"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
SubWikiTextWithArgs.name
|
Return template's name (includes whitespace).
|
wikitextparser/_parser_function.py
|
def name(self) -> str:
"""Return template's name (includes whitespace)."""
h = self._atomic_partition(self._first_arg_sep)[0]
if len(h) == len(self.string):
return h[2:-2]
return h[2:]
|
def name(self) -> str:
"""Return template's name (includes whitespace)."""
h = self._atomic_partition(self._first_arg_sep)[0]
if len(h) == len(self.string):
return h[2:-2]
return h[2:]
|
[
"Return",
"template",
"s",
"name",
"(",
"includes",
"whitespace",
")",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_parser_function.py#L66-L71
|
[
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"h",
"=",
"self",
".",
"_atomic_partition",
"(",
"self",
".",
"_first_arg_sep",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"h",
")",
"==",
"len",
"(",
"self",
".",
"string",
")",
":",
"return",
"h",
"[",
"2",
":",
"-",
"2",
"]",
"return",
"h",
"[",
"2",
":",
"]"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
_plant_trie
|
Create a Trie out of a list of words and return an atomic regex pattern.
The corresponding Regex should match much faster than a simple Regex union.
|
wikitextparser/_config.py
|
def _plant_trie(strings: _List[str]) -> dict:
"""Create a Trie out of a list of words and return an atomic regex pattern.
The corresponding Regex should match much faster than a simple Regex union.
"""
# plant the trie
trie = {}
for string in strings:
d = trie
for char in string:
d[char] = char in d and d[char] or {}
d = d[char]
d[''] = None # EOS
return trie
|
def _plant_trie(strings: _List[str]) -> dict:
"""Create a Trie out of a list of words and return an atomic regex pattern.
The corresponding Regex should match much faster than a simple Regex union.
"""
# plant the trie
trie = {}
for string in strings:
d = trie
for char in string:
d[char] = char in d and d[char] or {}
d = d[char]
d[''] = None # EOS
return trie
|
[
"Create",
"a",
"Trie",
"out",
"of",
"a",
"list",
"of",
"words",
"and",
"return",
"an",
"atomic",
"regex",
"pattern",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_config.py#L8-L21
|
[
"def",
"_plant_trie",
"(",
"strings",
":",
"_List",
"[",
"str",
"]",
")",
"->",
"dict",
":",
"# plant the trie",
"trie",
"=",
"{",
"}",
"for",
"string",
"in",
"strings",
":",
"d",
"=",
"trie",
"for",
"char",
"in",
"string",
":",
"d",
"[",
"char",
"]",
"=",
"char",
"in",
"d",
"and",
"d",
"[",
"char",
"]",
"or",
"{",
"}",
"d",
"=",
"d",
"[",
"char",
"]",
"d",
"[",
"''",
"]",
"=",
"None",
"# EOS",
"return",
"trie"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
_pattern
|
Convert a trie to a regex pattern.
|
wikitextparser/_config.py
|
def _pattern(trie: dict) -> str:
"""Convert a trie to a regex pattern."""
if '' in trie:
if len(trie) == 1:
return ''
optional = True
del trie['']
else:
optional = False
subpattern_to_chars = _defaultdict(list)
for char, sub_trie in trie.items():
subpattern = _pattern(sub_trie)
subpattern_to_chars[subpattern].append(char)
alts = []
for subpattern, chars in subpattern_to_chars.items():
if len(chars) == 1:
alts.append(chars[0] + subpattern)
else:
chars.sort(reverse=True)
alts.append('[' + ''.join(chars) + ']' + subpattern)
if len(alts) == 1:
result = alts[0]
if optional:
if len(result) == 1:
result += '?+'
else: # more than one character in alts[0]
result = '(?:' + result + ')?+'
else:
alts.sort(reverse=True)
result = '(?>' + '|'.join(alts) + ')'
if optional:
result += '?+'
return result
|
def _pattern(trie: dict) -> str:
"""Convert a trie to a regex pattern."""
if '' in trie:
if len(trie) == 1:
return ''
optional = True
del trie['']
else:
optional = False
subpattern_to_chars = _defaultdict(list)
for char, sub_trie in trie.items():
subpattern = _pattern(sub_trie)
subpattern_to_chars[subpattern].append(char)
alts = []
for subpattern, chars in subpattern_to_chars.items():
if len(chars) == 1:
alts.append(chars[0] + subpattern)
else:
chars.sort(reverse=True)
alts.append('[' + ''.join(chars) + ']' + subpattern)
if len(alts) == 1:
result = alts[0]
if optional:
if len(result) == 1:
result += '?+'
else: # more than one character in alts[0]
result = '(?:' + result + ')?+'
else:
alts.sort(reverse=True)
result = '(?>' + '|'.join(alts) + ')'
if optional:
result += '?+'
return result
|
[
"Convert",
"a",
"trie",
"to",
"a",
"regex",
"pattern",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_config.py#L24-L60
|
[
"def",
"_pattern",
"(",
"trie",
":",
"dict",
")",
"->",
"str",
":",
"if",
"''",
"in",
"trie",
":",
"if",
"len",
"(",
"trie",
")",
"==",
"1",
":",
"return",
"''",
"optional",
"=",
"True",
"del",
"trie",
"[",
"''",
"]",
"else",
":",
"optional",
"=",
"False",
"subpattern_to_chars",
"=",
"_defaultdict",
"(",
"list",
")",
"for",
"char",
",",
"sub_trie",
"in",
"trie",
".",
"items",
"(",
")",
":",
"subpattern",
"=",
"_pattern",
"(",
"sub_trie",
")",
"subpattern_to_chars",
"[",
"subpattern",
"]",
".",
"append",
"(",
"char",
")",
"alts",
"=",
"[",
"]",
"for",
"subpattern",
",",
"chars",
"in",
"subpattern_to_chars",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"chars",
")",
"==",
"1",
":",
"alts",
".",
"append",
"(",
"chars",
"[",
"0",
"]",
"+",
"subpattern",
")",
"else",
":",
"chars",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"alts",
".",
"append",
"(",
"'['",
"+",
"''",
".",
"join",
"(",
"chars",
")",
"+",
"']'",
"+",
"subpattern",
")",
"if",
"len",
"(",
"alts",
")",
"==",
"1",
":",
"result",
"=",
"alts",
"[",
"0",
"]",
"if",
"optional",
":",
"if",
"len",
"(",
"result",
")",
"==",
"1",
":",
"result",
"+=",
"'?+'",
"else",
":",
"# more than one character in alts[0]",
"result",
"=",
"'(?:'",
"+",
"result",
"+",
"')?+'",
"else",
":",
"alts",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"result",
"=",
"'(?>'",
"+",
"'|'",
".",
"join",
"(",
"alts",
")",
"+",
"')'",
"if",
"optional",
":",
"result",
"+=",
"'?+'",
"return",
"result"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._check_index
|
Return adjusted start and stop index as tuple.
Used in __setitem__ and __delitem__.
|
wikitextparser/_wikitext.py
|
def _check_index(self, key: Union[slice, int]) -> (int, int):
"""Return adjusted start and stop index as tuple.
Used in __setitem__ and __delitem__.
"""
ss, se = self._span
if isinstance(key, int):
if key < 0:
key += se - ss
if key < 0:
raise IndexError('index out of range')
elif key >= se - ss:
raise IndexError('index out of range')
start = ss + key
return start, start + 1
# isinstance(key, slice)
if key.step is not None:
raise NotImplementedError(
'step is not implemented for string setter.')
start, stop = key.start or 0, key.stop
if start < 0:
start += se - ss
if start < 0:
raise IndexError('start index out of range')
if stop is None:
stop = se - ss
elif stop < 0:
stop += se - ss
if start > stop:
raise IndexError(
'stop index out of range or start is after the stop')
return start + ss, stop + ss
|
def _check_index(self, key: Union[slice, int]) -> (int, int):
"""Return adjusted start and stop index as tuple.
Used in __setitem__ and __delitem__.
"""
ss, se = self._span
if isinstance(key, int):
if key < 0:
key += se - ss
if key < 0:
raise IndexError('index out of range')
elif key >= se - ss:
raise IndexError('index out of range')
start = ss + key
return start, start + 1
# isinstance(key, slice)
if key.step is not None:
raise NotImplementedError(
'step is not implemented for string setter.')
start, stop = key.start or 0, key.stop
if start < 0:
start += se - ss
if start < 0:
raise IndexError('start index out of range')
if stop is None:
stop = se - ss
elif stop < 0:
stop += se - ss
if start > stop:
raise IndexError(
'stop index out of range or start is after the stop')
return start + ss, stop + ss
|
[
"Return",
"adjusted",
"start",
"and",
"stop",
"index",
"as",
"tuple",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L171-L202
|
[
"def",
"_check_index",
"(",
"self",
",",
"key",
":",
"Union",
"[",
"slice",
",",
"int",
"]",
")",
"->",
"(",
"int",
",",
"int",
")",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"if",
"key",
"<",
"0",
":",
"key",
"+=",
"se",
"-",
"ss",
"if",
"key",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"'index out of range'",
")",
"elif",
"key",
">=",
"se",
"-",
"ss",
":",
"raise",
"IndexError",
"(",
"'index out of range'",
")",
"start",
"=",
"ss",
"+",
"key",
"return",
"start",
",",
"start",
"+",
"1",
"# isinstance(key, slice)",
"if",
"key",
".",
"step",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'step is not implemented for string setter.'",
")",
"start",
",",
"stop",
"=",
"key",
".",
"start",
"or",
"0",
",",
"key",
".",
"stop",
"if",
"start",
"<",
"0",
":",
"start",
"+=",
"se",
"-",
"ss",
"if",
"start",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"'start index out of range'",
")",
"if",
"stop",
"is",
"None",
":",
"stop",
"=",
"se",
"-",
"ss",
"elif",
"stop",
"<",
"0",
":",
"stop",
"+=",
"se",
"-",
"ss",
"if",
"start",
">",
"stop",
":",
"raise",
"IndexError",
"(",
"'stop index out of range or start is after the stop'",
")",
"return",
"start",
"+",
"ss",
",",
"stop",
"+",
"ss"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText.insert
|
Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the need to shrink any of the sub-spans.
If parse is False, don't parse the inserted string.
|
wikitextparser/_wikitext.py
|
def insert(self, index: int, string: str) -> None:
"""Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the need to shrink any of the sub-spans.
If parse is False, don't parse the inserted string.
"""
ss, se = self._span
lststr = self._lststr
lststr0 = lststr[0]
if index < 0:
index += se - ss
if index < 0:
index = 0
elif index > se - ss: # Note that it is not >=. Index can be new.
index = se - ss
index += ss
# Update lststr
lststr[0] = lststr0[:index] + string + lststr0[index:]
string_len = len(string)
# Update spans
self._insert_update(
index=index,
length=string_len)
# Remember newly added spans by the string.
type_to_spans = self._type_to_spans
for type_, spans in parse_to_spans(
bytearray(string, 'ascii', 'replace')
).items():
for s, e in spans:
insort(type_to_spans[type_], [index + s, index + e])
|
def insert(self, index: int, string: str) -> None:
"""Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the need to shrink any of the sub-spans.
If parse is False, don't parse the inserted string.
"""
ss, se = self._span
lststr = self._lststr
lststr0 = lststr[0]
if index < 0:
index += se - ss
if index < 0:
index = 0
elif index > se - ss: # Note that it is not >=. Index can be new.
index = se - ss
index += ss
# Update lststr
lststr[0] = lststr0[:index] + string + lststr0[index:]
string_len = len(string)
# Update spans
self._insert_update(
index=index,
length=string_len)
# Remember newly added spans by the string.
type_to_spans = self._type_to_spans
for type_, spans in parse_to_spans(
bytearray(string, 'ascii', 'replace')
).items():
for s, e in spans:
insort(type_to_spans[type_], [index + s, index + e])
|
[
"Insert",
"the",
"given",
"string",
"before",
"the",
"specified",
"index",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L257-L289
|
[
"def",
"insert",
"(",
"self",
",",
"index",
":",
"int",
",",
"string",
":",
"str",
")",
"->",
"None",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"lststr",
"=",
"self",
".",
"_lststr",
"lststr0",
"=",
"lststr",
"[",
"0",
"]",
"if",
"index",
"<",
"0",
":",
"index",
"+=",
"se",
"-",
"ss",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"0",
"elif",
"index",
">",
"se",
"-",
"ss",
":",
"# Note that it is not >=. Index can be new.",
"index",
"=",
"se",
"-",
"ss",
"index",
"+=",
"ss",
"# Update lststr",
"lststr",
"[",
"0",
"]",
"=",
"lststr0",
"[",
":",
"index",
"]",
"+",
"string",
"+",
"lststr0",
"[",
"index",
":",
"]",
"string_len",
"=",
"len",
"(",
"string",
")",
"# Update spans",
"self",
".",
"_insert_update",
"(",
"index",
"=",
"index",
",",
"length",
"=",
"string_len",
")",
"# Remember newly added spans by the string.",
"type_to_spans",
"=",
"self",
".",
"_type_to_spans",
"for",
"type_",
",",
"spans",
"in",
"parse_to_spans",
"(",
"bytearray",
"(",
"string",
",",
"'ascii'",
",",
"'replace'",
")",
")",
".",
"items",
"(",
")",
":",
"for",
"s",
",",
"e",
"in",
"spans",
":",
"insort",
"(",
"type_to_spans",
"[",
"type_",
"]",
",",
"[",
"index",
"+",
"s",
",",
"index",
"+",
"e",
"]",
")"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText.string
|
Return str(self).
|
wikitextparser/_wikitext.py
|
def string(self) -> str:
"""Return str(self)."""
start, end = self._span
return self._lststr[0][start:end]
|
def string(self) -> str:
"""Return str(self)."""
start, end = self._span
return self._lststr[0][start:end]
|
[
"Return",
"str",
"(",
"self",
")",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L297-L300
|
[
"def",
"string",
"(",
"self",
")",
"->",
"str",
":",
"start",
",",
"end",
"=",
"self",
".",
"_span",
"return",
"self",
".",
"_lststr",
"[",
"0",
"]",
"[",
"start",
":",
"end",
"]"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._atomic_partition
|
Partition self.string where `char`'s not in atomic sub-spans.
|
wikitextparser/_wikitext.py
|
def _atomic_partition(self, char: int) -> Tuple[str, str, str]:
"""Partition self.string where `char`'s not in atomic sub-spans."""
s, e = self._span
index = self._shadow.find(char)
if index == -1:
return self._lststr[0][s:e], '', ''
lststr0 = self._lststr[0]
return lststr0[s:s + index], chr(char), lststr0[s + index + 1:e]
|
def _atomic_partition(self, char: int) -> Tuple[str, str, str]:
"""Partition self.string where `char`'s not in atomic sub-spans."""
s, e = self._span
index = self._shadow.find(char)
if index == -1:
return self._lststr[0][s:e], '', ''
lststr0 = self._lststr[0]
return lststr0[s:s + index], chr(char), lststr0[s + index + 1:e]
|
[
"Partition",
"self",
".",
"string",
"where",
"char",
"s",
"not",
"in",
"atomic",
"sub",
"-",
"spans",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L312-L319
|
[
"def",
"_atomic_partition",
"(",
"self",
",",
"char",
":",
"int",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
":",
"s",
",",
"e",
"=",
"self",
".",
"_span",
"index",
"=",
"self",
".",
"_shadow",
".",
"find",
"(",
"char",
")",
"if",
"index",
"==",
"-",
"1",
":",
"return",
"self",
".",
"_lststr",
"[",
"0",
"]",
"[",
"s",
":",
"e",
"]",
",",
"''",
",",
"''",
"lststr0",
"=",
"self",
".",
"_lststr",
"[",
"0",
"]",
"return",
"lststr0",
"[",
"s",
":",
"s",
"+",
"index",
"]",
",",
"chr",
"(",
"char",
")",
",",
"lststr0",
"[",
"s",
"+",
"index",
"+",
"1",
":",
"e",
"]"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._subspans
|
Return all the sub-span including self._span.
|
wikitextparser/_wikitext.py
|
def _subspans(self, type_: str) -> List[List[int]]:
"""Return all the sub-span including self._span."""
return self._type_to_spans[type_]
|
def _subspans(self, type_: str) -> List[List[int]]:
"""Return all the sub-span including self._span."""
return self._type_to_spans[type_]
|
[
"Return",
"all",
"the",
"sub",
"-",
"span",
"including",
"self",
".",
"_span",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L321-L323
|
[
"def",
"_subspans",
"(",
"self",
",",
"type_",
":",
"str",
")",
"->",
"List",
"[",
"List",
"[",
"int",
"]",
"]",
":",
"return",
"self",
".",
"_type_to_spans",
"[",
"type_",
"]"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._close_subspans
|
Close all sub-spans of (start, stop).
|
wikitextparser/_wikitext.py
|
def _close_subspans(self, start: int, stop: int) -> None:
"""Close all sub-spans of (start, stop)."""
ss, se = self._span
for spans in self._type_to_spans.values():
b = bisect(spans, [start])
for i, (s, e) in enumerate(spans[b:bisect(spans, [stop], b)]):
if e <= stop:
if ss != s or se != e:
spans.pop(i + b)[:] = -1, -1
b -= 1
|
def _close_subspans(self, start: int, stop: int) -> None:
"""Close all sub-spans of (start, stop)."""
ss, se = self._span
for spans in self._type_to_spans.values():
b = bisect(spans, [start])
for i, (s, e) in enumerate(spans[b:bisect(spans, [stop], b)]):
if e <= stop:
if ss != s or se != e:
spans.pop(i + b)[:] = -1, -1
b -= 1
|
[
"Close",
"all",
"sub",
"-",
"spans",
"of",
"(",
"start",
"stop",
")",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L325-L334
|
[
"def",
"_close_subspans",
"(",
"self",
",",
"start",
":",
"int",
",",
"stop",
":",
"int",
")",
"->",
"None",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"for",
"spans",
"in",
"self",
".",
"_type_to_spans",
".",
"values",
"(",
")",
":",
"b",
"=",
"bisect",
"(",
"spans",
",",
"[",
"start",
"]",
")",
"for",
"i",
",",
"(",
"s",
",",
"e",
")",
"in",
"enumerate",
"(",
"spans",
"[",
"b",
":",
"bisect",
"(",
"spans",
",",
"[",
"stop",
"]",
",",
"b",
")",
"]",
")",
":",
"if",
"e",
"<=",
"stop",
":",
"if",
"ss",
"!=",
"s",
"or",
"se",
"!=",
"e",
":",
"spans",
".",
"pop",
"(",
"i",
"+",
"b",
")",
"[",
":",
"]",
"=",
"-",
"1",
",",
"-",
"1",
"b",
"-=",
"1"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._shrink_update
|
Update self._type_to_spans according to the removed span.
Warning: If an operation involves both _shrink_update and
_insert_update, you might wanna consider doing the
_insert_update before the _shrink_update as this function
can cause data loss in self._type_to_spans.
|
wikitextparser/_wikitext.py
|
def _shrink_update(self, rmstart: int, rmstop: int) -> None:
"""Update self._type_to_spans according to the removed span.
Warning: If an operation involves both _shrink_update and
_insert_update, you might wanna consider doing the
_insert_update before the _shrink_update as this function
can cause data loss in self._type_to_spans.
"""
# Note: The following algorithm won't work correctly if spans
# are not sorted.
# Note: No span should be removed from _type_to_spans.
for spans in self._type_to_spans.values():
i = len(spans) - 1
while i >= 0:
s, e = span = spans[i]
if rmstop <= s:
# rmstart <= rmstop <= s <= e
rmlength = rmstop - rmstart
span[:] = s - rmlength, e - rmlength
i -= 1
continue
break
else:
continue
while True:
if rmstart <= s:
if rmstop < e:
# rmstart < s <= rmstop < e
span[:] = rmstart, e + rmstart - rmstop
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
# rmstart <= s <= e < rmstop
spans.pop(i)[:] = -1, -1
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
break
while i >= 0:
if e <= rmstart:
# s <= e <= rmstart <= rmstop
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
# s <= rmstart <= rmstop <= e
span[1] -= rmstop - rmstart
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
|
def _shrink_update(self, rmstart: int, rmstop: int) -> None:
"""Update self._type_to_spans according to the removed span.
Warning: If an operation involves both _shrink_update and
_insert_update, you might wanna consider doing the
_insert_update before the _shrink_update as this function
can cause data loss in self._type_to_spans.
"""
# Note: The following algorithm won't work correctly if spans
# are not sorted.
# Note: No span should be removed from _type_to_spans.
for spans in self._type_to_spans.values():
i = len(spans) - 1
while i >= 0:
s, e = span = spans[i]
if rmstop <= s:
# rmstart <= rmstop <= s <= e
rmlength = rmstop - rmstart
span[:] = s - rmlength, e - rmlength
i -= 1
continue
break
else:
continue
while True:
if rmstart <= s:
if rmstop < e:
# rmstart < s <= rmstop < e
span[:] = rmstart, e + rmstart - rmstop
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
# rmstart <= s <= e < rmstop
spans.pop(i)[:] = -1, -1
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
break
while i >= 0:
if e <= rmstart:
# s <= e <= rmstart <= rmstop
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
# s <= rmstart <= rmstop <= e
span[1] -= rmstop - rmstart
i -= 1
if i < 0:
break
s, e = span = spans[i]
continue
|
[
"Update",
"self",
".",
"_type_to_spans",
"according",
"to",
"the",
"removed",
"span",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L336-L392
|
[
"def",
"_shrink_update",
"(",
"self",
",",
"rmstart",
":",
"int",
",",
"rmstop",
":",
"int",
")",
"->",
"None",
":",
"# Note: The following algorithm won't work correctly if spans",
"# are not sorted.",
"# Note: No span should be removed from _type_to_spans.",
"for",
"spans",
"in",
"self",
".",
"_type_to_spans",
".",
"values",
"(",
")",
":",
"i",
"=",
"len",
"(",
"spans",
")",
"-",
"1",
"while",
"i",
">=",
"0",
":",
"s",
",",
"e",
"=",
"span",
"=",
"spans",
"[",
"i",
"]",
"if",
"rmstop",
"<=",
"s",
":",
"# rmstart <= rmstop <= s <= e",
"rmlength",
"=",
"rmstop",
"-",
"rmstart",
"span",
"[",
":",
"]",
"=",
"s",
"-",
"rmlength",
",",
"e",
"-",
"rmlength",
"i",
"-=",
"1",
"continue",
"break",
"else",
":",
"continue",
"while",
"True",
":",
"if",
"rmstart",
"<=",
"s",
":",
"if",
"rmstop",
"<",
"e",
":",
"# rmstart < s <= rmstop < e",
"span",
"[",
":",
"]",
"=",
"rmstart",
",",
"e",
"+",
"rmstart",
"-",
"rmstop",
"i",
"-=",
"1",
"if",
"i",
"<",
"0",
":",
"break",
"s",
",",
"e",
"=",
"span",
"=",
"spans",
"[",
"i",
"]",
"continue",
"# rmstart <= s <= e < rmstop",
"spans",
".",
"pop",
"(",
"i",
")",
"[",
":",
"]",
"=",
"-",
"1",
",",
"-",
"1",
"i",
"-=",
"1",
"if",
"i",
"<",
"0",
":",
"break",
"s",
",",
"e",
"=",
"span",
"=",
"spans",
"[",
"i",
"]",
"continue",
"break",
"while",
"i",
">=",
"0",
":",
"if",
"e",
"<=",
"rmstart",
":",
"# s <= e <= rmstart <= rmstop",
"i",
"-=",
"1",
"if",
"i",
"<",
"0",
":",
"break",
"s",
",",
"e",
"=",
"span",
"=",
"spans",
"[",
"i",
"]",
"continue",
"# s <= rmstart <= rmstop <= e",
"span",
"[",
"1",
"]",
"-=",
"rmstop",
"-",
"rmstart",
"i",
"-=",
"1",
"if",
"i",
"<",
"0",
":",
"break",
"s",
",",
"e",
"=",
"span",
"=",
"spans",
"[",
"i",
"]",
"continue"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._insert_update
|
Update self._type_to_spans according to the added length.
|
wikitextparser/_wikitext.py
|
def _insert_update(self, index: int, length: int) -> None:
"""Update self._type_to_spans according to the added length."""
ss, se = self._span
for spans in self._type_to_spans.values():
for span in spans:
if index < span[1] or span[1] == index == se:
span[1] += length
# index is before s, or at s but not on self_span
if index < span[0] or span[0] == index != ss:
span[0] += length
|
def _insert_update(self, index: int, length: int) -> None:
"""Update self._type_to_spans according to the added length."""
ss, se = self._span
for spans in self._type_to_spans.values():
for span in spans:
if index < span[1] or span[1] == index == se:
span[1] += length
# index is before s, or at s but not on self_span
if index < span[0] or span[0] == index != ss:
span[0] += length
|
[
"Update",
"self",
".",
"_type_to_spans",
"according",
"to",
"the",
"added",
"length",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L394-L403
|
[
"def",
"_insert_update",
"(",
"self",
",",
"index",
":",
"int",
",",
"length",
":",
"int",
")",
"->",
"None",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"for",
"spans",
"in",
"self",
".",
"_type_to_spans",
".",
"values",
"(",
")",
":",
"for",
"span",
"in",
"spans",
":",
"if",
"index",
"<",
"span",
"[",
"1",
"]",
"or",
"span",
"[",
"1",
"]",
"==",
"index",
"==",
"se",
":",
"span",
"[",
"1",
"]",
"+=",
"length",
"# index is before s, or at s but not on self_span",
"if",
"index",
"<",
"span",
"[",
"0",
"]",
"or",
"span",
"[",
"0",
"]",
"==",
"index",
"!=",
"ss",
":",
"span",
"[",
"0",
"]",
"+=",
"length"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText.nesting_level
|
Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Template or
ParserFunction increases the level by one.
|
wikitextparser/_wikitext.py
|
def nesting_level(self) -> int:
"""Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Template or
ParserFunction increases the level by one.
"""
ss, se = self._span
level = 0
type_to_spans = self._type_to_spans
for type_ in ('Template', 'ParserFunction'):
spans = type_to_spans[type_]
for s, e in spans[:bisect(spans, [ss + 1])]:
if se <= e:
level += 1
return level
|
def nesting_level(self) -> int:
"""Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Template or
ParserFunction increases the level by one.
"""
ss, se = self._span
level = 0
type_to_spans = self._type_to_spans
for type_ in ('Template', 'ParserFunction'):
spans = type_to_spans[type_]
for s, e in spans[:bisect(spans, [ss + 1])]:
if se <= e:
level += 1
return level
|
[
"Return",
"the",
"nesting",
"level",
"of",
"self",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L406-L420
|
[
"def",
"nesting_level",
"(",
"self",
")",
"->",
"int",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"level",
"=",
"0",
"type_to_spans",
"=",
"self",
".",
"_type_to_spans",
"for",
"type_",
"in",
"(",
"'Template'",
",",
"'ParserFunction'",
")",
":",
"spans",
"=",
"type_to_spans",
"[",
"type_",
"]",
"for",
"s",
",",
"e",
"in",
"spans",
"[",
":",
"bisect",
"(",
"spans",
",",
"[",
"ss",
"+",
"1",
"]",
")",
"]",
":",
"if",
"se",
"<=",
"e",
":",
"level",
"+=",
"1",
"return",
"level"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._shadow
|
Return a copy of self.string with specific sub-spans replaced.
Comments blocks are replaced by spaces. Other sub-spans are replaced
by underscores.
The replaced sub-spans are: (
'Template', 'WikiLink', 'ParserFunction', 'ExtensionTag',
'Comment',
)
This function is called upon extracting tables or extracting the data
inside them.
|
wikitextparser/_wikitext.py
|
def _shadow(self) -> bytearray:
"""Return a copy of self.string with specific sub-spans replaced.
Comments blocks are replaced by spaces. Other sub-spans are replaced
by underscores.
The replaced sub-spans are: (
'Template', 'WikiLink', 'ParserFunction', 'ExtensionTag',
'Comment',
)
This function is called upon extracting tables or extracting the data
inside them.
"""
ss, se = self._span
string = self._lststr[0][ss:se]
cached_string, shadow = getattr(
self, '_shadow_cache', (None, None))
if cached_string == string:
return shadow
# In the old method the existing spans were used to create the shadow.
# But it was slow because there can be thousands of spans and iterating
# over them to find the relevant sub-spans could take a significant
# amount of time. The new method tries to parse the self.string which
# is usually much more faster because there are usually far less
# sub-spans for individual objects.
shadow = bytearray(string, 'ascii', 'replace')
if self._type in SPAN_PARSER_TYPES:
head = shadow[:2]
tail = shadow[-2:]
shadow[:2] = shadow[-2:] = b'__'
parse_to_spans(shadow)
shadow[:2] = head
shadow[-2:] = tail
else:
parse_to_spans(shadow)
self._shadow_cache = string, shadow
return shadow
|
def _shadow(self) -> bytearray:
"""Return a copy of self.string with specific sub-spans replaced.
Comments blocks are replaced by spaces. Other sub-spans are replaced
by underscores.
The replaced sub-spans are: (
'Template', 'WikiLink', 'ParserFunction', 'ExtensionTag',
'Comment',
)
This function is called upon extracting tables or extracting the data
inside them.
"""
ss, se = self._span
string = self._lststr[0][ss:se]
cached_string, shadow = getattr(
self, '_shadow_cache', (None, None))
if cached_string == string:
return shadow
# In the old method the existing spans were used to create the shadow.
# But it was slow because there can be thousands of spans and iterating
# over them to find the relevant sub-spans could take a significant
# amount of time. The new method tries to parse the self.string which
# is usually much more faster because there are usually far less
# sub-spans for individual objects.
shadow = bytearray(string, 'ascii', 'replace')
if self._type in SPAN_PARSER_TYPES:
head = shadow[:2]
tail = shadow[-2:]
shadow[:2] = shadow[-2:] = b'__'
parse_to_spans(shadow)
shadow[:2] = head
shadow[-2:] = tail
else:
parse_to_spans(shadow)
self._shadow_cache = string, shadow
return shadow
|
[
"Return",
"a",
"copy",
"of",
"self",
".",
"string",
"with",
"specific",
"sub",
"-",
"spans",
"replaced",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L423-L460
|
[
"def",
"_shadow",
"(",
"self",
")",
"->",
"bytearray",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"string",
"=",
"self",
".",
"_lststr",
"[",
"0",
"]",
"[",
"ss",
":",
"se",
"]",
"cached_string",
",",
"shadow",
"=",
"getattr",
"(",
"self",
",",
"'_shadow_cache'",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"cached_string",
"==",
"string",
":",
"return",
"shadow",
"# In the old method the existing spans were used to create the shadow.",
"# But it was slow because there can be thousands of spans and iterating",
"# over them to find the relevant sub-spans could take a significant",
"# amount of time. The new method tries to parse the self.string which",
"# is usually much more faster because there are usually far less",
"# sub-spans for individual objects.",
"shadow",
"=",
"bytearray",
"(",
"string",
",",
"'ascii'",
",",
"'replace'",
")",
"if",
"self",
".",
"_type",
"in",
"SPAN_PARSER_TYPES",
":",
"head",
"=",
"shadow",
"[",
":",
"2",
"]",
"tail",
"=",
"shadow",
"[",
"-",
"2",
":",
"]",
"shadow",
"[",
":",
"2",
"]",
"=",
"shadow",
"[",
"-",
"2",
":",
"]",
"=",
"b'__'",
"parse_to_spans",
"(",
"shadow",
")",
"shadow",
"[",
":",
"2",
"]",
"=",
"head",
"shadow",
"[",
"-",
"2",
":",
"]",
"=",
"tail",
"else",
":",
"parse_to_spans",
"(",
"shadow",
")",
"self",
".",
"_shadow_cache",
"=",
"string",
",",
"shadow",
"return",
"shadow"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._ext_link_shadow
|
Replace the invalid chars of SPAN_PARSER_TYPES with b'_'.
For comments, all characters are replaced, but for ('Template',
'ParserFunction', 'Parameter') only invalid characters are replaced.
|
wikitextparser/_wikitext.py
|
def _ext_link_shadow(self):
"""Replace the invalid chars of SPAN_PARSER_TYPES with b'_'.
For comments, all characters are replaced, but for ('Template',
'ParserFunction', 'Parameter') only invalid characters are replaced.
"""
ss, se = self._span
string = self._lststr[0][ss:se]
byte_array = bytearray(string, 'ascii', 'replace')
subspans = self._subspans
for type_ in 'Template', 'ParserFunction', 'Parameter':
for s, e in subspans(type_):
byte_array[s:e] = b' ' + INVALID_EXT_CHARS_SUB(
b' ', byte_array[s + 2:e - 2]) + b' '
for s, e in subspans('Comment'):
byte_array[s:e] = (e - s) * b'_'
return byte_array
|
def _ext_link_shadow(self):
"""Replace the invalid chars of SPAN_PARSER_TYPES with b'_'.
For comments, all characters are replaced, but for ('Template',
'ParserFunction', 'Parameter') only invalid characters are replaced.
"""
ss, se = self._span
string = self._lststr[0][ss:se]
byte_array = bytearray(string, 'ascii', 'replace')
subspans = self._subspans
for type_ in 'Template', 'ParserFunction', 'Parameter':
for s, e in subspans(type_):
byte_array[s:e] = b' ' + INVALID_EXT_CHARS_SUB(
b' ', byte_array[s + 2:e - 2]) + b' '
for s, e in subspans('Comment'):
byte_array[s:e] = (e - s) * b'_'
return byte_array
|
[
"Replace",
"the",
"invalid",
"chars",
"of",
"SPAN_PARSER_TYPES",
"with",
"b",
"_",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L463-L479
|
[
"def",
"_ext_link_shadow",
"(",
"self",
")",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"string",
"=",
"self",
".",
"_lststr",
"[",
"0",
"]",
"[",
"ss",
":",
"se",
"]",
"byte_array",
"=",
"bytearray",
"(",
"string",
",",
"'ascii'",
",",
"'replace'",
")",
"subspans",
"=",
"self",
".",
"_subspans",
"for",
"type_",
"in",
"'Template'",
",",
"'ParserFunction'",
",",
"'Parameter'",
":",
"for",
"s",
",",
"e",
"in",
"subspans",
"(",
"type_",
")",
":",
"byte_array",
"[",
"s",
":",
"e",
"]",
"=",
"b' '",
"+",
"INVALID_EXT_CHARS_SUB",
"(",
"b' '",
",",
"byte_array",
"[",
"s",
"+",
"2",
":",
"e",
"-",
"2",
"]",
")",
"+",
"b' '",
"for",
"s",
",",
"e",
"in",
"subspans",
"(",
"'Comment'",
")",
":",
"byte_array",
"[",
"s",
":",
"e",
"]",
"=",
"(",
"e",
"-",
"s",
")",
"*",
"b'_'",
"return",
"byte_array"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText._pp_type_to_spans
|
Create the arguments for the parse function used in pformat method.
Only return sub-spans and change the them to fit the new scope, i.e
self.string.
|
wikitextparser/_wikitext.py
|
def _pp_type_to_spans(self) -> Dict[str, List[List[int]]]:
"""Create the arguments for the parse function used in pformat method.
Only return sub-spans and change the them to fit the new scope, i.e
self.string.
"""
ss, se = self._span
if ss == 0 and se == len(self._lststr[0]):
return deepcopy(self._type_to_spans)
return {
type_: [
[s - ss, e - ss] for s, e in spans[bisect(spans, [ss]):]
if e <= se
] for type_, spans in self._type_to_spans.items()}
|
def _pp_type_to_spans(self) -> Dict[str, List[List[int]]]:
"""Create the arguments for the parse function used in pformat method.
Only return sub-spans and change the them to fit the new scope, i.e
self.string.
"""
ss, se = self._span
if ss == 0 and se == len(self._lststr[0]):
return deepcopy(self._type_to_spans)
return {
type_: [
[s - ss, e - ss] for s, e in spans[bisect(spans, [ss]):]
if e <= se
] for type_, spans in self._type_to_spans.items()}
|
[
"Create",
"the",
"arguments",
"for",
"the",
"parse",
"function",
"used",
"in",
"pformat",
"method",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L481-L494
|
[
"def",
"_pp_type_to_spans",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"List",
"[",
"int",
"]",
"]",
"]",
":",
"ss",
",",
"se",
"=",
"self",
".",
"_span",
"if",
"ss",
"==",
"0",
"and",
"se",
"==",
"len",
"(",
"self",
".",
"_lststr",
"[",
"0",
"]",
")",
":",
"return",
"deepcopy",
"(",
"self",
".",
"_type_to_spans",
")",
"return",
"{",
"type_",
":",
"[",
"[",
"s",
"-",
"ss",
",",
"e",
"-",
"ss",
"]",
"for",
"s",
",",
"e",
"in",
"spans",
"[",
"bisect",
"(",
"spans",
",",
"[",
"ss",
"]",
")",
":",
"]",
"if",
"e",
"<=",
"se",
"]",
"for",
"type_",
",",
"spans",
"in",
"self",
".",
"_type_to_spans",
".",
"items",
"(",
")",
"}"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText.pprint
|
Deprecated, use self.pformat instead.
|
wikitextparser/_wikitext.py
|
def pprint(self, indent: str = ' ', remove_comments=False):
"""Deprecated, use self.pformat instead."""
warn(
'pprint method is deprecated, use pformat instead.',
DeprecationWarning,
)
return self.pformat(indent, remove_comments)
|
def pprint(self, indent: str = ' ', remove_comments=False):
"""Deprecated, use self.pformat instead."""
warn(
'pprint method is deprecated, use pformat instead.',
DeprecationWarning,
)
return self.pformat(indent, remove_comments)
|
[
"Deprecated",
"use",
"self",
".",
"pformat",
"instead",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L496-L502
|
[
"def",
"pprint",
"(",
"self",
",",
"indent",
":",
"str",
"=",
"' '",
",",
"remove_comments",
"=",
"False",
")",
":",
"warn",
"(",
"'pprint method is deprecated, use pformat instead.'",
",",
"DeprecationWarning",
",",
")",
"return",
"self",
".",
"pformat",
"(",
"indent",
",",
"remove_comments",
")"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
test
|
WikiText.pformat
|
Return a pretty-print of self.string as string.
Try to organize templates and parser functions by indenting, aligning
at the equal signs, and adding space where appropriate.
Note that this function will not mutate self.
|
wikitextparser/_wikitext.py
|
def pformat(self, indent: str = ' ', remove_comments=False) -> str:
"""Return a pretty-print of self.string as string.
Try to organize templates and parser functions by indenting, aligning
at the equal signs, and adding space where appropriate.
Note that this function will not mutate self.
"""
ws = WS
# Do not try to do inplace pformat. It will overwrite on some spans.
string = self.string
parsed = WikiText([string], self._pp_type_to_spans())
# Since _type_to_spans arg of WikiText has been used, parsed._span
# is not set yet.
span = [0, len(string)]
parsed._span = span
parsed._type_to_spans['WikiText'] = [span]
if remove_comments:
for c in parsed.comments:
del c[:]
else:
# Only remove comments that contain whitespace.
for c in parsed.comments:
if not c.contents.strip(ws):
del c[:]
# First remove all current spacings.
for template in reversed(parsed.templates):
stripped_tl_name = template.name.strip(ws)
template.name = (
' ' + stripped_tl_name + ' '
if stripped_tl_name[0] == '{' else stripped_tl_name
)
args = template.arguments
if not args:
continue
if ':' in stripped_tl_name:
# Don't use False because we don't know for sure.
not_a_parser_function = None
else:
not_a_parser_function = True
# Required for alignment
arg_stripped_names = [a.name.strip(ws) for a in args]
arg_positionalities = [a.positional for a in args]
arg_name_lengths = [
wcswidth(n.replace('لا', '?'))
if not p else 0
for n, p in zip(arg_stripped_names, arg_positionalities)
]
max_name_len = max(arg_name_lengths)
# Format template.name.
level = template.nesting_level
newline_indent = '\n' + indent * level
template.name += newline_indent
if level == 1:
last_comment_indent = '<!--\n-->'
else:
last_comment_indent = '<!--\n' + indent * (level - 2) + ' -->'
# Special formatting for the last argument.
last_arg = args.pop()
last_is_positional = arg_positionalities.pop()
last_value = last_arg.value
last_stripped_value = last_value.strip(ws)
if last_is_positional and last_value != last_stripped_value:
stop_conversion = True
if not last_value.endswith('\n' + indent * (level - 1)):
last_arg.value = last_value + last_comment_indent
elif not_a_parser_function:
stop_conversion = False
last_arg.name = (
' ' + arg_stripped_names.pop() + ' ' +
' ' * (max_name_len - arg_name_lengths.pop()))
last_arg.value = (
' ' + last_stripped_value + '\n' + indent * (level - 1))
elif last_is_positional:
# (last_value == last_stripped_value
# and not_a_parser_function is not True)
stop_conversion = True
# Can't strip or adjust the position of the value
# because this could be a positional argument in a template.
last_arg.value = last_value + last_comment_indent
else:
stop_conversion = True
# This is either a parser function or a keyword
# argument in a template. In both cases the name
# can be lstripped and the value can be rstripped.
last_arg.name = ' ' + last_arg.name.lstrip(ws)
if not last_value.endswith('\n' + indent * (level - 1)):
last_arg.value = (
last_value.rstrip(ws) + ' ' + last_comment_indent)
if not args:
continue
comment_indent = '<!--\n' + indent * (level - 1) + ' -->'
for arg, stripped_name, positional, arg_name_len in zip(
reversed(args),
reversed(arg_stripped_names),
reversed(arg_positionalities),
reversed(arg_name_lengths),
):
value = arg.value
stripped_value = value.strip(ws)
# Positional arguments of templates are sensitive to
# whitespace. See:
# https://meta.wikimedia.org/wiki/Help:Newlines_and_spaces
if stop_conversion:
if not value.endswith(newline_indent):
arg.value += comment_indent
elif positional and value != stripped_value:
stop_conversion = True
if not value.endswith(newline_indent):
arg.value += comment_indent
elif not_a_parser_function:
arg.name = (
' ' + stripped_name + ' ' +
' ' * (max_name_len - arg_name_len))
arg.value = ' ' + stripped_value + newline_indent
i = 0
functions = parsed.parser_functions
while i < len(functions):
func = functions[i]
i += 1
name = func.name
ls_name = name.lstrip(ws)
lws = len(name) - len(ls_name)
if lws:
del func[2:lws + 2]
if ls_name.lower() in ('#tag', '#invoke', ''):
# The 2nd argument of `tag` parser function is an exception
# and cannot be stripped.
# So in `{{#tag:tagname|arg1|...}}`, no whitespace should be
# added/removed to/from arg1.
# See: [[mw:Help:Extension:ParserFunctions#Miscellaneous]]
# All args of #invoke are also whitespace-sensitive.
# Todo: Instead use comments to indent.
continue
args = func.arguments
# Whitespace, including newlines, tabs, and spaces is stripped
# from the beginning and end of all the parameters of
# parser functions. See:
# www.mediawiki.org/wiki/Help:Extension:ParserFunctions#
# Stripping_whitespace
level = func.nesting_level
short_indent = '\n' + indent * (level - 1)
newline_indent = short_indent + indent
if len(args) == 1:
arg = args[0]
# the first arg is both the first and last argument
if arg.positional:
arg.value = (
newline_indent + arg.value.strip(ws) + short_indent)
else:
# Note that we don't add spaces before and after the
# '=' in parser functions because it could be part of
# an ordinary string.
arg.name = newline_indent + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + short_indent
functions = parsed.parser_functions
continue
# Special formatting for the first argument
arg = args[0]
if arg.positional:
arg.value = \
newline_indent + arg.value.strip(ws) + newline_indent
else:
arg.name = newline_indent + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + newline_indent
# Formatting the middle arguments
for arg in args[1:-1]:
if arg.positional:
arg.value = ' ' + arg.value.strip(ws) + newline_indent
else:
arg.name = ' ' + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + newline_indent
# Special formatting for the last argument
arg = args[-1]
if arg.positional:
arg.value = ' ' + arg.value.strip(ws) + short_indent
else:
arg.name = ' ' + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + short_indent
functions = parsed.parser_functions
return parsed.string
|
def pformat(self, indent: str = ' ', remove_comments=False) -> str:
"""Return a pretty-print of self.string as string.
Try to organize templates and parser functions by indenting, aligning
at the equal signs, and adding space where appropriate.
Note that this function will not mutate self.
"""
ws = WS
# Do not try to do inplace pformat. It will overwrite on some spans.
string = self.string
parsed = WikiText([string], self._pp_type_to_spans())
# Since _type_to_spans arg of WikiText has been used, parsed._span
# is not set yet.
span = [0, len(string)]
parsed._span = span
parsed._type_to_spans['WikiText'] = [span]
if remove_comments:
for c in parsed.comments:
del c[:]
else:
# Only remove comments that contain whitespace.
for c in parsed.comments:
if not c.contents.strip(ws):
del c[:]
# First remove all current spacings.
for template in reversed(parsed.templates):
stripped_tl_name = template.name.strip(ws)
template.name = (
' ' + stripped_tl_name + ' '
if stripped_tl_name[0] == '{' else stripped_tl_name
)
args = template.arguments
if not args:
continue
if ':' in stripped_tl_name:
# Don't use False because we don't know for sure.
not_a_parser_function = None
else:
not_a_parser_function = True
# Required for alignment
arg_stripped_names = [a.name.strip(ws) for a in args]
arg_positionalities = [a.positional for a in args]
arg_name_lengths = [
wcswidth(n.replace('لا', '?'))
if not p else 0
for n, p in zip(arg_stripped_names, arg_positionalities)
]
max_name_len = max(arg_name_lengths)
# Format template.name.
level = template.nesting_level
newline_indent = '\n' + indent * level
template.name += newline_indent
if level == 1:
last_comment_indent = '<!--\n-->'
else:
last_comment_indent = '<!--\n' + indent * (level - 2) + ' -->'
# Special formatting for the last argument.
last_arg = args.pop()
last_is_positional = arg_positionalities.pop()
last_value = last_arg.value
last_stripped_value = last_value.strip(ws)
if last_is_positional and last_value != last_stripped_value:
stop_conversion = True
if not last_value.endswith('\n' + indent * (level - 1)):
last_arg.value = last_value + last_comment_indent
elif not_a_parser_function:
stop_conversion = False
last_arg.name = (
' ' + arg_stripped_names.pop() + ' ' +
' ' * (max_name_len - arg_name_lengths.pop()))
last_arg.value = (
' ' + last_stripped_value + '\n' + indent * (level - 1))
elif last_is_positional:
# (last_value == last_stripped_value
# and not_a_parser_function is not True)
stop_conversion = True
# Can't strip or adjust the position of the value
# because this could be a positional argument in a template.
last_arg.value = last_value + last_comment_indent
else:
stop_conversion = True
# This is either a parser function or a keyword
# argument in a template. In both cases the name
# can be lstripped and the value can be rstripped.
last_arg.name = ' ' + last_arg.name.lstrip(ws)
if not last_value.endswith('\n' + indent * (level - 1)):
last_arg.value = (
last_value.rstrip(ws) + ' ' + last_comment_indent)
if not args:
continue
comment_indent = '<!--\n' + indent * (level - 1) + ' -->'
for arg, stripped_name, positional, arg_name_len in zip(
reversed(args),
reversed(arg_stripped_names),
reversed(arg_positionalities),
reversed(arg_name_lengths),
):
value = arg.value
stripped_value = value.strip(ws)
# Positional arguments of templates are sensitive to
# whitespace. See:
# https://meta.wikimedia.org/wiki/Help:Newlines_and_spaces
if stop_conversion:
if not value.endswith(newline_indent):
arg.value += comment_indent
elif positional and value != stripped_value:
stop_conversion = True
if not value.endswith(newline_indent):
arg.value += comment_indent
elif not_a_parser_function:
arg.name = (
' ' + stripped_name + ' ' +
' ' * (max_name_len - arg_name_len))
arg.value = ' ' + stripped_value + newline_indent
i = 0
functions = parsed.parser_functions
while i < len(functions):
func = functions[i]
i += 1
name = func.name
ls_name = name.lstrip(ws)
lws = len(name) - len(ls_name)
if lws:
del func[2:lws + 2]
if ls_name.lower() in ('#tag', '#invoke', ''):
# The 2nd argument of `tag` parser function is an exception
# and cannot be stripped.
# So in `{{#tag:tagname|arg1|...}}`, no whitespace should be
# added/removed to/from arg1.
# See: [[mw:Help:Extension:ParserFunctions#Miscellaneous]]
# All args of #invoke are also whitespace-sensitive.
# Todo: Instead use comments to indent.
continue
args = func.arguments
# Whitespace, including newlines, tabs, and spaces is stripped
# from the beginning and end of all the parameters of
# parser functions. See:
# www.mediawiki.org/wiki/Help:Extension:ParserFunctions#
# Stripping_whitespace
level = func.nesting_level
short_indent = '\n' + indent * (level - 1)
newline_indent = short_indent + indent
if len(args) == 1:
arg = args[0]
# the first arg is both the first and last argument
if arg.positional:
arg.value = (
newline_indent + arg.value.strip(ws) + short_indent)
else:
# Note that we don't add spaces before and after the
# '=' in parser functions because it could be part of
# an ordinary string.
arg.name = newline_indent + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + short_indent
functions = parsed.parser_functions
continue
# Special formatting for the first argument
arg = args[0]
if arg.positional:
arg.value = \
newline_indent + arg.value.strip(ws) + newline_indent
else:
arg.name = newline_indent + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + newline_indent
# Formatting the middle arguments
for arg in args[1:-1]:
if arg.positional:
arg.value = ' ' + arg.value.strip(ws) + newline_indent
else:
arg.name = ' ' + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + newline_indent
# Special formatting for the last argument
arg = args[-1]
if arg.positional:
arg.value = ' ' + arg.value.strip(ws) + short_indent
else:
arg.name = ' ' + arg.name.lstrip(ws)
arg.value = arg.value.rstrip(ws) + short_indent
functions = parsed.parser_functions
return parsed.string
|
[
"Return",
"a",
"pretty",
"-",
"print",
"of",
"self",
".",
"string",
"as",
"string",
"."
] |
5j9/wikitextparser
|
python
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L504-L684
|
[
"def",
"pformat",
"(",
"self",
",",
"indent",
":",
"str",
"=",
"' '",
",",
"remove_comments",
"=",
"False",
")",
"->",
"str",
":",
"ws",
"=",
"WS",
"# Do not try to do inplace pformat. It will overwrite on some spans.",
"string",
"=",
"self",
".",
"string",
"parsed",
"=",
"WikiText",
"(",
"[",
"string",
"]",
",",
"self",
".",
"_pp_type_to_spans",
"(",
")",
")",
"# Since _type_to_spans arg of WikiText has been used, parsed._span",
"# is not set yet.",
"span",
"=",
"[",
"0",
",",
"len",
"(",
"string",
")",
"]",
"parsed",
".",
"_span",
"=",
"span",
"parsed",
".",
"_type_to_spans",
"[",
"'WikiText'",
"]",
"=",
"[",
"span",
"]",
"if",
"remove_comments",
":",
"for",
"c",
"in",
"parsed",
".",
"comments",
":",
"del",
"c",
"[",
":",
"]",
"else",
":",
"# Only remove comments that contain whitespace.",
"for",
"c",
"in",
"parsed",
".",
"comments",
":",
"if",
"not",
"c",
".",
"contents",
".",
"strip",
"(",
"ws",
")",
":",
"del",
"c",
"[",
":",
"]",
"# First remove all current spacings.",
"for",
"template",
"in",
"reversed",
"(",
"parsed",
".",
"templates",
")",
":",
"stripped_tl_name",
"=",
"template",
".",
"name",
".",
"strip",
"(",
"ws",
")",
"template",
".",
"name",
"=",
"(",
"' '",
"+",
"stripped_tl_name",
"+",
"' '",
"if",
"stripped_tl_name",
"[",
"0",
"]",
"==",
"'{'",
"else",
"stripped_tl_name",
")",
"args",
"=",
"template",
".",
"arguments",
"if",
"not",
"args",
":",
"continue",
"if",
"':'",
"in",
"stripped_tl_name",
":",
"# Don't use False because we don't know for sure.",
"not_a_parser_function",
"=",
"None",
"else",
":",
"not_a_parser_function",
"=",
"True",
"# Required for alignment",
"arg_stripped_names",
"=",
"[",
"a",
".",
"name",
".",
"strip",
"(",
"ws",
")",
"for",
"a",
"in",
"args",
"]",
"arg_positionalities",
"=",
"[",
"a",
".",
"positional",
"for",
"a",
"in",
"args",
"]",
"arg_name_lengths",
"=",
"[",
"wcswidth",
"(",
"n",
".",
"replace",
"(",
"'لا', ",
"'",
"'))",
"",
"",
"if",
"not",
"p",
"else",
"0",
"for",
"n",
",",
"p",
"in",
"zip",
"(",
"arg_stripped_names",
",",
"arg_positionalities",
")",
"]",
"max_name_len",
"=",
"max",
"(",
"arg_name_lengths",
")",
"# Format template.name.",
"level",
"=",
"template",
".",
"nesting_level",
"newline_indent",
"=",
"'\\n'",
"+",
"indent",
"*",
"level",
"template",
".",
"name",
"+=",
"newline_indent",
"if",
"level",
"==",
"1",
":",
"last_comment_indent",
"=",
"'<!--\\n-->'",
"else",
":",
"last_comment_indent",
"=",
"'<!--\\n'",
"+",
"indent",
"*",
"(",
"level",
"-",
"2",
")",
"+",
"' -->'",
"# Special formatting for the last argument.",
"last_arg",
"=",
"args",
".",
"pop",
"(",
")",
"last_is_positional",
"=",
"arg_positionalities",
".",
"pop",
"(",
")",
"last_value",
"=",
"last_arg",
".",
"value",
"last_stripped_value",
"=",
"last_value",
".",
"strip",
"(",
"ws",
")",
"if",
"last_is_positional",
"and",
"last_value",
"!=",
"last_stripped_value",
":",
"stop_conversion",
"=",
"True",
"if",
"not",
"last_value",
".",
"endswith",
"(",
"'\\n'",
"+",
"indent",
"*",
"(",
"level",
"-",
"1",
")",
")",
":",
"last_arg",
".",
"value",
"=",
"last_value",
"+",
"last_comment_indent",
"elif",
"not_a_parser_function",
":",
"stop_conversion",
"=",
"False",
"last_arg",
".",
"name",
"=",
"(",
"' '",
"+",
"arg_stripped_names",
".",
"pop",
"(",
")",
"+",
"' '",
"+",
"' '",
"*",
"(",
"max_name_len",
"-",
"arg_name_lengths",
".",
"pop",
"(",
")",
")",
")",
"last_arg",
".",
"value",
"=",
"(",
"' '",
"+",
"last_stripped_value",
"+",
"'\\n'",
"+",
"indent",
"*",
"(",
"level",
"-",
"1",
")",
")",
"elif",
"last_is_positional",
":",
"# (last_value == last_stripped_value",
"# and not_a_parser_function is not True)",
"stop_conversion",
"=",
"True",
"# Can't strip or adjust the position of the value",
"# because this could be a positional argument in a template.",
"last_arg",
".",
"value",
"=",
"last_value",
"+",
"last_comment_indent",
"else",
":",
"stop_conversion",
"=",
"True",
"# This is either a parser function or a keyword",
"# argument in a template. In both cases the name",
"# can be lstripped and the value can be rstripped.",
"last_arg",
".",
"name",
"=",
"' '",
"+",
"last_arg",
".",
"name",
".",
"lstrip",
"(",
"ws",
")",
"if",
"not",
"last_value",
".",
"endswith",
"(",
"'\\n'",
"+",
"indent",
"*",
"(",
"level",
"-",
"1",
")",
")",
":",
"last_arg",
".",
"value",
"=",
"(",
"last_value",
".",
"rstrip",
"(",
"ws",
")",
"+",
"' '",
"+",
"last_comment_indent",
")",
"if",
"not",
"args",
":",
"continue",
"comment_indent",
"=",
"'<!--\\n'",
"+",
"indent",
"*",
"(",
"level",
"-",
"1",
")",
"+",
"' -->'",
"for",
"arg",
",",
"stripped_name",
",",
"positional",
",",
"arg_name_len",
"in",
"zip",
"(",
"reversed",
"(",
"args",
")",
",",
"reversed",
"(",
"arg_stripped_names",
")",
",",
"reversed",
"(",
"arg_positionalities",
")",
",",
"reversed",
"(",
"arg_name_lengths",
")",
",",
")",
":",
"value",
"=",
"arg",
".",
"value",
"stripped_value",
"=",
"value",
".",
"strip",
"(",
"ws",
")",
"# Positional arguments of templates are sensitive to",
"# whitespace. See:",
"# https://meta.wikimedia.org/wiki/Help:Newlines_and_spaces",
"if",
"stop_conversion",
":",
"if",
"not",
"value",
".",
"endswith",
"(",
"newline_indent",
")",
":",
"arg",
".",
"value",
"+=",
"comment_indent",
"elif",
"positional",
"and",
"value",
"!=",
"stripped_value",
":",
"stop_conversion",
"=",
"True",
"if",
"not",
"value",
".",
"endswith",
"(",
"newline_indent",
")",
":",
"arg",
".",
"value",
"+=",
"comment_indent",
"elif",
"not_a_parser_function",
":",
"arg",
".",
"name",
"=",
"(",
"' '",
"+",
"stripped_name",
"+",
"' '",
"+",
"' '",
"*",
"(",
"max_name_len",
"-",
"arg_name_len",
")",
")",
"arg",
".",
"value",
"=",
"' '",
"+",
"stripped_value",
"+",
"newline_indent",
"i",
"=",
"0",
"functions",
"=",
"parsed",
".",
"parser_functions",
"while",
"i",
"<",
"len",
"(",
"functions",
")",
":",
"func",
"=",
"functions",
"[",
"i",
"]",
"i",
"+=",
"1",
"name",
"=",
"func",
".",
"name",
"ls_name",
"=",
"name",
".",
"lstrip",
"(",
"ws",
")",
"lws",
"=",
"len",
"(",
"name",
")",
"-",
"len",
"(",
"ls_name",
")",
"if",
"lws",
":",
"del",
"func",
"[",
"2",
":",
"lws",
"+",
"2",
"]",
"if",
"ls_name",
".",
"lower",
"(",
")",
"in",
"(",
"'#tag'",
",",
"'#invoke'",
",",
"''",
")",
":",
"# The 2nd argument of `tag` parser function is an exception",
"# and cannot be stripped.",
"# So in `{{#tag:tagname|arg1|...}}`, no whitespace should be",
"# added/removed to/from arg1.",
"# See: [[mw:Help:Extension:ParserFunctions#Miscellaneous]]",
"# All args of #invoke are also whitespace-sensitive.",
"# Todo: Instead use comments to indent.",
"continue",
"args",
"=",
"func",
".",
"arguments",
"# Whitespace, including newlines, tabs, and spaces is stripped",
"# from the beginning and end of all the parameters of",
"# parser functions. See:",
"# www.mediawiki.org/wiki/Help:Extension:ParserFunctions#",
"# Stripping_whitespace",
"level",
"=",
"func",
".",
"nesting_level",
"short_indent",
"=",
"'\\n'",
"+",
"indent",
"*",
"(",
"level",
"-",
"1",
")",
"newline_indent",
"=",
"short_indent",
"+",
"indent",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"arg",
"=",
"args",
"[",
"0",
"]",
"# the first arg is both the first and last argument",
"if",
"arg",
".",
"positional",
":",
"arg",
".",
"value",
"=",
"(",
"newline_indent",
"+",
"arg",
".",
"value",
".",
"strip",
"(",
"ws",
")",
"+",
"short_indent",
")",
"else",
":",
"# Note that we don't add spaces before and after the",
"# '=' in parser functions because it could be part of",
"# an ordinary string.",
"arg",
".",
"name",
"=",
"newline_indent",
"+",
"arg",
".",
"name",
".",
"lstrip",
"(",
"ws",
")",
"arg",
".",
"value",
"=",
"arg",
".",
"value",
".",
"rstrip",
"(",
"ws",
")",
"+",
"short_indent",
"functions",
"=",
"parsed",
".",
"parser_functions",
"continue",
"# Special formatting for the first argument",
"arg",
"=",
"args",
"[",
"0",
"]",
"if",
"arg",
".",
"positional",
":",
"arg",
".",
"value",
"=",
"newline_indent",
"+",
"arg",
".",
"value",
".",
"strip",
"(",
"ws",
")",
"+",
"newline_indent",
"else",
":",
"arg",
".",
"name",
"=",
"newline_indent",
"+",
"arg",
".",
"name",
".",
"lstrip",
"(",
"ws",
")",
"arg",
".",
"value",
"=",
"arg",
".",
"value",
".",
"rstrip",
"(",
"ws",
")",
"+",
"newline_indent",
"# Formatting the middle arguments",
"for",
"arg",
"in",
"args",
"[",
"1",
":",
"-",
"1",
"]",
":",
"if",
"arg",
".",
"positional",
":",
"arg",
".",
"value",
"=",
"' '",
"+",
"arg",
".",
"value",
".",
"strip",
"(",
"ws",
")",
"+",
"newline_indent",
"else",
":",
"arg",
".",
"name",
"=",
"' '",
"+",
"arg",
".",
"name",
".",
"lstrip",
"(",
"ws",
")",
"arg",
".",
"value",
"=",
"arg",
".",
"value",
".",
"rstrip",
"(",
"ws",
")",
"+",
"newline_indent",
"# Special formatting for the last argument",
"arg",
"=",
"args",
"[",
"-",
"1",
"]",
"if",
"arg",
".",
"positional",
":",
"arg",
".",
"value",
"=",
"' '",
"+",
"arg",
".",
"value",
".",
"strip",
"(",
"ws",
")",
"+",
"short_indent",
"else",
":",
"arg",
".",
"name",
"=",
"' '",
"+",
"arg",
".",
"name",
".",
"lstrip",
"(",
"ws",
")",
"arg",
".",
"value",
"=",
"arg",
".",
"value",
".",
"rstrip",
"(",
"ws",
")",
"+",
"short_indent",
"functions",
"=",
"parsed",
".",
"parser_functions",
"return",
"parsed",
".",
"string"
] |
1347425814361d7955342c53212edbb27f0ff4b5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.