_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q271000
PJFMutators.safe_unicode
test
def safe_unicode(self, buf): """ Safely return an unicode encoded string """ tmp = "" buf = "".join(b for b in buf) for character in buf: tmp += character return tmp
python
{ "resource": "" }
q271001
PJFServer.run
test
def run(self): """ Start the servers """ route("/")(self.serve) if self.config.html: route("/<filepath:path>")(self.custom_html) if self.config.fuzz_web: self.request_checker.start() self.httpd.start() self.httpsd.start()
python
{ "resource": "" }
q271002
PJFServer.stop
test
def stop(self): """ Kill the servers """ os.kill(self.httpd.pid, signal.SIGKILL) os.kill(self.httpsd.pid, signal.SIGKILL) self.client_queue.put((0,0)) if self.config.fuzz_web: self.request_checker.join() self.logger.debug("[{0}] - PJFServer successfully completed".format(time.strftime("%H:%M:%S")))
python
{ "resource": "" }
q271003
PJFServer.custom_html
test
def custom_html(self, filepath): """ Serve custom HTML page """ try: response.headers.append("Access-Control-Allow-Origin", "*") response.headers.append("Accept-Encoding", "identity") response.headers.append("Content-Type", "text/html") return static_file(filepath, root=self.config.html) except Exception as e: raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
python
{ "resource": "" }
q271004
PJFServer.serve
test
def serve(self): """ Serve fuzzed JSON object """ try: fuzzed = self.json.fuzzed if self.config.fuzz_web: self.client_queue.put((request.environ.get('REMOTE_ADDR'), fuzzed)) response.headers.append("Access-Control-Allow-Origin", "*") response.headers.append("Accept-Encoding", "identity") response.headers.append("Content-Type", self.config.content_type) if self.config.notify: PJFTestcaseServer.send_testcase(fuzzed, '127.0.0.1', self.config.ports["servers"]["TCASE_PORT"]) yield fuzzed except Exception as e: raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
python
{ "resource": "" }
q271005
PJFMutation.fuzz
test
def fuzz(self, obj): """ Generic fuzz mutator, use a decorator for the given type """ decorators = self.decorators @decorators.mutate_object_decorate def mutate(): return obj return mutate()
python
{ "resource": "" }
q271006
PJFExecutor.spawn
test
def spawn(self, cmd, stdin_content="", stdin=False, shell=False, timeout=2): """ Spawn a new process using subprocess """ try: if type(cmd) != list: raise PJFInvalidType(type(cmd), list) if type(stdin_content) != str: raise PJFInvalidType(type(stdin_content), str) if type(stdin) != bool: raise PJFInvalidType(type(stdin), bool) self._in = stdin_content try: self.process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=shell) self.finish_read(timeout, stdin_content, stdin) if self.process.poll() is not None: self.close() except KeyboardInterrupt: return except OSError: raise PJFProcessExecutionError("Binary <%s> does not exist" % cmd[0]) except Exception as e: raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
python
{ "resource": "" }
q271007
PJFExecutor.get_output
test
def get_output(self, stdin_content, stdin): """ Try to get output in a separate thread """ try: if stdin: if sys.version_info >= (3, 0): self.process.stdin.write(bytes(stdin_content, "utf-8")) else: self.process.stdin.write(stdin_content) self._out = self.process.communicate()[0] except (error, IOError): self._out = self._in pass
python
{ "resource": "" }
q271008
PJFExecutor.finish_read
test
def finish_read(self, timeout=2, stdin_content="", stdin=False): """ Wait until we got output or until timeout is over """ process = Thread(target=self.get_output, args=(stdin_content, stdin)) process.start() if timeout > 0: process.join(timeout) else: process.join() if process.is_alive(): self.close() self.return_code = -signal.SIGHUP else: self.return_code = self.process.returncode
python
{ "resource": "" }
q271009
PJFExecutor.close
test
def close(self): """ Terminate the newly created process """ try: self.process.terminate() self.return_code = self.process.returncode except OSError: pass self.process.stdin.close() self.process.stdout.close() self.process.stderr.close() self.logger.debug("[{0}] - PJFExecutor successfully completed".format(time.strftime("%H:%M:%S")))
python
{ "resource": "" }
q271010
PJFConfiguration.start
test
def start(self): """ Parse the command line and start PyJFuzz """ from .pjf_worker import PJFWorker worker = PJFWorker(self) if self.update_pjf: worker.update_library() elif self.browser_auto: worker.browser_autopwn() elif self.fuzz_web: worker.web_fuzzer() elif self.json: if not self.web_server and not self.ext_fuzz and not self.cmd_fuzz: worker.fuzz() elif self.ext_fuzz: if self.stdin: worker.fuzz_stdin() else: worker.fuzz_command_line() elif self.cmd_fuzz: if self.stdin: worker.fuzz_external(True) else: worker.fuzz_external() else: worker.start_http_server() elif self.json_file: worker.start_file_fuzz() elif self.process_to_monitor: worker.start_process_monitor()
python
{ "resource": "" }
q271011
PJFExternalFuzzer.execute
test
def execute(self, obj): """ Perform the actual external fuzzing, you may replace this method in order to increase performance """ try: if self.config.stdin: self.spawn(self.config.command, stdin_content=obj, stdin=True, timeout=1) else: if "@@" not in self.config.command: raise PJFMissingArgument("Missing @@ filename indicator while using non-stdin fuzzing method") for x in self.config.command: if "@@" in x: self.config.command[self.config.command.index(x)] = x.replace("@@", obj) self.spawn(self.config.command, timeout=2) self.logger.debug("[{0}] - PJFExternalFuzzer successfully completed".format(time.strftime("%H:%M:%S"))) return self._out except KeyboardInterrupt: return "" except Exception as e: raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
python
{ "resource": "" }
q271012
PJFEncoder.json_encode
test
def json_encode(func): """ Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable """ def func_wrapper(self, indent, utf8): if utf8: encoding = "\\x%02x" else: encoding = "\\u%04x" hex_regex = re.compile(r"(\\\\x[a-fA-F0-9]{2})") unicode_regex = re.compile(r"(\\u[a-fA-F0-9]{4})") def encode_decode_all(d, _decode=True): if type(d) == dict: for k in d: if type(d[k]) in [dict, list]: if _decode: d[k] = encode_decode_all(d[k]) else: d[k] = encode_decode_all(d[k], _decode=False) elif type(d[k]) == str: if _decode: d[k] = decode(d[k]) else: d[k] = encode(d[k]) elif type(d) == list: arr = [] for e in d: if type(e) == str: if _decode: arr.append(decode(e)) else: arr.append(encode(e)) elif type(e) in [dict, list]: if _decode: arr.append(encode_decode_all(e)) else: arr.append(encode_decode_all(e, _decode=False)) else: arr.append(e) return arr else: if _decode: return decode(d) else: return encode(d) return d def decode(x): tmp = "".join(encoding % ord(c) if c not in p else c for c in x) if sys.version_info >= (3, 0): return str(tmp) else: for encoded in unicode_regex.findall(tmp): tmp = tmp.replace(encoded, encoded.decode("unicode_escape")) return unicode(tmp) def encode(x): for encoded in hex_regex.findall(x): if sys.version_info >= (3, 0): x = x.replace(encoded, bytes(str(encoded).replace("\\\\x", "\\x"),"utf-8").decode("unicode_escape")) else: x = x.replace(encoded, str(encoded).replace("\\\\x", "\\x").decode("string_escape")) return x if indent: return encode_decode_all("{0}".format(json.dumps(encode_decode_all(func(self)), indent=5)), _decode=False) else: return encode_decode_all("{0}".format(json.dumps(encode_decode_all(func(self)))), _decode=False) return func_wrapper
python
{ "resource": "" }
q271013
String.build
test
def build(self, pre=None, shortest=False): """Build the String instance :param list pre: The prerequisites list (optional, default=None) :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] if self.value is not None and rand.maybe(): return utils.val(self.value, pre, shortest=shortest) length = super(String, self).build(pre, shortest=shortest) res = rand.data(length, self.charset) return res
python
{ "resource": "" }
q271014
And.build
test
def build(self, pre=None, shortest=False): """Build the ``And`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] res = deque() for x in self.values: try: res.append(utils.val(x, pre, shortest=shortest)) except errors.OptGram as e: continue except errors.FlushGrams as e: prev = "".join(res) res.clear() # this is assuming a scope was pushed! if len(self.fuzzer._scope_stack) == 1: pre.append(prev) else: stmts = self.fuzzer._curr_scope.setdefault("prev_append", deque()) stmts.extend(pre) stmts.append(prev) pre.clear() continue return self.sep.join(res)
python
{ "resource": "" }
q271015
Q.build
test
def build(self, pre=None, shortest=False): """Build the ``Quote`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ res = super(Q, self).build(pre, shortest=shortest) if self.escape: return repr(res) elif self.html_js_escape: return ("'" + res.encode("string_escape").replace("<", "\\x3c").replace(">", "\\x3e") + "'") else: return "{q}{r}{q}".format(q=self.quote, r=res)
python
{ "resource": "" }
q271016
Or.build
test
def build(self, pre=None, shortest=False): """Build the ``Or`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] # self.shortest_vals will be set by the GramFuzzer and will # contain a list of value options that have a minimal reference # chain if shortest and self.shortest_vals is not None: return utils.val(rand.choice(self.shortest_vals), pre, shortest=shortest) else: return utils.val(rand.choice(self.values), pre, shortest=shortest)
python
{ "resource": "" }
q271017
Opt.build
test
def build(self, pre=None, shortest=False): """Build the current ``Opt`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] if shortest or rand.maybe(self.prob): raise errors.OptGram return super(Opt, self).build(pre, shortest=shortest)
python
{ "resource": "" }
q271018
Ref.build
test
def build(self, pre=None, shortest=False): """Build the ``Ref`` instance by fetching the rule from the GramFuzzer instance and building it :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ global REF_LEVEL REF_LEVEL += 1 try: if pre is None: pre = [] #print("{:04d} - {} - {}:{}".format(REF_LEVEL, shortest, self.cat, self.refname)) definition = self.fuzzer.get_ref(self.cat, self.refname) res = utils.val( definition, pre, shortest=(shortest or REF_LEVEL >= self.max_recursion) ) return res # this needs to happen no matter what finally: REF_LEVEL -= 1
python
{ "resource": "" }
q271019
STAR.build
test
def build(self, pre=None, shortest=False): """Build the STAR field. :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] if shortest: raise errors.OptGram elif rand.maybe(): return super(STAR, self).build(pre, shortest=shortest) else: raise errors.OptGram
python
{ "resource": "" }
q271020
PJFProcessMonitor.shutdown
test
def shutdown(self, *args): """ Shutdown the running process and the monitor """ try: self._shutdown() if self.process: self.process.wait() self.process.stdout.close() self.process.stdin.close() self.process.stderr.close() self.finished = True self.send_testcase('', '127.0.0.1', self.config.ports["servers"]["TCASE_PORT"]) self.logger.debug("[{0}] - PJFProcessMonitor successfully completed".format(time.strftime("%H:%M:%S"))) except Exception as e: raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
python
{ "resource": "" }
q271021
PJFProcessMonitor.run_and_monitor
test
def run_and_monitor(self): """ Run command once and check exit code """ signal.signal(signal.SIGINT, self.shutdown) self.spawn(self.config.process_to_monitor, timeout=0) return self._is_sigsegv(self.return_code)
python
{ "resource": "" }
q271022
PJFProcessMonitor.start_monitor
test
def start_monitor(self, standalone=True): """ Run command in a loop and check exit status plus restart process when needed """ try: self.start() cmdline = shlex.split(self.config.process_to_monitor) if standalone: signal.signal(signal.SIGINT, self.shutdown) self.process = subprocess.Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE) while self.process and not self.finished: self.process.wait() if self._is_sigsegv(self.process.returncode): if self.config.debug: print("[\033[92mINFO\033[0m] Process crashed with \033[91mSIGSEGV\033[0m, waiting for testcase...") while not self.got_testcase(): time.sleep(1) self.save_testcase(self.testcase[-10:]) # just take last 10 testcases if self.process: self.process = subprocess.Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE) except OSError: self.shutdown() self.process = False self.got_testcase = lambda: True raise PJFProcessExecutionError("Binary <%s> does not exist" % cmdline[0]) except Exception as e: raise PJFBaseException("Unknown error please send log to author")
python
{ "resource": "" }
q271023
randfloat
test
def randfloat(a, b=None): """Return a random float :param float a: Either the minimum value (inclusive) if ``b`` is set, or the maximum value if ``b`` is not set (non-inclusive, in which case the minimum is implicitly 0.0) :param float b: The maximum value to generate (non-inclusive) :returns: float """ if b is None: max_ = a min_ = 0.0 else: min_ = a max_ = b diff = max_ - min_ res = _random() res *= diff res += min_ return res
python
{ "resource": "" }
q271024
GramFuzzer.add_definition
test
def add_definition(self, cat, def_name, def_val, no_prune=False, gram_file="default"): """Add a new rule definition named ``def_name`` having value ``def_value`` to the category ``cat``. :param str cat: The category to add the rule to :param str def_name: The name of the rule definition :param def_val: The value of the rule definition :param bool no_prune: If the rule should explicitly *NOT* be pruned even if it has been determined to be unreachable (default=``False``) :param str gram_file: The file the rule was defined in (default=``"default"``). """ self._rules_processed = False self.add_to_cat_group(cat, gram_file, def_name) if no_prune: self.no_prunes.setdefault(cat, {}).setdefault(def_name, True) if self._staged_defs is not None: # if we're tracking changes during rule generation, add any new rules # to _staged_defs so they can be reverted if something goes wrong self._staged_defs.append((cat, def_name, def_val)) else: self.defs.setdefault(cat, {}).setdefault(def_name, deque()).append(def_val)
python
{ "resource": "" }
q271025
GramFuzzer.add_to_cat_group
test
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)
python
{ "resource": "" }
q271026
GramFuzzer.gen
test
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
python
{ "resource": "" }
q271027
PJFFactory.fuzz_elements
test
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
python
{ "resource": "" }
q271028
PJFFactory.fuzzed
test
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))
python
{ "resource": "" }
q271029
PJFFactory.get_fuzzed
test
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))
python
{ "resource": "" }
q271030
PJFDecorators.mutate_object_decorate
test
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
python
{ "resource": "" }
q271031
Process.sigterm_handler
test
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()
python
{ "resource": "" }
q271032
Process.cli_command_quit
test
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)
python
{ "resource": "" }
q271033
Process.cli_command_pause
test
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
python
{ "resource": "" }
q271034
Process.cli_command_resume
test
def cli_command_resume(self, msg): """\ sets state to waiting - so we resume spawning children """ if self.state == State.PAUSED: self.state = State.WAITING
python
{ "resource": "" }
q271035
Process.cli_command_stop
test
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
python
{ "resource": "" }
q271036
Process.cli_command_restart
test
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
python
{ "resource": "" }
q271037
Skype.getEvents
test
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
python
{ "resource": "" }
q271038
Skype.setMood
test
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
python
{ "resource": "" }
q271039
Skype.setAvatar
test
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())
python
{ "resource": "" }
q271040
Skype.getUrlMeta
test
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()
python
{ "resource": "" }
q271041
SkypeContacts.contact
test
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
python
{ "resource": "" }
q271042
SkypeContacts.user
test
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
python
{ "resource": "" }
q271043
SkypeContacts.bots
test
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]
python
{ "resource": "" }
q271044
SkypeContacts.bot
test
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
python
{ "resource": "" }
q271045
SkypeContacts.search
test
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]
python
{ "resource": "" }
q271046
SkypeContacts.requests
test
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
python
{ "resource": "" }
q271047
SkypeObj.fromRaw
test
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))
python
{ "resource": "" }
q271048
SkypeObj.merge
test
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)
python
{ "resource": "" }
q271049
SkypeObjs.merge
test
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]
python
{ "resource": "" }
q271050
SkypeConnection.syncStateCall
test
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
python
{ "resource": "" }
q271051
SkypeConnection.readToken
test
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()
python
{ "resource": "" }
q271052
SkypeConnection.writeToken
test
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")
python
{ "resource": "" }
q271053
SkypeConnection.verifyToken
test
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()
python
{ "resource": "" }
q271054
SkypeConnection.refreshSkypeToken
test
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()
python
{ "resource": "" }
q271055
SkypeConnection.getUserId
test
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")
python
{ "resource": "" }
q271056
SkypeConnection.getRegToken
test
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()
python
{ "resource": "" }
q271057
SkypeConnection.syncEndpoints
test
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))
python
{ "resource": "" }
q271058
SkypeLiveAuthProvider.checkUser
test
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")
python
{ "resource": "" }
q271059
SkypeRefreshAuthProvider.auth
test
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)
python
{ "resource": "" }
q271060
SkypeRegistrationTokenProvider.auth
test
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
python
{ "resource": "" }
q271061
SkypeEndpoint.config
test
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"}})
python
{ "resource": "" }
q271062
SkypeEndpoint.ping
test
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})
python
{ "resource": "" }
q271063
SkypeChats.recent
test
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
python
{ "resource": "" }
q271064
SkypeChats.chat
test
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))
python
{ "resource": "" }
q271065
SkypeChats.create
test
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])
python
{ "resource": "" }
q271066
SkypeUtils.userToId
test
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
python
{ "resource": "" }
q271067
SkypeUtils.chatToId
test
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
python
{ "resource": "" }
q271068
SkypeUtils.exhaust
test
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
python
{ "resource": "" }
q271069
u
test
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
python
{ "resource": "" }
q271070
detect_format
test
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
python
{ "resource": "" }
q271071
parse
test
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()
python
{ "resource": "" }
q271072
Post.to_dict
test
def to_dict(self): "Post as a dict, for serializing" d = self.metadata.copy() d['content'] = self.content return d
python
{ "resource": "" }
q271073
YAMLHandler.load
test
def load(self, fm, **kwargs): """ Parse YAML front matter. This uses yaml.SafeLoader by default. """ kwargs.setdefault('Loader', SafeLoader) return yaml.load(fm, **kwargs)
python
{ "resource": "" }
q271074
YAMLHandler.export
test
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)
python
{ "resource": "" }
q271075
JSONHandler.export
test
def export(self, metadata, **kwargs): "Turn metadata into JSON" kwargs.setdefault('indent', 4) metadata = json.dumps(metadata, **kwargs) return u(metadata)
python
{ "resource": "" }
q271076
WikiList._match
test
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
python
{ "resource": "" }
q271077
WikiList.items
test
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
python
{ "resource": "" }
q271078
WikiList.sublists
test
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
python
{ "resource": "" }
q271079
WikiList.convert
test
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)
python
{ "resource": "" }
q271080
SubWikiTextWithArgs.arguments
test
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
python
{ "resource": "" }
q271081
SubWikiTextWithArgs.lists
test
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]
python
{ "resource": "" }
q271082
_plant_trie
test
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
python
{ "resource": "" }
q271083
_pattern
test
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
python
{ "resource": "" }
q271084
WikiText._check_index
test
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
python
{ "resource": "" }
q271085
WikiText.insert
test
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])
python
{ "resource": "" }
q271086
WikiText._atomic_partition
test
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]
python
{ "resource": "" }
q271087
WikiText._subspans
test
def _subspans(self, type_: str) -> List[List[int]]: """Return all the sub-span including self._span.""" return self._type_to_spans[type_]
python
{ "resource": "" }
q271088
WikiText._shrink_update
test
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
python
{ "resource": "" }
q271089
WikiText._insert_update
test
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
python
{ "resource": "" }
q271090
WikiText.nesting_level
test
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
python
{ "resource": "" }
q271091
WikiText._shadow
test
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
python
{ "resource": "" }
q271092
WikiText._ext_link_shadow
test
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
python
{ "resource": "" }
q271093
WikiText._pp_type_to_spans
test
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()}
python
{ "resource": "" }
q271094
WikiText.pprint
test
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)
python
{ "resource": "" }
q271095
WikiText.parameters
test
def parameters(self) -> List['Parameter']: """Return a list of parameter objects.""" _lststr = self._lststr _type_to_spans = self._type_to_spans return [ Parameter(_lststr, _type_to_spans, span, 'Parameter') for span in self._subspans('Parameter')]
python
{ "resource": "" }
q271096
WikiText.parser_functions
test
def parser_functions(self) -> List['ParserFunction']: """Return a list of parser function objects.""" _lststr = self._lststr _type_to_spans = self._type_to_spans return [ ParserFunction(_lststr, _type_to_spans, span, 'ParserFunction') for span in self._subspans('ParserFunction')]
python
{ "resource": "" }
q271097
WikiText.templates
test
def templates(self) -> List['Template']: """Return a list of templates as template objects.""" _lststr = self._lststr _type_to_spans = self._type_to_spans return [ Template(_lststr, _type_to_spans, span, 'Template') for span in self._subspans('Template')]
python
{ "resource": "" }
q271098
WikiText.wikilinks
test
def wikilinks(self) -> List['WikiLink']: """Return a list of wikilink objects.""" _lststr = self._lststr _type_to_spans = self._type_to_spans return [ WikiLink(_lststr, _type_to_spans, span, 'WikiLink') for span in self._subspans('WikiLink')]
python
{ "resource": "" }
q271099
WikiText.comments
test
def comments(self) -> List['Comment']: """Return a list of comment objects.""" _lststr = self._lststr _type_to_spans = self._type_to_spans return [ Comment(_lststr, _type_to_spans, span, 'Comment') for span in self._subspans('Comment')]
python
{ "resource": "" }