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 run_stacker(self, command='diff'): # pylint: disable=too-many-branches,too-many-locals """Run Stacker."""
response = {'skipped_configs': False} stacker_cmd = [command, "--region=%s" % self.context.env_region] if command == 'destroy': stacker_cmd.append('--force') elif command == 'build': if 'CI' in self.context.env_vars: stacker_cmd.append('--recreate-failed') else: stacker_cmd.append('--interactive') if 'DEBUG' in self.context.env_vars: stacker_cmd.append('--verbose') # Increase logging if requested stacker_env_file = get_stacker_env_file(self.path, self.context.env_name, self.context.env_region) stacker_env_file_present = os.path.isfile( os.path.join(self.path, stacker_env_file) ) if isinstance(self.options.get('environments', {}).get(self.context.env_name), dict): for (key, val) in self.options['environments'][self.context.env_name].items(): # noqa stacker_cmd.extend(['-e', "%s=%s" % (key, val)]) if stacker_env_file_present: stacker_cmd.append(stacker_env_file) if not (stacker_env_file_present or self.options.get( 'environments', {}).get(self.context.env_name)): response['skipped_configs'] = True LOGGER.info( "Skipping stacker %s; no environment " "file found for this environment/region " "(looking for one of \"%s\")", command, ', '.join( gen_stacker_env_files(self.context.env_name, # noqa self.context.env_region)) # noqa ) else: with change_dir(self.path): # Iterate through any stacker yaml configs to deploy them in order # or destroy them in reverse order for _root, _dirs, files in os.walk(self.path): sorted_files = sorted(files) if command == 'destroy': sorted_files = reversed(sorted_files) for name in sorted_files: if re.match(r"runway(\..*)?\.yml", name) or ( name.startswith('.')): # Hidden files (e.g. .gitlab-ci.yml) or runway configs # definitely aren't stacker config files continue if os.path.splitext(name)[1] in ['.yaml', '.yml']: ensure_stacker_compat_config( os.path.join(self.path, name) ) LOGGER.info("Running stacker %s on %s in region %s", command, name, self.context.env_region) stacker_cmd_str = make_stacker_cmd_string( stacker_cmd + [name], get_embedded_lib_path() ) stacker_cmd_list = [sys.executable, '-c'] LOGGER.debug( "Stacker command being executed: %s \"%s\"", ' '.join(stacker_cmd_list), stacker_cmd_str ) run_module_command( cmd_list=stacker_cmd_list + [stacker_cmd_str], env_vars=self.context.env_vars ) break # only need top level files return response
<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_cf_distribution_class(): """Return the correct troposphere CF distribution class."""
if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): cf_dist = cloudfront.Distribution cf_dist.props['DistributionConfig'] = (DistributionConfig, True) return cf_dist return cloudfront.Distribution
<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_s3_origin_conf_class(): """Return the correct S3 Origin Config class for troposphere."""
if LooseVersion(troposphere.__version__) > LooseVersion('2.4.0'): return cloudfront.S3OriginConfig if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): return S3OriginConfig return cloudfront.S3Origin
<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_available(self, show=None): """ Sets the agent availability to True. Args: show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None) """
show = self.state.show if show is None else show self.set_presence(PresenceState(available=True, show=show))
<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_unavailable(self): """Sets the agent availability to False."""
show = PresenceShow.NONE self.set_presence(PresenceState(available=False, show=show))
<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_presence(self, state=None, status=None, priority=None): """ Change the presence broadcast by the client. If the client is currently connected, the new presence is broadcast immediately. Args: state(aioxmpp.PresenceState, optional): New presence state to broadcast (Default value = None) status(dict or str, optional): New status information to broadcast (Default value = None) priority (int, optional): New priority for the resource (Default value = None) """
state = state if state is not None else self.state status = status if status is not None else self.status priority = priority if priority is not None else self.priority self.presenceserver.set_presence(state, status, priority)
<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_contacts(self): """ Returns list of contacts Returns: dict: the roster of contacts """
for jid, item in self.roster.items.items(): try: self._contacts[jid.bare()].update(item.export_as_json()) except KeyError: self._contacts[jid.bare()] = item.export_as_json() return self._contacts
<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_contact(self, jid): """ Returns a contact Args: jid (aioxmpp.JID): jid of the contact Returns: dict: the roster of contacts """
try: return self.get_contacts()[jid.bare()] except KeyError: raise ContactNotFound except AttributeError: raise AttributeError("jid must be an aioxmpp.JID object")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscribe(self, peer_jid): """ Asks for subscription Args: peer_jid (str): the JID you ask for subscriptiion """
self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsubscribe(self, peer_jid): """ Asks for unsubscription Args: peer_jid (str): the JID you ask for unsubscriptiion """
self.roster.unsubscribe(aioxmpp.JID.fromstr(peer_jid).bare())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def approve(self, peer_jid): """ Approve a subscription request from jid Args: peer_jid (str): the JID to approve """
self.roster.approve(aioxmpp.JID.fromstr(peer_jid).bare())
<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(self, event, category=None): """ Adds a new event to the trace store. The event may hava a category Args: event (spade.message.Message): the event to be stored category (str, optional): a category to classify the event (Default value = None) """
date = datetime.datetime.now() self.store.insert(0, (date, event, category)) if len(self.store) > self.size: del self.store[-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 filter(self, limit=None, to=None, category=None): """ Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default value = None) category (str, optional): only events belonging to the category (Default value = None) Returns: list: a list of filtered events """
if category and not to: msg_slice = itertools.islice((x for x in self.store if x[2] == category), limit) elif to and not category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1])), limit) elif to and category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1]) and x[2] == category), limit) else: msg_slice = self.all(limit=limit) return msg_slice return list(msg_slice)[::-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 start(self, auto_register=True): """ Tells the container to start this agent. It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method. Args: auto_register (bool): register the agent in the server (Default value = True) """
return self.container.start_agent(agent=self, auto_register=auto_register)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _async_connect(self): # pragma: no cover """ connect and authenticate to the XMPP server. Async mode. """
try: self.conn_coro = self.client.connected() aenter = type(self.conn_coro).__aenter__(self.conn_coro) self.stream = await aenter logger.info(f"Agent {str(self.jid)} connected and authenticated.") except aiosasl.AuthenticationFailure: raise AuthenticationFailure( "Could not authenticate the agent. Check user and password or use auto_register=True")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _async_register(self): # pragma: no cover """ Register the agent in the XMPP server from a coroutine. """
metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security) query = ibr.Query(self.jid.localpart, self.password) _, stream, features = await aioxmpp.node.connect_xmlstream(self.jid, metadata, loop=self.loop) await ibr.register(stream, query)
<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_avatar_url(jid): """ Static method to build a gravatar url with the agent's JID Args: jid (aioxmpp.JID): an XMPP identifier Returns: str: an URL for the gravatar """
digest = md5(str(jid).encode("utf-8")).hexdigest() return "http://www.gravatar.com/avatar/{md5}?d=monsterid".format(md5=digest)
<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_behaviour(self, behaviour, template=None): """ Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and deliver them to the behaviour. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour to be started template (spade.template.Template, optional): the template to match messages with (Default value = None) """
behaviour.set_agent(self) if issubclass(type(behaviour), FSMBehaviour): for _, state in behaviour.get_states().items(): state.set_agent(self) behaviour.set_template(template) self.behaviours.append(behaviour) if self.is_alive(): behaviour.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_behaviour(self, behaviour): """ Removes a behaviour from the agent. The behaviour is first killed. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour instance to be removed """
if not self.has_behaviour(behaviour): raise ValueError("This behaviour is not registered") index = self.behaviours.index(behaviour) self.behaviours[index].kill() self.behaviours.pop(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _async_stop(self): """ Stops an agent and kills all its behaviours. """
if self.presence: self.presence.set_unavailable() for behav in self.behaviours: behav.kill() if self.web.is_started(): await self.web.runner.cleanup() """ Discconnect from XMPP server. """ if self.is_alive(): # Disconnect from XMPP server self.client.stop() aexit = self.conn_coro.__aexit__(*sys.exc_info()) await aexit logger.info("Client disconnected.") self._alive.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _message_received(self, msg): """ Callback run when an XMPP Message is reveived. This callback delivers the message to every behaviour that is waiting for it. First, the aioxmpp.Message is converted to spade.message.Message Args: msg (aioxmpp.Messagge): the message just received. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour. """
msg = Message.from_node(msg) return self.dispatch(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 dispatch(self, msg): """ Dispatch the message to every behaviour that is waiting for it using their templates match. Args: msg (spade.message.Messagge): the message to dispatch. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour. """
logger.debug(f"Got message: {msg}") futures = [] matched = False for behaviour in (x for x in self.behaviours if x.match(msg)): futures.append(self.submit(behaviour.enqueue(msg))) logger.debug(f"Message enqueued to behaviour: {behaviour}") self.traces.append(msg, category=str(behaviour)) matched = True if not matched: logger.warning(f"No behaviour matched for message: {msg}") self.traces.append(msg) return futures
<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_node(cls, node): """ Creates a new spade.message.Message from an aixoxmpp.stanza.Message Args: node (aioxmpp.stanza.Message): an aioxmpp Message Returns: spade.message.Message: a new spade Message """
if not isinstance(node, aioxmpp.stanza.Message): raise AttributeError("node must be a aioxmpp.stanza.Message instance") msg = cls() msg._to = node.to msg._sender = node.from_ if None in node.body: msg.body = node.body[None] else: for key in node.body.keys(): msg.body = node.body[key] break for data in node.xep0004_data: if data.title == SPADE_X_METADATA: for field in data.fields: if field.var != "_thread_node": msg.set_metadata(field.var, field.values[0]) else: msg.thread = field.values[0] 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 to(self, jid: str): """ Set jid of the receiver. Args: jid (str): the jid of the receiver. """
if jid is not None and not isinstance(jid, str): raise TypeError("'to' MUST be a string") self._to = aioxmpp.JID.fromstr(jid) if jid is not None else 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 sender(self, jid: str): """ Set jid of the sender Args: jid (str): jid of the sender """
if jid is not None and not isinstance(jid, str): raise TypeError("'sender' MUST be a string") self._sender = aioxmpp.JID.fromstr(jid) if jid is not None else 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 thread(self, value: str): """ Set thread id of the message Args: value (str): the thread id """
if value is not None and not isinstance(value, str): raise TypeError("'thread' MUST be a string") self._thread = 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_metadata(self, key: str, value: str): """ Add a new metadata to the message Args: key (str): name of the metadata value (str): value of the metadata """
if not isinstance(key, str) or not isinstance(value, str): raise TypeError("'key' and 'value' of metadata MUST be strings") self.metadata[key] = 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_metadata(self, key) -> str: """ Get the value of a metadata. Returns None if metadata does not exist. Args: key (str): name of the metadata Returns: str: the value of the metadata (or None) """
return self.metadata[key] if key in self.metadata else 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 match(self, message) -> bool: """ Returns wether a message matches with this message or not. The message can be a Message object or a Template object. Args: message (spade.message.Message): the message to match to Returns: bool: wether the message matches or not """
if self.to and message.to != self.to: return False if self.sender and message.sender != self.sender: return False if self.body and message.body != self.body: return False if self.thread and message.thread != self.thread: return False for key, value in self.metadata.items(): if message.get_metadata(key) != value: return False logger.debug(f"message matched {self} == {message}") 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 make_reply(self): """ Creates a copy of the message, exchanging sender and receiver Returns: spade.message.Message: a new message with exchanged sender and receiver """
return Message( to=str(self.sender), sender=str(self.to), body=self.body, thread=self.thread, metadata=self.metadata )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self): """ Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent """
msg = aioxmpp.stanza.Message( to=self.to, from_=self.sender, type_=aioxmpp.MessageType.CHAT, ) msg.body[None] = self.body # Send metadata using xep-0004: Data Forms (https://xmpp.org/extensions/xep-0004.html) if len(self.metadata): data = forms_xso.Data(type_=forms_xso.DataType.FORM) for name, value in self.metadata.items(): data.fields.append( forms_xso.Field( var=name, type_=forms_xso.FieldType.TEXT_SINGLE, values=[value], ) ) if self.thread: data.fields.append(forms_xso.Field(var="_thread_node", type_=forms_xso.FieldType.TEXT_SINGLE, values=[self.thread])) data.title = SPADE_X_METADATA msg.xep0004_data = [data] 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 unused_port(hostname): """Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((hostname, 0)) return s.getsockname()[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def start_server_in_loop(runner, hostname, port, agent): """ Listens to http requests and sends them to the webapp. Args: runner: AppRunner to process the http requests hostname: host name to listen from. port: port to listen from. agent: agent that owns the web app. """
await runner.setup() agent.web.server = aioweb.TCPSite(runner, hostname, port) await agent.web.server.start() logger.info(f"Serving on http://{hostname}:{port}/")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, hostname=None, port=None, templates_path=None): """ Starts the web interface. Args: hostname (str, optional): host name to listen from. (Default value = None) port (int, optional): port to listen from. (Default value = None) templates_path (str, optional): path to look for templates. (Default value = None) """
self.hostname = hostname if hostname else "localhost" if port: self.port = port elif not self.port: self.port = unused_port(self.hostname) if templates_path: self.loaders.insert(0, jinja2.FileSystemLoader(templates_path)) self._set_loaders() self.setup_routes() self.runner = aioweb.AppRunner(self.app) return self.agent.submit(start_server_in_loop(self.runner, self.hostname, self.port, self.agent))
<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_get(self, path, controller, template, raw=False): """ Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not """
if raw: fn = controller else: fn = self._prepare_controller(controller, template) self.app.router.add_get(path, fn)
<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_agent(self, agent): """ Links behaviour with its owner agent Args: agent (spade.agent.Agent): the agent who owns the behaviour """
self.agent = agent self.queue = asyncio.Queue(loop=self.agent.loop) self.presence = agent.presence self.web = agent.web
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, message: Message) -> bool: """ Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Returns: bool: wheter the messaged matches or not """
if self.template: return self.template.match(message) 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 set(self, name: str, value: Any) -> None: """ Stores a knowledge item in the agent knowledge base. Args: name (str): name of the item value (Any): value of the item """
self.agent.set(name, 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 start(self): """starts behaviour in the event loop"""
self.agent.submit(self._start()) self.is_running = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _start(self): """ Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called. """
self.agent._alive.wait() try: await self.on_start() except Exception as e: logger.error("Exception running on_start in behaviour {}: {}".format(self, e)) self.kill(exit_code=e) await self._step() self._is_done.clear()
<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, exit_code: Any = None): """ Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None) """
self._force_kill.set() if exit_code is not None: self._exit_code = exit_code logger.info("Killing behavior {0} with exit code: {1}".format(self, exit_code))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exit_code(self) -> Any: """ Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception. Returns: object: the exit code of the behaviour """
if self._done() or self.is_killed(): return self._exit_code else: raise BehaviourNotFinishedException
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def send(self, msg: Message): """ Sends a message. Args: msg (spade.message.Message): the message to be sent. """
if not msg.sender: msg.sender = str(self.agent.jid) logger.debug(f"Adding agent's jid as sender to message: {msg}") await self.agent.container.send(msg, self) msg.sent = True self.agent.traces.append(msg, category=str(self))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def receive(self, timeout: float = None) -> Union[Message, None]: """ Receives a message for this behaviour. If timeout is not None it returns the message or "None" after timeout is done. Args: timeout (float): number of seconds until return Returns: spade.message.Message: a Message or None """
if timeout: coro = self.queue.get() try: msg = await asyncio.wait_for(coro, timeout=timeout) except asyncio.TimeoutError: msg = None else: try: msg = self.queue.get_nowait() except asyncio.QueueEmpty: msg = None 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 period(self, value: float): """ Set the period. Args: value (float): seconds """
if value < 0: raise ValueError("Period must be greater or equal than zero.") self._period = timedelta(seconds=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 add_state(self, name: str, state: State, initial: bool = False): """ Adds a new state to the FSM. Args: name (str): the name of the state, which is used as its identifier. state (spade.behaviour.State): The state class initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False) """
if not issubclass(state.__class__, State): raise AttributeError("state must be subclass of spade.behaviour.State") self._states[name] = state if initial: self.current_state = 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 add_transition(self, source: str, dest: str): """ Adds a transition from one state to another. Args: source (str): the name of the state from where the transition starts dest (str): the name of the state where the transition ends """
self._transitions[source].append(dest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_transition(self, source: str, dest: str) -> bool: """ Checks if a transitions is registered in the FSM Args: source (str): the source state name dest (str): the destination state name Returns: bool: wether the transition is valid or not """
if dest not in self._states or source not in self._states: raise NotValidState elif dest not in self._transitions[source]: raise NotValidTransition 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 to_graphviz(self) -> str: """ Converts the FSM behaviour structure to Graphviz syntax Returns: str: the graph in Graphviz syntax """
graph = "digraph finite_state_machine { rankdir=LR; node [fixedsize=true];" for origin, dest in self._transitions.items(): origin = origin.replace(" ", "_") for d in dest: d = d.replace(" ", "_") graph += "{0} -> {1};".format(origin, d) graph += "}" return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resample(x, sr_orig, sr_new, axis=-1, filter='kaiser_best', **kwargs): '''Resample a signal x from sr_orig to sr_new along a given axis. Parameters ---------- x : np.ndarray, dtype=np.float* The input signal(s) to resample. sr_orig : int > 0 The sampling rate of x sr_new : int > 0 The target sampling rate of the output signal(s) axis : int The target axis along which to resample `x` filter : optional, str or callable The resampling filter to use. By default, uses the `kaiser_best` (pre-computed filter). kwargs additional keyword arguments provided to the specified filter Returns ------- y : np.ndarray `x` resampled to `sr_new` Raises ------ ValueError if `sr_orig` or `sr_new` is not positive TypeError if the input signal `x` has an unsupported data type. Examples -------- >>> # Generate a sine wave at 440 Hz for 5 seconds >>> sr_orig = 44100.0 >>> x = np.sin(2 * np.pi * 440.0 / sr_orig * np.arange(5 * sr_orig)) >>> x array([ 0. , 0.063, ..., -0.125, -0.063]) >>> # Resample to 22050 with default parameters >>> resampy.resample(x, sr_orig, 22050) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using the fast (low-quality) filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_fast') array([ 0.013, 0.121, ..., -0.189, -0.102]) >>> # Resample using a high-quality filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_best') array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using a Hann-windowed sinc filter >>> resampy.resample(x, sr_orig, 22050, filter='sinc_window', ... window=scipy.signal.hann) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Generate stereo data >>> x_right = np.sin(2 * np.pi * 880.0 / sr_orig * np.arange(len(x)))]) >>> x_stereo = np.stack([x, x_right]) >>> x_stereo.shape (2, 220500) >>> # Resample along the time axis (1) >>> y_stereo = resampy.resample(x, sr_orig, 22050, axis=1) >>> y_stereo.shape (2, 110250) ''' if sr_orig <= 0: raise ValueError('Invalid sample rate: sr_orig={}'.format(sr_orig)) if sr_new <= 0: raise ValueError('Invalid sample rate: sr_new={}'.format(sr_new)) sample_ratio = float(sr_new) / sr_orig # Set up the output shape shape = list(x.shape) shape[axis] = int(shape[axis] * sample_ratio) if shape[axis] < 1: raise ValueError('Input signal length={} is too small to ' 'resample from {}->{}'.format(x.shape[axis], sr_orig, sr_new)) y = np.zeros(shape, dtype=x.dtype) interp_win, precision, _ = get_filter(filter, **kwargs) if sample_ratio < 1: interp_win *= sample_ratio interp_delta = np.zeros_like(interp_win) interp_delta[:-1] = np.diff(interp_win) # Construct 2d views of the data with the resampling axis on the first dimension x_2d = x.swapaxes(0, axis).reshape((x.shape[axis], -1)) y_2d = y.swapaxes(0, axis).reshape((y.shape[axis], -1)) resample_f(x_2d, y_2d, sample_ratio, interp_win, interp_delta, precision) return y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sinc_window(num_zeros=64, precision=9, window=None, rolloff=0.945): '''Construct a windowed sinc interpolation filter Parameters ---------- num_zeros : int > 0 The number of zero-crossings to retain in the sinc filter precision : int > 0 The number of filter coefficients to retain for each zero-crossing window : callable The window function. By default, uses Blackman-Harris. rolloff : float > 0 The roll-off frequency (as a fraction of nyquist) Returns ------- interp_window: np.ndarray [shape=(num_zeros * num_table + 1)] The interpolation window (right-hand side) num_bits: int The number of bits of precision to use in the filter table rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist Raises ------ TypeError if `window` is not callable or `None` ValueError if `num_zeros < 1`, `precision < 1`, or `rolloff` is outside the range `(0, 1]`. Examples -------- >>> # A filter with 10 zero-crossings, 32 samples per crossing, and a ... # Hann window for tapering. >>> halfwin, prec, rolloff = resampy.filters.sinc_window(num_zeros=10, precision=5, ... window=scipy.signal.hann) >>> halfwin array([ 9.450e-01, 9.436e-01, ..., -7.455e-07, -0.000e+00]) >>> prec 32 >>> rolloff 0.945 >>> # Or using sinc-window filter construction directly in resample >>> y = resampy.resample(x, sr_orig, sr_new, filter='sinc_window', ... num_zeros=10, precision=5, ... window=scipy.signal.hann) ''' if window is None: window = scipy.signal.blackmanharris elif not six.callable(window): raise TypeError('window must be callable, not type(window)={}'.format(type(window))) if not 0 < rolloff <= 1: raise ValueError('Invalid roll-off: rolloff={}'.format(rolloff)) if num_zeros < 1: raise ValueError('Invalid num_zeros: num_zeros={}'.format(num_zeros)) if precision < 0: raise ValueError('Invalid precision: precision={}'.format(precision)) # Generate the right-wing of the sinc num_bits = 2**precision n = num_bits * num_zeros sinc_win = rolloff * np.sinc(rolloff * np.linspace(0, num_zeros, num=n + 1, endpoint=True)) # Build the window function and cut off the left half taper = window(2 * n + 1)[n:] interp_win = (taper * sinc_win) return interp_win, num_bits, rolloff
<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_filter(name_or_function, **kwargs): '''Retrieve a window given its name or function handle. Parameters ---------- name_or_function : str or callable If a function, returns `name_or_function(**kwargs)`. If a string, and it matches the name of one of the defined filter functions, the corresponding function is called with `**kwargs`. If a string, and it matches the name of a pre-computed filter, the corresponding filter is retrieved, and kwargs is ignored. Valid pre-computed filter names are: - 'kaiser_fast' - 'kaiser_best' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the filter rolloff : float > 0 The roll-off frequency of the filter as a fraction of Nyquist Raises ------ NotImplementedError If `name_or_function` cannot be found as a filter. ''' if name_or_function in FILTER_FUNCTIONS: return getattr(sys.modules[__name__], name_or_function)(**kwargs) elif six.callable(name_or_function): return name_or_function(**kwargs) else: try: return load_filter(name_or_function) except (IOError, ValueError): raise NotImplementedError('Cannot load filter definition for ' '{}'.format(name_or_function))
<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_filter(filter_name): '''Retrieve a pre-computed filter. Parameters ---------- filter_name : str The key of the filter, e.g., 'kaiser_fast' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the fitler rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist ''' fname = os.path.join('data', os.path.extsep.join([filter_name, 'npz'])) data = np.load(pkg_resources.resource_filename(__name__, fname)) return data['half_window'], data['precision'], data['rolloff']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_values_of(func): """Return the defaults of the function `func`."""
signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def required_arguments(func): """Return all arguments of a function that do not have a default value."""
defaults = default_values_of(func) args = arguments_of(func) if defaults: args = args[:-len(defaults)] return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Prompt the user to enter a free text message. This question type can be used to prompt the user for some text input. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """
merged_style = merge_styles([DEFAULT_STYLE, style]) validator = build_validator(validate) def get_prompt_tokens(): return [("class:qmark", qmark), ("class:question", ' {} '.format(message))] p = PromptSession(get_prompt_tokens, style=merged_style, validator=validator, **kwargs) p.default_buffer.reset(Document(default)) return Question(p.app)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip_if(self, condition: bool, default: Any = None) -> 'Question': """Skip the question if flag is set and return the default instead."""
self.should_skip_question = condition self.default = default return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update."""
default_container = ps.layout.container default_buffer_window = \ default_container.get_children()[0].content.get_children()[1].content assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small as possible, avoiding # empty lines in selections default_buffer_window.dont_extend_height = Always()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: """Create a layout combining question and inquirer selection."""
ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary_blank_lines(ps) return Layout(HSplit([ ps.layout.container, ConditionalContainer( Window(ic), filter=~IsDone() ) ]))
<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(c: Union[Text, 'Choice', Dict[Text, Any]]) -> 'Choice': """Create a choice object from different representations."""
if isinstance(c, Choice): return c elif isinstance(c, str): return Choice(c, c) else: return Choice(c.get('name'), c.get('value'), c.get('disabled', None), c.get('checked'), c.get('key'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """
return text.text(message, default, validate, qmark, style, is_password=True, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form(**kwargs: Question): """Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict."""
return Form(*(FormField(k, q) for k, q in kwargs.items()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt(questions: List[Dict[Text, Any]], answers: Optional[Dict[Text, Any]] = None, patch_stdout: bool = False, true_color: bool = False, kbi_msg: Text = DEFAULT_KBI_MESSAGE, **kwargs): """Prompt the user for input on all the questions."""
if isinstance(questions, dict): questions = [questions] answers = answers or {} for question_config in questions: # import the question if 'type' not in question_config: raise PromptParameterException('type') if 'name' not in question_config: raise PromptParameterException('name') choices = question_config.get('choices') if choices is not None and callable(choices): question_config['choices'] = choices(answers) _kwargs = kwargs.copy() _kwargs.update(question_config) _type = _kwargs.pop('type') _filter = _kwargs.pop('filter', None) name = _kwargs.pop('name') when = _kwargs.pop('when', None) if true_color: _kwargs["color_depth"] = ColorDepth.TRUE_COLOR try: if when: # at least a little sanity check! if callable(question_config['when']): try: if not question_config['when'](answers): continue except Exception as e: raise ValueError("Problem in 'when' check of {} " "question: {}".format(name, e)) else: raise ValueError("'when' needs to be function that " "accepts a dict argument") if _filter: # at least a little sanity check! if not callable(_filter): raise ValueError("'filter' needs to be function that " "accepts an argument") if callable(question_config.get('default')): _kwargs['default'] = question_config['default'](answers) create_question_func = prompt_by_name(_type) if not create_question_func: raise ValueError("No question type '{}' found. " "Known question types are {}." "".format(_type, ", ".join(AVAILABLE_PROMPTS))) missing_args = list(utils.missing_arguments(create_question_func, _kwargs)) if missing_args: raise PromptParameterException(missing_args[0]) question = create_question_func(**_kwargs) answer = question.unsafe_ask(patch_stdout) if answer is not None: if _filter: try: answer = _filter(answer) except Exception as e: raise ValueError("Problem processing 'filter' of {} " "question: {}".format(name, e)) answers[name] = answer except KeyboardInterrupt: print('') print(kbi_msg) print('') return {} return answers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confirm(message: Text, default: bool = True, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Prompt the user to confirm or reject. This question type can be used to prompt the user for a confirmation of a yes-or-no question. If the user just hits enter, the default value will be returned. Args: message: Question text default: Default value will be returned if the user just hits enter. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """
merged_style = merge_styles([DEFAULT_STYLE, style]) status = {'answer': None} def get_prompt_tokens(): tokens = [] tokens.append(("class:qmark", qmark)) tokens.append(("class:question", ' {} '.format(message))) if status['answer'] is not None: answer = ' {}'.format(YES if status['answer'] else NO) tokens.append(("class:answer", answer)) else: instruction = ' {}'.format(YES_OR_NO if default else NO_OR_YES) tokens.append(("class:instruction", instruction)) return to_formatted_text(tokens) bindings = KeyBindings() @bindings.add(Keys.ControlQ, eager=True) @bindings.add(Keys.ControlC, eager=True) def _(event): event.app.exit(exception=KeyboardInterrupt, style='class:aborting') @bindings.add('n') @bindings.add('N') def key_n(event): status['answer'] = False event.app.exit(result=False) @bindings.add('y') @bindings.add('Y') def key_y(event): status['answer'] = True event.app.exit(result=True) @bindings.add(Keys.ControlM, eager=True) def set_answer(event): status['answer'] = default event.app.exit(result=default) @bindings.add(Keys.Any) def other(event): """Disallow inserting other text.""" pass return Question(PromptSession(get_prompt_tokens, key_bindings=bindings, style=merged_style, **kwargs).app)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rawselect(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Ask the user to select one item from a list of choices using shortcuts. The user can only select one option. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Passing `Choice` objects, allows you to configure the item more (e.g. preselecting it or disabeling it). default: Default return value (single value). qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """
return select.select(message, choices, default, qmark, style, use_shortcuts=True, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _discover_models(self): """ Return a dict containing a list of cassandra.cqlengine.Model classes within installed App. """
apps = get_installed_apps() connection = self.connection.connection.alias keyspace = self.connection.connection.keyspace for app in apps: self._cql_models[app.__name__] = get_cql_models( app, connection=connection, keyspace=keyspace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def django_table_names(self, only_existing=False, **kwargs): """ Returns a list of all table names that have associated cqlengine models and are present in settings.INSTALLED_APPS. """
all_models = list(chain.from_iterable(self.cql_models.values())) tables = [model.column_family_name(include_keyspace=False) for model in all_models] return tables
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_names(self, cursor=None, **kwargs): """ Returns all table names in current keyspace """
# Avoid migration code being executed if cursor: return [] connection = self.connection.connection keyspace_name = connection.keyspace if not connection.cluster.schema_metadata_enabled and \ keyspace_name not in connection.cluster.metadata.keyspaces: connection.cluster.refresh_schema_metadata() keyspace = connection.cluster.metadata.keyspaces[keyspace_name] return keyspace.tables
<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_models_keyspace(self, keyspace): """Set keyspace for all connection models"""
for models in self.connection.introspection.cql_models.values(): for model in models: model.__keyspace__ = keyspace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _import_management(): """ Import the 'management' module within each installed app, to register dispatcher events. """
from importlib import import_module for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except SystemError: # We get SystemError if INSTALLED_APPS contains the # name of a class rather than a module pass except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith('No module named') \ or 'management' not in msg: raise
<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_installed_apps(): """ Return list of all installed apps """
if django.VERSION >= (1, 7): from django.apps import apps return [a.models_module for a in apps.get_app_configs() if a.models_module is not None] else: from django.db import models return models.get_apps()
<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(self, *args, **options): """ Pretend django_cassandra_engine to be dummy database backend with no support for migrations. """
self._change_cassandra_engine_name('django.db.backends.dummy') try: super(Command, self).handle(*args, **options) finally: self._change_cassandra_engine_name('django_cassandra_engine')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sql_flush(self, style, tables, sequences, allow_cascade=False): """ Truncate all existing tables in current keyspace. :returns: an empty list """
for table in tables: qs = "TRUNCATE {}".format(table) self.connection.connection.execute(qs) 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 add_field(self, field, **kwargs): """Add each field as a private field."""
getattr(self, self._private_fields_name).append(field) self._expire_cache(reverse=True) self._expire_cache(reverse=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 _give_columns_django_field_attributes(self): """ Add Django Field attributes to each cqlengine.Column instance. So that the Django Options class may interact with it as if it were a Django Field. """
methods_to_add = ( django_field_methods.value_from_object, django_field_methods.value_to_string, django_field_methods.get_attname, django_field_methods.get_cache_name, django_field_methods.pre_save, django_field_methods.get_prep_value, django_field_methods.get_choices, django_field_methods.get_choices_default, django_field_methods.save_form_data, django_field_methods.formfield, django_field_methods.get_db_prep_value, django_field_methods.get_db_prep_save, django_field_methods.db_type_suffix, django_field_methods.select_format, django_field_methods.get_internal_type, django_field_methods.get_attname_column, django_field_methods.check, django_field_methods._check_field_name, django_field_methods._check_db_index, django_field_methods.deconstruct, django_field_methods.run_validators, django_field_methods.clean, django_field_methods.get_db_converters, django_field_methods.get_prep_lookup, django_field_methods.get_db_prep_lookup, django_field_methods.get_filter_kwargs_for_object, django_field_methods.set_attributes_from_name, django_field_methods.db_parameters, django_field_methods.get_pk_value_on_save, django_field_methods.get_col, ) for name, cql_column in six.iteritems(self._defined_columns): self._set_column_django_attributes(cql_column=cql_column, name=name) for method in methods_to_add: try: method_name = method.func_name except AttributeError: # python 3 method_name = method.__name__ new_method = six.create_bound_method(method, cql_column) setattr(cql_column, method_name, new_method)
<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_column(cls, name): """ Based on cqlengine.models.BaseModel._get_column. But to work with 'pk' """
if name == 'pk': return cls._meta.get_field(cls._meta.pk.name) return cls._columns[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 _get_next(request): """ The part that's the least straightforward about views in this module is how they determine their redirects after they have finished computation. In short, they will try and determine the next place to go in the following order: 1. If there is a variable named ``next`` in the *POST* parameters, the view will redirect to that variable's value. 2. If there is a variable named ``next`` in the *GET* parameters, the view will redirect to that variable's value. 3. If Django can determine the previous page from the HTTP headers, the view will redirect to that previous page. """
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None))) if not next: next = request.path return next
<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_cache_key(user_or_username, size, prefix): """ Returns a cache key consisten of a username and image size. """
if isinstance(user_or_username, get_user_model()): user_or_username = get_username(user_or_username) key = six.u('%s_%s_%s') % (prefix, user_or_username, size) return six.u('%s_%s') % (slugify(key)[:100], hashlib.md5(force_bytes(key)).hexdigest())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_result(default_size=settings.AVATAR_DEFAULT_SIZE): """ Decorator to cache the result of functions that take a ``user`` and a ``size`` value. """
if not settings.AVATAR_CACHE_ENABLED: def decorator(func): return func return decorator def decorator(func): def cached_func(user, size=None, **kwargs): prefix = func.__name__ cached_funcs.add(prefix) key = get_cache_key(user, size or default_size, prefix=prefix) result = cache.get(key) if result is None: result = func(user, size or default_size, **kwargs) cache_set(key, result) return result return cached_func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate_cache(user, size=None): """ Function to be called when saving or changing an user's avatars. """
sizes = set(settings.AVATAR_AUTO_GENERATE_SIZES) if size is not None: sizes.add(size) for prefix in cached_funcs: for size in sizes: cache.delete(get_cache_key(user, size, prefix))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create(self, institution_id, initial_products, _options=None, webhook=None, transactions__start_date=None, transactions__end_date=None, ): ''' Generate a public token for sandbox testing. :param str institution_id: :param [str] initial_products: :param str webhook: ''' options = _options or {} if webhook is not None: options['webhook'] = webhook transaction_options = {} transaction_options.update(options.get('transactions', {})) if transactions__start_date is not None: transaction_options['start_date'] = transactions__start_date if transactions__end_date is not None: transaction_options['end_date'] = transactions__end_date if transaction_options: options['transactions'] = transaction_options return self.client.post_public_key('/sandbox/public_token/create', { 'institution_id': institution_id, 'initial_products': initial_products, 'options': options, })
<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_response(response): ''' Create an error of the right class from an API response. :param response dict Response JSON ''' cls = PLAID_ERROR_TYPE_MAP.get(response['error_type'], PlaidError) return cls(response['error_message'], response['error_type'], response['error_code'], response['display_message'], response['request_id'], response.get('causes'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create(self, access_tokens, days_requested, options=None): ''' Create an asset report. :param [str] access_tokens: A list of access tokens, one token for each Item to be included in the Asset Report. :param int days_requested: Days of transaction history requested to be included in the Asset Report. :param dict options: An optional dictionary. For more information on the options object, see the documentation site listed above. ''' options = options or {} return self.client.post('/asset_report/create', { 'access_tokens': access_tokens, 'days_requested': days_requested, 'options': options, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def refresh(self, asset_report_token, days_requested, options=None): ''' Create a new, refreshed asset report based on an existing asset report. :param str asset_report_token: The existing Asset Report's asset report token. :param int days_requested: Days of transaction history requested to be included in the Asset Report. :param dict options: An optional dictionary. This is the same object used in `create`. ''' options = options or {} return self.client.post('/asset_report/refresh', { 'asset_report_token': asset_report_token, 'days_requested': days_requested, 'options': options, })
<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(self, asset_report_token, include_insights=False): ''' Retrieves an asset report. :param str asset_report_token: The asset report token for the asset report you created. :param bool include_insights: An optional boolean specifying whether we should retrieve the report as an Asset Report with Insights. For more, see https://plaid.com/docs/#retrieve-json-report-request. ''' return self.client.post('/asset_report/get', { 'asset_report_token': asset_report_token, 'include_insights': include_insights, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def post(self, path, data, is_json=True): '''Make a post request with client_id and secret key.''' post_data = { 'client_id': self.client_id, 'secret': self.secret, } post_data.update(data) return self._post(path, post_data, is_json)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def post_public(self, path, data, is_json=True): '''Make a post request requiring no auth.''' return self._post(path, data, is_json)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def post_public_key(self, path, data, is_json=True): '''Make a post request using a public key.''' post_data = { 'public_key': self.public_key } post_data.update(data) return self._post(path, post_data, is_json)
<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_by_id(self, institution_id, _options=None): ''' Fetch a single institution by id. :param str institution_id: ''' options = _options or {} return self.client.post_public_key('/institutions/get_by_id', { 'institution_id': institution_id, 'options': options, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search(self, query, _options={}, products=None): ''' Search all institutions by name. :param str query: Query against the full list of institutions. :param [str] products: Filter FIs by available products. Optional. ''' options = _options or {} return self.client.post_public_key('/institutions/search', { 'query': query, 'products': products, 'options': options, })
<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_avro(file_path_or_buffer, schema=None, **kwargs): """ Avro file reader. Args: file_path_or_buffer: Input file path or file-like object. schema: Avro schema. **kwargs: Keyword argument to pandas.DataFrame.from_records. Returns: Class of pd.DataFrame. """
if isinstance(file_path_or_buffer, six.string_types): with open(file_path_or_buffer, 'rb') as f: return __file_to_dataframe(f, schema, **kwargs) else: return __file_to_dataframe(file_path_or_buffer, schema, **kwargs)
<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_avro(file_path_or_buffer, df, schema=None, codec='null', append=False): """ Avro file writer. Args: file_path_or_buffer: Output file path or file-like object. df: pd.DataFrame. schema: Dict of Avro schema. If it's set None, inferring schema. append: Boolean to control if will append to existing file codec: A string indicating the compression codec to use. Default is no compression ("null"), other acceptable values are "snappy" and "deflate". You must have python-snappy installed to use the snappy codec. """
if schema is None: schema = __schema_infer(df) open_mode = 'wb' if not append else 'a+b' if isinstance(file_path_or_buffer, six.string_types): with open(file_path_or_buffer, open_mode) as f: fastavro.writer(f, schema=schema, records=df.to_dict('records'), codec=codec) else: fastavro.writer(file_path_or_buffer, schema=schema, records=df.to_dict('records'), codec=codec)
<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, x, w=1): """ Update the t-digest with value x and weight w. """
self.n += w if len(self) == 0: self._add_centroid(Centroid(x, w)) return S = self._find_closest_centroids(x) while len(S) != 0 and w > 0: j = choice(list(range(len(S)))) c_j = S[j] q = self._compute_centroid_quantile(c_j) # This filters the out centroids that do not satisfy the second part # of the definition of S. See original paper by Dunning. if c_j.count + w > self._threshold(q): S.pop(j) continue delta_w = min(self._threshold(q) - c_j.count, w) self._update_centroid(c_j, x, delta_w) w -= delta_w S.pop(j) if w > 0: self._add_centroid(Centroid(x, w)) if len(self) > self.K / self.delta: self.compress() 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 batch_update(self, values, w=1): """ Update the t-digest with an iterable of values. This assumes all points have the same weight. """
for x in values: self.update(x, w) self.compress() 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 trimmed_mean(self, p1, p2): """ Computes the mean of the distribution between the two percentiles p1 and p2. This is a modified algorithm than the one presented in the original t-Digest paper. """
if not (p1 < p2): raise ValueError("p1 must be between 0 and 100 and less than p2.") min_count = p1 / 100. * self.n max_count = p2 / 100. * self.n trimmed_sum = trimmed_count = curr_count = 0 for i, c in enumerate(self.C.values()): next_count = curr_count + c.count if next_count <= min_count: curr_count = next_count continue count = c.count if curr_count < min_count: count = next_count - min_count if next_count > max_count: count -= next_count - max_count trimmed_sum += count * c.mean trimmed_count += count if next_count >= max_count: break curr_count = next_count if trimmed_count == 0: return 0 return trimmed_sum / trimmed_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 centroids_to_list(self): """ Returns a Python list of the TDigest object's Centroid values. """
centroids = [] for key in self.C.keys(): tree_values = self.C.get_value(key) centroids.append({'m':tree_values.mean, 'c':tree_values.count}) return centroids
<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_from_dict(self, dict_values): """ Updates TDigest object with dictionary values. The digest delta and K values are optional if you would like to update them, but the n value is not required because it is computed from the centroid weights. For example, you can initalize a new TDigest: digest = TDigest() Then load dictionary values into the digest: digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]}) Or update an existing digest where the centroids will be appropriately merged: digest = TDigest() digest.update(1) digest.update(2) digest.update(3) digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]}) Resulting in the digest having merged similar centroids by increasing their weight: {'K': 25, 'delta': 0.01, 'centroids': [{'c': 2.0, 'm': 1.0}, {'c': 2.0, 'm': 2.0}, {'c': 2.0, 'm': 3.0}], 'n': 6.0} Alternative you can provide only a list of centroid values with update_centroids_from_list() """
self.delta = dict_values.get('delta', self.delta) self.K = dict_values.get('K', self.K) self.update_centroids_from_list(dict_values['centroids']) return self
<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_centroids_from_list(self, list_values): """ Add or update Centroids from a Python list. Any existing centroids in the digest object are appropriately updated. Example: digest.update_centroids([{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]) """
[self.update(value['m'], value['c']) for value in list_values] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_undirected(matrix): """ Determine if the matrix reprensents a directed graph :param matrix: The matrix to tested :returns: boolean """
if isspmatrix(matrix): return sparse_allclose(matrix, matrix.transpose()) return np.allclose(matrix, matrix.T)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_adjacency_matrix(matrix): """ Converts transition matrix into adjacency matrix :param matrix: The matrix to be converted :returns: adjacency matrix """
for i in range(matrix.shape[0]): if isspmatrix(matrix): col = find(matrix[:,i])[2] else: col = matrix[:,i].T.tolist()[0] coeff = max( Fraction(c).limit_denominator().denominator for c in col ) matrix[:,i] *= coeff return matrix