text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_jobs_to_dequeue(self): """ Returns the number of jobs that can be dequeued right now from the queue. """
# timed ZSET if self.is_timed: return context.connections.redis.zcount( self.redis_key, "-inf", time.time()) # In all other cases, it's the same as .size() else: return self.size()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sorted_graph( self, start=0, stop=100, slices=100, include_inf=False, exact=False): """ Returns a graph of the distribution of jobs in a sorted set """
if not self.is_sorted: raise Exception("Not a sorted queue") with context.connections.redis.pipeline(transaction=exact) as pipe: interval = old_div(float(stop - start), slices) for i in range(0, slices): pipe.zcount(self.redis_key, (start + i * interval), "(%s" % (start + (i + 1) * interval)) if include_inf: pipe.zcount(self.redis_key, stop, "+inf") pipe.zcount(self.redis_key, "-inf", "(%s" % start) data = pipe.execute() if include_inf: return data[-1:] + data[:-1] return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_signal_handlers(self): """ Handle events like Ctrl-C from the command line. """
self.graceful_stop = False def request_shutdown_now(): self.shutdown_now() def request_shutdown_graceful(): # Second time CTRL-C, shutdown now if self.graceful_stop: self.shutdown_now() else: self.graceful_stop = True self.shutdown_graceful() # First time CTRL-C, try to shutdown gracefully gevent.signal(signal.SIGINT, request_shutdown_graceful) # User (or Heroku) requests a stop now, just mark tasks as interrupted. gevent.signal(signal.SIGTERM, request_shutdown_now)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_commands(self, commands, timeout=None): """ Sets the processes' desired commands for this pool and manages diff to reach that state """
self.desired_commands = commands target_commands = list(self.desired_commands) for process in list(self.processes): found = False for i in range(len(target_commands)): if process["command"] == target_commands[i]: target_commands.pop(i) found = True break if not found: self.stop_process(process, timeout) # What is left are the commands to add # TODO: we should only do this once memory conditions allow for command in target_commands: self.spawn(command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn(self, command): """ Spawns a new process and adds it to the pool """
# process_name # output # time before starting (wait for port?) # start_new_session=True : avoid sending parent signals to child env = dict(os.environ) env["MRQ_IS_SUBPROCESS"] = "1" env.update(self.extra_env or {}) # Extract env variables from shell commands. parts = shlex.split(command) for p in list(parts): if "=" in p: env[p.split("=")[0]] = p[len(p.split("=")[0]) + 1:] parts.pop(0) else: break p = subprocess.Popen(parts, shell=False, close_fds=True, env=env, cwd=os.getcwd()) self.processes.append({ "subprocess": p, "pid": p.pid, "command": command, "psutil": psutil.Process(pid=p.pid) })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self): """ Waits for the pool to be fully stopped """
while True: if not self.greenlet_watch: break if self.stopping: gevent.sleep(0.1) else: gevent.sleep(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch_processes(self): """ Manages the status of all the known processes """
for process in list(self.processes): self.watch_process(process) # Cleanup processes self.processes = [p for p in self.processes if not p.get("dead")] if self.stopping and len(self.processes) == 0: self.stop_watch()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch_process(self, process): """ Manages the status of a single process """
status = process["psutil"].status() # TODO: how to avoid zombies? # print process["pid"], status if process.get("terminate"): if status in ("zombie", "dead"): process["dead"] = True elif process.get("terminate_at"): if time.time() > (process["terminate_at"] + 5): log.warning("Process %s had to be sent SIGKILL" % (process["pid"], )) process["subprocess"].send_signal(signal.SIGKILL) elif time.time() > process["terminate_at"]: log.warning("Process %s had to be sent SIGTERM" % (process["pid"], )) process["subprocess"].send_signal(signal.SIGTERM) else: if status in ("zombie", "dead"): # Restart a new process right away (TODO: sleep a bit? max retries?) process["dead"] = True self.spawn(process["command"]) elif status not in ("running", "sleeping"): log.warning("Process %s was in status %s" % (process["pid"], status))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self, timeout=None): """ Initiates a graceful stop of the processes """
self.stopping = True for process in list(self.processes): self.stop_process(process, timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_process(self, process, timeout=None): """ Initiates a graceful stop of one process """
process["terminate"] = True if timeout is not None: process["terminate_at"] = time.time() + timeout process["subprocess"].send_signal(signal.SIGINT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terminate(self): """ Terminates the processes right now with a SIGTERM """
for process in list(self.processes): process["subprocess"].send_signal(signal.SIGTERM) self.stop_watch()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self): """ Kills the processes right now with a SIGKILL """
for process in list(self.processes): process["subprocess"].send_signal(signal.SIGKILL) self.stop_watch()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_watch(self): """ Stops the periodic watch greenlet, thus the pool itself """
if self.greenlet_watch: self.greenlet_watch.kill(block=False) self.greenlet_watch = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(messages=None, conf=None, parse_mode=None, disable_web_page_preview=False, files=None, images=None, captions=None, locations=None, timeout=30): """Send data over Telegram. All arguments are optional. Always use this function with explicit keyword arguments. So `send(messages=["Hello!"])` instead of `send(["Hello!"])` as the latter will *break* when I change the order of the arguments. The `file` type is the [file object][] returned by the `open()` function. To send an image/file you open it in binary mode: ``` python import telegram_send with open("image.jpg", "rb") as f: telegram_send.send(images=[f]) ``` [file object]: https://docs.python.org/3/glossary.html#term-file-object # Arguments conf (str): Path of configuration file to use. Will use the default config if not specified. `~` expands to user's home directory. messages (List[str]): The messages to send. parse_mode (str): Specifies formatting of messages, one of `["text", "markdown", "html"]`. disable_web_page_preview (bool): Disables web page previews for all links in the messages. files (List[file]): The files to send. images (List[file]): The images to send. captions (List[str]): The captions to send with the images. locations (List[str]): The locations to send. Locations are strings containing the latitude and longitude separated by whitespace or a comma. timeout (int|float): The read timeout for network connections in seconds. """
conf = expanduser(conf) if conf else get_config_path() config = configparser.ConfigParser() if not config.read(conf) or not config.has_section("telegram"): raise ConfigError("Config not found") missing_options = set(["token", "chat_id"]) - set(config.options("telegram")) if len(missing_options) > 0: raise ConfigError("Missing options in config: {}".format(", ".join(missing_options))) token = config.get("telegram", "token") chat_id = int(config.get("telegram", "chat_id")) if config.get("telegram", "chat_id").isdigit() else config.get("telegram", "chat_id") request = telegram.utils.request.Request(read_timeout=timeout) bot = telegram.Bot(token, request=request) # We let the user specify "text" as a parse mode to be more explicit about # the lack of formatting applied to the message, but "text" isn't a supported # parse_mode in python-telegram-bot. Instead, set the parse_mode to None # in this case. if parse_mode == "text": parse_mode = None if messages: def send_message(message): return bot.send_message(chat_id=chat_id, text=message, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview) for m in messages: if len(m) > MAX_MESSAGE_LENGTH: warn(markup("Message longer than MAX_MESSAGE_LENGTH=%d, splitting into smaller messages." % MAX_MESSAGE_LENGTH, "red")) ms = split_message(m, MAX_MESSAGE_LENGTH) for m in ms: send_message(m) elif len(m) == 0: continue else: send_message(m) if files: for f in files: bot.send_document(chat_id=chat_id, document=f) if images: if captions: # make captions equal length when not all images have captions captions += [None] * (len(images) - len(captions)) for (i, c) in zip(images, captions): bot.send_photo(chat_id=chat_id, photo=i, caption=c) else: for i in images: bot.send_photo(chat_id=chat_id, photo=i) if locations: it = iter(locations) for loc in it: if "," in loc: lat, lon = loc.split(",") else: lat = loc lon = next(it) bot.send_location(chat_id=chat_id, latitude=float(lat), longitude=float(lon))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_message(message, max_length): """Split large message into smaller messages each smaller than the max_length."""
ms = [] while len(message) > max_length: ms.append(message[:max_length]) message = message[max_length:] ms.append(message) return ms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_message(self, msg): """Issues an `inspection` service message based on a PyLint message. Registers each message type upon first encounter. :param utils.Message msg: a PyLint message """
if msg.msg_id not in self.msg_types: self.report_message_type(msg) self.msg_types.add(msg.msg_id) self.tc.message('inspection', typeId=msg.msg_id, message=msg.msg, file=os.path.relpath(msg.abspath).replace('\\', '/'), line=str(msg.line), SEVERITY=TC_SEVERITY.get(msg.category))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_reports(self, layout): """Issues the final PyLint score as a TeamCity build statistic value"""
try: score = self.linter.stats['global_note'] except (AttributeError, KeyError): pass else: self.tc.message('buildStatisticValue', key='PyLintScore', value=str(score))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_webhook_handler(self, scope, callback): """ Allows adding a webhook_handler as an alternative to the decorators """
scope = scope.lower() if scope == 'after_send': self._after_send = callback return if scope not in Page.WEBHOOK_ENDPOINTS: raise ValueError("The 'scope' argument must be one of {}.".format(Page.WEBHOOK_ENDPOINTS)) self._webhook_handlers[scope] = callback
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getWindows(input): """Get a source's windows"""
with rasterio.open(input) as src: return [[window, ij] for ij, window in src.block_windows()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_function(data, window, ij, g_args): """Takes an array, and sets any value above the mean to the max, the rest to 0"""
output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max() return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tb_capture(func): """A decorator which captures worker tracebacks. Tracebacks in particular, are captured. Inspired by an example in https://bugs.python.org/issue13831. This decorator wraps rio-mucho worker tasks. Parameters func : function A function to be decorated. Returns ------- func """
@wraps(func) def wrapper(*args, **kwds): try: return func(*args, **kwds) except Exception: raise MuchoChildError() return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_worker(inpaths, g_args): """The multiprocessing worker initializer Parameters inpaths : list of str A list of dataset paths. g_args : dict Global arguments. Returns ------- None """
global global_args global srcs global_args = g_args srcs = [rasterio.open(i) for i in inpaths]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def safe_serialize_type(l): '''serialize only with letters, numbers and _''' if isinstance(l, str): return l elif isinstance(l, list): return '%s_%s_' % (l[0], ''.join(map(safe_serialize_type, l[1:]))) else: return str(l)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def method_call(receiver, message, args, pseudo_type=None): '''A shortcut for a method call, expands a str receiver to a identifier''' if not isinstance(receiver, Node): receiver = local(receiver) return Node('method_call', receiver=receiver, message=message, args=args, pseudo_type=pseudo_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def call(function, args, pseudo_type=None): '''A shortcut for a call with an identifier callee''' if not isinstance(function, Node): function = local(function) return Node('call', function=function, args=args, pseudo_type=pseudo_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_node(value): '''Expand to a literal node if a basic type otherwise just returns the node''' if isinstance(value, Node): return value elif isinstance(value, str): return Node('string', value=value, pseudo_type='String') elif isinstance(value, int): return Node('int', value=value, pseudo_type='Int') elif isinstance(value, bool): return Node('boolean', value=str(value).lower(), pseudo_type='Boolean') elif isinstance(value, float): return Node('float', value=value, pseudo_type='Float') elif value is None: return Node('null', pseudo_type='Void') else: 1/0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_op(op, reversed=False): ''' create a function that transforms a method to a binary op often we need to convert a pseudo method <receiver>.<message>(<z>) to a binary op <receiver> <op> <message> that's a decorator that helps for that ''' def transformer(receiver, param, pseudo_type): if not reversed: return Node('binary_op', op=op, left=receiver, right=param, pseudo_type=pseudo_type) return Node('binary_op', op=op, left=param, right=receiver, pseudo_type=pseudo_type) return transformer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def leaking(self, z, module, name, node, context, *data): ''' an expression leaking ... assignment nodes into the nearest block list of nodes c++ guys, stay calm ''' # input(node.y) args = [node.receiver] + node.args if node.type == 'standard_method_call' else node.args z = z(module, name, args) if context == 'expression': if isinstance(z, NormalLeakingNode): leaked_nodes, exp = z.as_expression() else: leaked_nodes, exp = z.as_expression() zz = local(z.temp_name(getattr(z, 'default', '')), node.pseudo_type) leaked_nodes = z.as_assignment(zz) exp = local(zz, node.pseudo_type) if exp is None or exp.pseudo_type == 'Void': raise PseudoTypeError("pseudo can't handle values with void type in expression: %s?%s" % (module, name)) self.leaked_nodes += leaked_nodes return exp elif context == 'assignment': if isinstance(z, NormalLeakingNode): leaked_nodes, exp = z.as_expression() if exp is None or exp.pseudo_type == 'Void': raise PseudoTypeError("pseudo can't handle values with void type in expression: %s?%s" % (module, name)) self.leaked_nodes += leaked_nodes return assignment(data[0], exp) else: self.leaked_nodes += z.as_assignment(data[0]) return None elif context == 'block': leaked_nodes, exp = z.as_expression() self.leaked_nodes += leaked_nodes return exp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _expand_api(self, api, receiver, args, pseudo_type, equivalent): ''' the heart of api translation dsl function or <z>(<arg>, ..) can be expanded, <z> can be just a name for a global function, or #name for method, <arg> can be %{self} for self or %{n} for nth arg ''' if callable(api): if receiver: return api(receiver, *(args + [pseudo_type])) else: return api(*(args + [pseudo_type])) elif isinstance(api, str): if '(' in api: call_api, arg_code = api[:-1].split('(') new_args = [self._parse_part( a.strip(), receiver, args, equivalent) for a in arg_code.split(',')] else: call_api, arg_code = api, '' new_args = args if '#' in call_api: a, b = call_api.split('#') method_receiver = self._parse_part( a, receiver, args, equivalent) if a else receiver return method_call(method_receiver, b, new_args, pseudo_type=pseudo_type) elif '.' in call_api: a, b = call_api.split('.') static_receiver = self._parse_part( a, receiver, args, equivalent) if a else receiver if b[-1] != '!': return Node('static_call', receiver=static_receiver, message=b, args=new_args, pseudo_type=pseudo_type) else: return Node('attr', object=static_receiver, attr=b[:-1], pseudo_type=pseudo_type) else: if receiver: return call(call_api, [receiver] + new_args, pseudo_type=pseudo_type) else: return call(call_api, new_args, pseudo_type=pseudo_type) else: raise PseudoDSLError('%s not supported by api dsl' % str(api))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_main(main, language): ''' generate output code for main in `language` `main` is a dict/Node or a list of dicts/Nodes with pseudo ast e.g. > print(generate_main({'type': 'int', 'value': 0, 'pseudo_type': 'Int'}, 'rb')) 2 > print(generate_main([pseudo.pseudo_tree.to_node('a'), pseudo.pseudo_tree.to_node(0)], 'js')) 'a'; 0; ''' base = {'type': 'module', 'custom_exceptions': [], 'definitions': [], 'constants': [], 'main': [], 'pseudo_type': 'Void'} base_node = pseudo.loader.convert_to_syntax_tree(base) if isinstance(main, dict): base['main'] = [main] elif isinstance(main, list): if main and isinstance(main[0], dict): base['main'] = main else: base_node.main = main elif isinstance(main, pseudo.pseudo_tree.Node): base_node.main = [main] if base['main']: q = pseudo.loader.convert_to_syntax_tree(base) else: q = base_node return generate(q, language)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ported_string(raw_data, encoding='utf-8', errors='ignore'): """ Give as input raw data and output a str in Python 3 and unicode in Python 2. Args: raw_data: Python 2 str, Python 3 bytes or str to porting encoding: string giving the name of an encoding errors: his specifies the treatment of characters which are invalid in the input encoding Returns: str (Python 3) or unicode (Python 2) """
if not raw_data: return six.text_type() if isinstance(raw_data, six.text_type): return raw_data.strip() if six.PY2: try: return six.text_type(raw_data, encoding, errors).strip() except LookupError: return six.text_type(raw_data, "utf-8", errors).strip() if six.PY3: try: return six.text_type(raw_data, encoding).strip() except (LookupError, UnicodeDecodeError): return six.text_type(raw_data, "utf-8", errors).strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_header_part(header): """ Given an raw header returns an decoded header Args: header (string): header to decode Returns: str (Python 3) or unicode (Python 2) """
if not header: return six.text_type() output = six.text_type() try: for d, c in decode_header(header): c = c if c else 'utf-8' output += ported_string(d, c, 'ignore') # Header parsing failed, when header has charset Shift_JIS except (HeaderParseError, UnicodeError): log.error("Failed decoding header part: {}".format(header)) output += header return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fingerprints(data): """ This function return the fingerprints of data. Args: data (string): raw data Returns: namedtuple: fingerprints md5, sha1, sha256, sha512 """
Hashes = namedtuple('Hashes', "md5 sha1 sha256 sha512") if six.PY2: if not isinstance(data, str): data = data.encode("utf-8") elif six.PY3: if not isinstance(data, bytes): data = data.encode("utf-8") # md5 md5 = hashlib.md5() md5.update(data) md5 = md5.hexdigest() # sha1 sha1 = hashlib.sha1() sha1.update(data) sha1 = sha1.hexdigest() # sha256 sha256 = hashlib.sha256() sha256.update(data) sha256 = sha256.hexdigest() # sha512 sha512 = hashlib.sha512() sha512.update(data) sha512 = sha512.hexdigest() return Hashes(md5, sha1, sha256, sha512)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msgconvert(email): """ Exec msgconvert tool, to convert msg Outlook mail in eml mail format Args: email (string): file path of Outlook msg mail Returns: tuple with file path of mail converted and standard output data (unicode Python 2, str Python 3) """
log.debug("Started converting Outlook email") temph, temp = tempfile.mkstemp(prefix="outlook_") command = ["msgconvert", "--outfile", temp, email] try: if six.PY2: with open(os.devnull, "w") as devnull: out = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=devnull) elif six.PY3: out = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) except OSError: message = "To use this function you must install 'msgconvert' tool" log.exception(message) raise MailParserOSError(message) else: stdoutdata, _ = out.communicate() return temp, stdoutdata.decode("utf-8").strip() finally: os.close(temph)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_received(received): """ Parse a single received header. Return a dictionary of values by clause. Arguments: received {str} -- single received header Raises: MailParserReceivedParsingError -- Raised when a received header cannot be parsed Returns: dict -- values by clause """
values_by_clause = {} for pattern in RECEIVED_COMPILED_LIST: matches = [match for match in pattern.finditer(received)] if len(matches) == 0: # no matches for this clause, but it's ok! keep going! log.debug("No matches found for %s in %s" % ( pattern.pattern, received)) continue elif len(matches) > 1: # uh, can't have more than one of each clause in a received. # so either there's more than one or the current regex is wrong msg = "More than one match found for %s in %s" % ( pattern.pattern, received) log.error(msg) raise MailParserReceivedParsingError(msg) else: # otherwise we have one matching clause! log.debug("Found one match for %s in %s" % ( pattern.pattern, received)) match = matches[0].groupdict() if six.PY2: values_by_clause[match.keys()[0]] = match.values()[0] elif six.PY3: key = list(match.keys())[0] value = list(match.values())[0] values_by_clause[key] = value if len(values_by_clause) == 0: # we weren't able to match anything... msg = "Unable to match any clauses in %s" % (received) log.error(msg) raise MailParserReceivedParsingError(msg) return values_by_clause
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receiveds_parsing(receiveds): """ This function parses the receiveds headers. Args: receiveds (list): list of raw receiveds headers Returns: a list of parsed receiveds headers with first hop in first position """
parsed = [] receiveds = [re.sub(JUNK_PATTERN, " ", i).strip() for i in receiveds] n = len(receiveds) log.debug("Nr. of receiveds. {}".format(n)) for idx, received in enumerate(receiveds): log.debug("Parsing received {}/{}".format(idx + 1, n)) log.debug("Try to parse {!r}".format(received)) try: # try to parse the current received header... values_by_clause = parse_received(received) except MailParserReceivedParsingError: # if we can't, let's append the raw parsed.append({'raw': received}) else: # otherwise append the full values_by_clause dict parsed.append(values_by_clause) log.debug("len(receiveds) %s, len(parsed) %s" % ( len(receiveds), len(parsed))) if len(receiveds) != len(parsed): # something really bad happened, # so just return raw receiveds with hop indices log.error("len(receiveds): %s, len(parsed): %s, receiveds: %s, \ parsed: %s" % (len(receiveds), len(parsed), receiveds, parsed)) return receiveds_not_parsed(receiveds) else: # all's good! we have parsed or raw receiveds for each received header return receiveds_format(parsed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receiveds_not_parsed(receiveds): """ If receiveds are not parsed, makes a new structure with raw field. It's useful to have the same structure of receiveds parsed. Args: receiveds (list): list of raw receiveds headers Returns: a list of not parsed receiveds headers with first hop in first position """
log.debug("Receiveds for this email are not parsed") output = [] counter = Counter() for i in receiveds[::-1]: j = {"raw": i.strip()} j["hop"] = counter["hop"] + 1 counter["hop"] += 1 output.append(j) else: return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receiveds_format(receiveds): """ Given a list of receiveds hop, adds metadata and reformat field values Args: receiveds (list): list of receiveds hops already formatted Returns: list of receiveds reformated and with new fields """
log.debug("Receiveds for this email are parsed") output = [] counter = Counter() for i in receiveds[::-1]: # Clean strings j = {k: v.strip() for k, v in i.items() if v} # Add hop j["hop"] = counter["hop"] + 1 # Add UTC date if i.get("date"): # Modify date to manage strange header like: # "for <eboktor@romolo.com>; Tue, 7 Mar 2017 14:29:24 -0800", i["date"] = i["date"].split(";")[-1] try: j["date_utc"], _ = convert_mail_date(i["date"]) except TypeError: j["date_utc"] = None # Add delay size = len(output) now = j.get("date_utc") if size and now: before = output[counter["hop"] - 1].get("date_utc") if before: j["delay"] = (now - before).total_seconds() else: j["delay"] = 0 else: j["delay"] = 0 # append result output.append(j) # new hop counter["hop"] += 1 else: for i in output: if i.get("date_utc"): i["date_utc"] = i["date_utc"].isoformat() else: return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_header(message, name): """ Gets an email.message.Message and a header name and returns the mail header decoded with the correct charset. Args: message (email.message.Message): email message object name (string): header to get Returns: decoded header """
header = message.get(name) log.debug("Getting header {!r}: {!r}".format(name, header)) if header: return decode_header_part(header) return six.text_type()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mail_keys(message, complete=True): """ Given an email.message.Message, return a set with all email parts to get Args: message (email.message.Message): email message object complete (bool): if True returns all email headers Returns: set with all email parts """
if complete: log.debug("Get all headers") all_headers_keys = {i.lower() for i in message.keys()} all_parts = ADDRESSES_HEADERS | OTHERS_PARTS | all_headers_keys else: log.debug("Get only mains headers") all_parts = ADDRESSES_HEADERS | OTHERS_PARTS log.debug("All parts to get: {}".format(", ".join(all_parts))) return all_parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_sample(binary, payload, path, filename): # pragma: no cover """ This function writes a sample on file system. Args: binary (bool): True if it's a binary file payload: payload of sample, in base64 if it's a binary path (string): path of file filename (string): name of file hash_ (string): file hash """
if not os.path.exists(path): os.makedirs(path) sample = os.path.join(path, filename) if binary: with open(sample, "wb") as f: f.write(base64.b64decode(payload)) else: with open(sample, "w") as f: f.write(payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_file_obj(cls, fp): """ Init a new object from a file-like object. Not for Outlook msg. Args: fp (file-like object): file-like object of raw email Returns: Instance of MailParser """
log.debug("Parsing email from file object") try: fp.seek(0) except IOError: # When stdout is a TTY it's a character device # and it's not seekable, you cannot seek in a TTY. pass finally: s = fp.read() return cls.from_string(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_file(cls, fp, is_outlook=False): """ Init a new object from a file path. Args: fp (string): file path of raw email is_outlook (boolean): if True is an Outlook email Returns: Instance of MailParser """
log.debug("Parsing email from file {!r}".format(fp)) with ported_open(fp) as f: message = email.message_from_file(f) if is_outlook: log.debug("Removing temp converted Outlook email {!r}".format(fp)) os.remove(fp) return cls(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_string(cls, s): """ Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser """
log.debug("Parsing email from string") message = email.message_from_string(s) return cls(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_bytes(cls, bt): """ Init a new object from bytes. Args: bt (bytes-like object): raw email as bytes-like object Returns: Instance of MailParser """
log.debug("Parsing email from bytes") if six.PY2: raise MailParserEnvironmentError( "Parsing from bytes is valid only for Python 3.x version") message = email.message_from_bytes(bt) return cls(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset(self): """ Reset the state of mail object. """
log.debug("Reset all variables") self._attachments = [] self._text_plain = [] self._text_html = [] self._defects = [] self._defects_categories = set() self._has_defects = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _append_defects(self, part, part_content_type): """ Add new defects and defects categories to object attributes. The defects are a list of all the problems found when parsing this message. Args: part (string): mail part part_content_type (string): content type of part """
part_defects = {} for e in part.defects: defects = "{}: {}".format(e.__class__.__name__, e.__doc__) self._defects_categories.add(e.__class__.__name__) part_defects.setdefault(part_content_type, []).append(defects) log.debug("Added defect {!r}".format(defects)) # Tag mail with defect if part_defects: self._has_defects = True # Save all defects self._defects.append(part_defects)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_mail(self, complete=True): """ This method assigns the right values to all tokens of email. Returns a parsed object Keyword Arguments: complete {bool} -- If True returns all mails parts (default: {True}) Returns: dict -- Parsed email object """
mail = {} keys = get_mail_keys(self.message, complete) for i in keys: log.debug("Getting header or part {!r}".format(i)) value = getattr(self, i) if value: mail[i] = value # add defects mail["has_defects"] = self.has_defects if self.has_defects: mail["defects"] = self.defects mail["defects_categories"] = list(self.defects_categories) return mail
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_server_ipaddress(self, trust): """ Return the ip address of sender Overview: Extract a reliable sender IP address heuristically for each message. Although the message format dictates a chain of relaying IP addresses in each message, a malicious relay can easily alter that. Therefore we cannot simply take the first IP in the chain. Instead, our method is as follows. First we trust the sender IP reported by our mail server in the Received headers, and if the previous relay IP address is on our trust list (e.g. other well-known mail services), we continue to follow the previous Received line, till we reach the first unrecognized IP address in the email header. From article Characterizing Botnets from Email Spam Records: Li Zhuang, J. D. Tygar In our case we trust only our mail server with the trust string. Args: trust (string): String that identify our mail server Returns: string with the ip address """
log.debug("Trust string is {!r}".format(trust)) if not trust.strip(): return received = self.message.get_all("received", []) for i in received: i = ported_string(i) if trust in i: log.debug("Trust string {!r} is in {!r}".format(trust, i)) check = REGXIP.findall(i[0:i.find("by")]) if check: try: ip_str = six.text_type(check[-1]) log.debug("Found sender IP {!r} in {!r}".format( ip_str, i)) ip = ipaddress.ip_address(ip_str) except ValueError: return else: if not ip.is_private: log.debug("IP {!r} not private".format(ip_str)) return ip_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def received_raw(self): """ Return a list of all received headers in raw format """
output = [] for i in self.message.get_all("received", []): output.append(decode_header_part(i)) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def headers(self): """ Return only the headers as Python object """
d = {} for k, v in self.message.items(): d[k] = decode_header_part(v) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date(self): """ Return the mail date in datetime.datetime format and UTC. """
date = self.message.get('date') conv = None try: conv, _ = convert_mail_date(date) finally: return conv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timezone(self): """ Return timezone. Offset from UTC. """
date = self.message.get('date') timezone = 0 try: _, timezone = convert_mail_date(date) finally: return timezone
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date_json(self): """ Return the JSON of date """
if self.date: return json.dumps(self.date.isoformat(), ensure_ascii=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mail_json(self): """ Return the JSON of mail parsed """
if self.mail.get("date"): self._mail["date"] = self.date.isoformat() return json.dumps(self.mail, ensure_ascii=False, indent=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mail_partial_json(self): """ Return the JSON of mail parsed partial """
if self.mail_partial.get("date"): self._mail_partial["date"] = self.date.isoformat() return json.dumps(self.mail_partial, ensure_ascii=False, indent=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_worker_fn(scraper, img_url, pbar, status_flags, status_lock): """ Stnadalone function that downloads images. """
failed = False size_failed = False try: scraper.download_image(img_url) except ImageDownloadError: failed = True except ImageSizeError: size_failed = True status_lock.acquire(True) if failed: status_flags['failed'] += 1 elif size_failed: status_flags['under_min_or_over_max_filesize'] += 1 status_flags['percent'] = status_flags[ 'percent'] + old_div(100.0, scraper.no_to_download) pbar.update(status_flags['percent'] % 100) status_lock.release() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_html(self): """ Downloads HTML content of page given the page_url"""
if self.use_ghost: self.url = urljoin("http://", self.url) import selenium import selenium.webdriver driver = selenium.webdriver.PhantomJS( service_log_path=os.path.devnull) driver.get(self.url) page_html = driver.page_source page_url = driver.current_url driver.quit() else: if self.proxy_url: print("Using proxy: " + self.proxy_url + "\n") try: page = requests.get(self.url, proxies=self.proxies) if page.status_code != 200: raise PageLoadError(page.status_code) except requests.exceptions.MissingSchema: self.url = "http://" + self.url page = requests.get(self.url, proxies=self.proxies) if page.status_code != 200: raise PageLoadError(page.status_code) except requests.exceptions.ConnectionError: raise PageLoadError(None) try: page_html = page.text page_url = page.url except UnboundLocalError: raise PageLoadError(None) self.page_html = page_html self.page_url = page_url return (self.page_html, self.page_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_img_list(self): """ Gets list of images from the page_html. """
tree = html.fromstring(self.page_html) img = tree.xpath('//img/@src') links = tree.xpath('//a/@href') img_list = self.process_links(img) img_links = self.process_links(links) img_list.extend(img_links) if self.filename_pattern: # Compile pattern for efficiency pattern = re.compile(self.filename_pattern) # Verifies filename in the image URL matches pattern def matches_pattern(img_url): """ Function to check if pattern is matched. """ img_filename = urlparse(img_url).path.split('/')[-1] return pattern.search(img_filename) images = [urljoin(self.url, img_url) for img_url in img_list if matches_pattern(img_url)] else: images = [urljoin(self.url, img_url) for img_url in img_list] images = list(set(images)) self.images = images if self.scrape_reverse: self.images.reverse() return self.images
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_download_path(self): """ Processes the download path. It checks if the path exists and the scraper has write permissions. """
if os.path.exists(self.download_path): if not os.access(self.download_path, os.W_OK): raise DirectoryAccessError elif os.access(os.path.dirname(self.download_path), os.W_OK): os.makedirs(self.download_path) else: raise DirectoryCreateError return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_image(self, img_url): """ Downloads a single image. Downloads img_url using self.page_url as base. Also, raises the appropriate exception if required. """
img_request = None try: img_request = requests.request( 'get', img_url, stream=True, proxies=self.proxies) if img_request.status_code != 200: raise ImageDownloadError(img_request.status_code) except: raise ImageDownloadError() if img_url[-3:] == "svg" or (int(img_request.headers['content-length']) > self.min_filesize and\ int(img_request.headers['content-length']) < self.max_filesize): img_content = img_request.content with open(os.path.join(self.download_path, img_url.split('/')[-1]), 'wb') as f: byte_image = bytes(img_content) f.write(byte_image) else: raise ImageSizeError(img_request.headers['content-length']) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_links(self, links): """ Function to process the list of links and filter required links."""
links_list = [] for link in links: if os.path.splitext(link)[1][1:].strip().lower() in self.format_list: links_list.append(link) return links_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, value): "Updates the progress bar to a new value." if value <= 0.1: value = 0 assert 0 <= value <= self.maxval self.currval = value if not self._need_update() or self.finished: return if not self.start_time: self.start_time = time.time() self.seconds_elapsed = time.time() - self.start_time self.prev_percentage = self.percentage() if value != self.maxval: self.fd.write(self._format_line() + '\r') else: self.finished = True self.fd.write(self._format_line() + '\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(self): """Used to tell the progress is finished."""
self.update(self.maxval) if self.signal_set: signal.signal(signal.SIGWINCH, signal.SIG_DFL)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def console_main(): """ This function handles all the console action. """
setproctitle('image-scraper') scraper = ImageScraper() scraper.get_arguments() print("\nImageScraper\n============\nRequesting page....\n") try: scraper.get_html() except PageLoadError as err: if err.status_code is None: print("ImageScraper is unable to acces the internet.") else: print("Page failed to load. Status code: {0}".format(err.status_code)) sys.exit() scraper.get_img_list() if len(scraper.images) == 0: sys.exit("Sorry, no images found.") if scraper.no_to_download is None: scraper.no_to_download = len(scraper.images) print("Found {0} images: ".format(len(scraper.images))) try: scraper.process_download_path() except DirectoryAccessError: print("Sorry, the directory can't be accessed.") sys.exit() except DirectoryCreateError: print("Sorry, the directory can't be created.") sys.exit() if scraper.dump_urls: for img_url in scraper.images: print(img_url) status_flags = {'count': 0, 'percent': 0.0, 'failed': 0, 'under_min_or_over_max_filesize': 0} widgets = ['Progress: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()] pbar = ProgressBar(widgets=widgets, maxval=100).start() pool = ThreadPoolExecutor(max_workers=scraper.nthreads) status_lock = threading.Lock() for img_url in scraper.images: if status_flags['count'] == scraper.no_to_download: break pool.submit(download_worker_fn, scraper, img_url, pbar, status_flags, status_lock) status_flags['count'] += 1 pool.shutdown(wait=True) pbar.finish() print("\nDone!\nDownloaded {0} images\nFailed: {1}\n".format( status_flags['count']-status_flags['failed']-status_flags['under_min_or_over_max_filesize'], status_flags['failed'])) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(cls, raw): """ Given a possibly-multiline string representing an SSE message, parse it and return a Event object. """
msg = cls() for line in raw.splitlines(): m = cls.sse_line_pattern.match(line) if m is None: # Malformed line. Discard but warn. warnings.warn('Invalid SSE line: "%s"' % line, SyntaxWarning) continue name = m.group('name') if name == '': # line began with a ":", so is a comment. Ignore continue value = m.group('value') if name == 'data': # If we already have some data, then join to it with a newline. # Else this is it. if msg.data: msg.data = '%s\n%s' % (msg.data, value) else: msg.data = value elif name == 'event': msg.event = value elif name == 'id': msg.id = value elif name == 'retry': msg.retry = int(value) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_upstream(repo: Repo) -> Remote: """Find upstream repository for pluggy on the remotes"""
for remote in repo.remotes: for url in remote.urls: if url.endswith("pytest-dev/pluggy.git"): return remote raise RuntimeError("could not find tox-dev/tox.git remote")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, plugin, name=None): """ Register a plugin and return its canonical name or None if the name is blocked from registering. Raise a ValueError if the plugin is already registered. """
plugin_name = name or self.get_canonical_name(plugin) if plugin_name in self._name2plugin or plugin in self._plugin2hookcallers: if self._name2plugin.get(plugin_name, -1) is None: return # blocked plugin, return None to indicate no registration raise ValueError( "Plugin already registered: %s=%s\n%s" % (plugin_name, plugin, self._name2plugin) ) # XXX if an error happens we should make sure no state has been # changed at point of return self._name2plugin[plugin_name] = plugin # register matching hook implementations of the plugin self._plugin2hookcallers[plugin] = hookcallers = [] for name in dir(plugin): hookimpl_opts = self.parse_hookimpl_opts(plugin, name) if hookimpl_opts is not None: normalize_hookimpl_opts(hookimpl_opts) method = getattr(plugin, name) hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) hook = getattr(self.hook, name, None) if hook is None: hook = _HookCaller(name, self._hookexec) setattr(self.hook, name, hook) elif hook.has_spec(): self._verify_hook(hook, hookimpl) hook._maybe_apply_history(hookimpl) hook._add_hookimpl(hookimpl) hookcallers.append(hook) return plugin_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, plugin=None, name=None): """ unregister a plugin object and all its contained hook implementations from internal data structures. """
if name is None: assert plugin is not None, "one of name or plugin needs to be specified" name = self.get_name(plugin) if plugin is None: plugin = self.get_plugin(name) # if self._name2plugin[name] == None registration was blocked: ignore if self._name2plugin.get(name): del self._name2plugin[name] for hookcaller in self._plugin2hookcallers.pop(plugin, []): hookcaller._remove_plugin(plugin) return plugin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_blocked(self, name): """ block registrations of the given name, unregister if already registered. """
self.unregister(name=name) self._name2plugin[name] = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_hookspecs(self, module_or_class): """ add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly. """
names = [] for name in dir(module_or_class): spec_opts = self.parse_hookspec_opts(module_or_class, name) if spec_opts is not None: hc = getattr(self.hook, name, None) if hc is None: hc = _HookCaller(name, self._hookexec, module_or_class, spec_opts) setattr(self.hook, name, hc) else: # plugins registered this hook without knowing the spec hc.set_specification(module_or_class, spec_opts) for hookfunction in hc.get_hookimpls(): self._verify_hook(hc, hookfunction) names.append(name) if not names: raise ValueError( "did not find any %r hooks in %r" % (self.project_name, module_or_class) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_name(self, plugin): """ Return name for registered plugin or None if not registered. """
for name, val in self._name2plugin.items(): if plugin == val: return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_pending(self): """ Verify that all hooks which have not been verified against a hook specification are optional, otherwise raise PluginValidationError"""
for name in self.hook.__dict__: if name[0] != "_": hook = getattr(self.hook, name) if not hook.has_spec(): for hookimpl in hook.get_hookimpls(): if not hookimpl.optionalhook: raise PluginValidationError( hookimpl.plugin, "unknown hook %r in plugin %r" % (name, hookimpl.plugin), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_setuptools_entrypoints(self, group, name=None): """ Load modules from querying the specified setuptools ``group``. :param str group: entry point group to load plugins :param str name: if given, loads only plugins with the given ``name``. :rtype: int :return: return the number of loaded plugins by this call. """
from pkg_resources import ( iter_entry_points, DistributionNotFound, VersionConflict, ) count = 0 for ep in iter_entry_points(group, name=name): # is the plugin registered or blocked? if self.get_plugin(ep.name) or self.is_blocked(ep.name): continue try: plugin = ep.load() except DistributionNotFound: continue except VersionConflict as e: raise PluginValidationError( plugin=None, message="Plugin %r could not be loaded: %s!" % (ep.name, e), ) self.register(plugin, name=ep.name) self._plugin_distinfo.append((plugin, ep.dist)) count += 1 return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_tracing(self): """ enable tracing of hook calls and return an undo function. """
hooktrace = self.hook._trace def before(hook_name, methods, kwargs): hooktrace.root.indent += 1 hooktrace(hook_name, kwargs) def after(outcome, hook_name, methods, kwargs): if outcome.excinfo is None: hooktrace("finish", hook_name, "-->", outcome.get_result()) hooktrace.root.indent -= 1 return self.add_hookcall_monitoring(before, after)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subset_hook_caller(self, name, remove_plugins): """ Return a new _HookCaller instance for the named method which manages calls to all registered plugins except the ones from remove_plugins. """
orig = getattr(self.hook, name) plugins_to_remove = [plug for plug in remove_plugins if hasattr(plug, name)] if plugins_to_remove: hc = _HookCaller( orig.name, orig._hookexec, orig.spec.namespace, orig.spec.opts ) for hookimpl in orig.get_hookimpls(): plugin = hookimpl.plugin if plugin not in plugins_to_remove: hc._add_hookimpl(hookimpl) # we also keep track of this hook caller so it # gets properly removed on plugin unregistration self._plugin2hookcallers.setdefault(plugin, []).append(hc) return hc return orig
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def varnames(func): """Return tuple of positional and keywrord argument names for a function, method, class or callable. In case of a class, its ``__init__`` method is considered. For methods the ``self`` parameter is not included. """
cache = getattr(func, "__dict__", {}) try: return cache["_varnames"] except KeyError: pass if inspect.isclass(func): try: func = func.__init__ except AttributeError: return (), () elif not inspect.isroutine(func): # callable object? try: func = getattr(func, "__call__", func) except Exception: return () try: # func MUST be a function or method here or we won't parse any args spec = _getargspec(func) except TypeError: return (), () args, defaults = tuple(spec.args), spec.defaults if defaults: index = -len(defaults) args, defaults = args[:index], tuple(args[index:]) else: defaults = () # strip any implicit instance arg # pypy3 uses "obj" instead of "self" for default dunder methods implicit_names = ("self",) if not _PYPY3 else ("self", "obj") if args: if inspect.ismethod(func) or ( "." in getattr(func, "__qualname__", ()) and args[0] in implicit_names ): args = args[1:] try: cache["_varnames"] = args, defaults except TypeError: pass return args, defaults
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_hookimpl(self, hookimpl): """Add an implementation to the callback chain. """
if hookimpl.hookwrapper: methods = self._wrappers else: methods = self._nonwrappers if hookimpl.trylast: methods.insert(0, hookimpl) elif hookimpl.tryfirst: methods.append(hookimpl) else: # find last non-tryfirst method i = len(methods) - 1 while i >= 0 and methods[i].tryfirst: i -= 1 methods.insert(i + 1, hookimpl) if "__multicall__" in hookimpl.argnames: warnings.warn( "Support for __multicall__ is now deprecated and will be" "removed in an upcoming release.", DeprecationWarning, ) self.multicall = _legacymulticall
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_historic(self, result_callback=None, kwargs=None, proc=None): """Call the hook with given ``kwargs`` for all registered plugins and for all plugins which will be registered afterwards. If ``result_callback`` is not ``None`` it will be called for for each non-None result obtained from a hook implementation. .. note:: The ``proc`` argument is now deprecated. """
if proc is not None: warnings.warn( "Support for `proc` argument is now deprecated and will be" "removed in an upcoming release.", DeprecationWarning, ) result_callback = proc self._call_history.append((kwargs or {}, result_callback)) # historizing hooks don't return results res = self._hookexec(self, self.get_hookimpls(), kwargs) if result_callback is None: return # XXX: remember firstresult isn't compat with historic for x in res or []: result_callback(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_extra(self, methods, kwargs): """ Call the hook with some additional temporarily participating methods using the specified kwargs as call parameters. """
old = list(self._nonwrappers), list(self._wrappers) for method in methods: opts = dict(hookwrapper=False, trylast=False, tryfirst=False) hookimpl = HookImpl(None, "<temp>", method, opts) self._add_hookimpl(hookimpl) try: return self(**kwargs) finally: self._nonwrappers, self._wrappers = old
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_apply_history(self, method): """Apply call history to a new hookimpl if it is marked as historic. """
if self.is_historic(): for kwargs, result_callback in self._call_history: res = self._hookexec(self, [method], kwargs) if res and result_callback is not None: result_callback(res[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_mp_handler(logger=None): """Wraps the handlers in the given Logger with an MultiProcessingHandler. :param logger: whose handlers to wrap. By default, the root logger. """
if logger is None: logger = logging.getLogger() for i, orig_handler in enumerate(list(logger.handlers)): handler = MultiProcessingHandler( 'mp-handler-{0}'.format(i), sub_handler=orig_handler) logger.removeHandler(orig_handler) logger.addHandler(handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_offset(target): """ returns a location's time zone offset from UTC in minutes. """
from pytz import timezone import pytz from datetime import datetime utc = pytz.utc today = datetime.now() tz_target = timezone(tf.certain_timezone_at(lat=target['lat'], lng=target['lng'])) # ATTENTION: tz_target could be None! handle error case today_target = tz_target.localize(today) today_utc = utc.localize(today) return (today_utc - today_target).total_seconds() / 60
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Establish a connection to APNs. If already connected, the function does nothing. If the connection fails, the function retries up to MAX_CONNECTION_RETRIES times. """
retries = 0 while retries < MAX_CONNECTION_RETRIES: try: self._connection.connect() logger.info('Connected to APNs') return except Exception: # pylint: disable=broad-except # close the connnection, otherwise next connect() call would do nothing self._connection.close() retries += 1 logger.exception('Failed connecting to APNs (attempt %s of %s)', retries, MAX_CONNECTION_RETRIES) raise ConnectionFailed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_raw(source, bitarray): ''' Get raw data as integer, based on offset and size ''' offset = int(source['offset']) size = int(source['size']) return int(''.join(['1' if digit else '0' for digit in bitarray[offset:offset + size]]), 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _set_raw(target, raw_value, bitarray): ''' put value into bit array ''' offset = int(target['offset']) size = int(target['size']) for digit in range(size): bitarray[offset+digit] = (raw_value >> (size-digit-1)) & 0x01 != 0 return bitarray
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_value(self, source, bitarray): ''' Get value, based on the data in XML ''' raw_value = self._get_raw(source, bitarray) rng = source.find('range') rng_min = float(rng.find('min').text) rng_max = float(rng.find('max').text) scl = source.find('scale') scl_min = float(scl.find('min').text) scl_max = float(scl.find('max').text) return { source['shortcut']: { 'description': source.get('description'), 'unit': source['unit'], 'value': (scl_max - scl_min) / (rng_max - rng_min) * (raw_value - rng_min) + scl_min, 'raw_value': raw_value, } }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_enum(self, source, bitarray): ''' Get enum value, based on the data in XML ''' raw_value = self._get_raw(source, bitarray) # Find value description. value_desc = source.find('item', {'value': str(raw_value)}) or self._get_rangeitem(source, raw_value) return { source['shortcut']: { 'description': source.get('description'), 'unit': source.get('unit', ''), 'value': value_desc['description'].format(value=raw_value), 'raw_value': raw_value, } }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_boolean(self, source, bitarray): ''' Get boolean value, based on the data in XML ''' raw_value = self._get_raw(source, bitarray) return { source['shortcut']: { 'description': source.get('description'), 'unit': source.get('unit', ''), 'value': True if raw_value else False, 'raw_value': raw_value, } }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _set_value(self, target, value, bitarray): ''' set given numeric value to target field in bitarray ''' # derive raw value rng = target.find('range') rng_min = float(rng.find('min').text) rng_max = float(rng.find('max').text) scl = target.find('scale') scl_min = float(scl.find('min').text) scl_max = float(scl.find('max').text) raw_value = (value - scl_min) * (rng_max - rng_min) / (scl_max - scl_min) + rng_min # store value in bitfield return self._set_raw(target, int(raw_value), bitarray)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_profile(self, bitarray, eep_rorg, rorg_func, rorg_type, direction=None, command=None): ''' Find profile and data description, matching RORG, FUNC and TYPE ''' if not self.init_ok: self.logger.warn('EEP.xml not loaded!') return None if eep_rorg not in self.telegrams.keys(): self.logger.warn('Cannot find rorg in EEP!') return None if rorg_func not in self.telegrams[eep_rorg].keys(): self.logger.warn('Cannot find func in EEP!') return None if rorg_type not in self.telegrams[eep_rorg][rorg_func].keys(): self.logger.warn('Cannot find type in EEP!') return None profile = self.telegrams[eep_rorg][rorg_func][rorg_type] if command: # multiple commands can be defined, with the command id always in same location (per RORG-FUNC-TYPE). eep_command = profile.find('command', recursive=False) # If commands are not set in EEP, or command is None, # get the first data as a "best guess". if not eep_command: return profile.find('data', recursive=False) # If eep_command is defined, so should be data.command return profile.find('data', {'command': str(command)}, recursive=False) # extract data description # the direction tag is optional if direction is None: return profile.find('data', recursive=False) return profile.find('data', {'direction': direction}, recursive=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_values(self, profile, bitarray, status): ''' Get keys and values from bitarray ''' if not self.init_ok or profile is None: return [], {} output = OrderedDict({}) for source in profile.contents: if not source.name: continue if source.name == 'value': output.update(self._get_value(source, bitarray)) if source.name == 'enum': output.update(self._get_enum(source, bitarray)) if source.name == 'status': output.update(self._get_boolean(source, status)) return output.keys(), output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_values(self, profile, data, status, properties): ''' Update data based on data contained in properties ''' if not self.init_ok or profile is None: return data, status for shortcut, value in properties.items(): # find the given property from EEP target = profile.find(shortcut=shortcut) if not target: # TODO: Should we raise an error? self.logger.warning('Cannot find data description for shortcut %s', shortcut) continue # update bit_data if target.name == 'value': data = self._set_value(target, value, data) if target.name == 'enum': data = self._set_enum(target, value, data) if target.name == 'status': status = self._set_boolean(target, value, status) return data, status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def combine_hex(data): ''' Combine list of integer values to one big integer ''' output = 0x00 for i, value in enumerate(reversed(data)): output |= (value << i * 8) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse(self): ''' Parse data from Packet ''' # Parse status from messages if self.rorg in [RORG.RPS, RORG.BS1, RORG.BS4]: self.status = self.data[-1] if self.rorg == RORG.VLD: self.status = self.optional[-1] if self.rorg in [RORG.RPS, RORG.BS1, RORG.BS4]: # These message types should have repeater count in the last for bits of status. self.repeater_count = enocean.utils.from_bitarray(self._bit_status[4:]) return self.parsed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def select_eep(self, rorg_func, rorg_type, direction=None, command=None): ''' Set EEP based on FUNC and TYPE ''' # set EEP profile self.rorg_func = rorg_func self.rorg_type = rorg_type self._profile = self.eep.find_profile(self._bit_data, self.rorg, rorg_func, rorg_type, direction, command) return self._profile is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_eep(self, rorg_func=None, rorg_type=None, direction=None, command=None): ''' Parse EEP based on FUNC and TYPE ''' # set EEP profile, if demanded if rorg_func is not None and rorg_type is not None: self.select_eep(rorg_func, rorg_type, direction, command) # parse data provides, values = self.eep.get_values(self._profile, self._bit_data, self._bit_status) self.parsed.update(values) return list(provides)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_eep(self, data): ''' Update packet data based on EEP. Input data is a dictionary with keys corresponding to the EEP. ''' self._bit_data, self._bit_status = self.eep.set_values(self._profile, self._bit_data, self._bit_status, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def build(self): ''' Build Packet for sending to EnOcean controller ''' data_length = len(self.data) ords = [0x55, (data_length >> 8) & 0xFF, data_length & 0xFF, len(self.optional), int(self.packet_type)] ords.append(crc8.calc(ords[1:5])) ords.extend(self.data) ords.extend(self.optional) ords.append(crc8.calc(ords[6:])) return ords
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_from_send_queue(self): ''' Get message from send queue, if one exists ''' try: packet = self.transmit.get(block=False) self.logger.info('Sending packet') self.logger.debug(packet) return packet except queue.Empty: pass return None