code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _to_ascii(s): """ Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str: """ # TODO: Always use unicode within ambry. from six import text_type, binary_type if isinstance(s, text_type): ascii_ = s.encode('ascii', 'ignore') ...
Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str:
Below is the the instruction that describes the task: ### Input: Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str: ### Response: def _to_ascii(s): """ Converts given string to ascii ignoring non ascii. Args: s (text or binary): ...
def request_param_update(self, var_id): """Place a param update request on the queue""" self._useV2 = self.cf.platform.get_protocol_version() >= 4 pk = CRTPPacket() pk.set_header(CRTPPort.PARAM, READ_CHANNEL) if self._useV2: pk.data = struct.pack('<H', var_id) ...
Place a param update request on the queue
Below is the the instruction that describes the task: ### Input: Place a param update request on the queue ### Response: def request_param_update(self, var_id): """Place a param update request on the queue""" self._useV2 = self.cf.platform.get_protocol_version() >= 4 pk = CRTPPacket() ...
def remove_raw_jobs(self, params_list): """ Remove jobs from a raw queue with their raw params. """ if len(params_list) == 0: return # ZSET if self.is_sorted: context.connections.redis.zrem(self.redis_key, *iter(params_list)) # SET elif self.is_...
Remove jobs from a raw queue with their raw params.
Below is the the instruction that describes the task: ### Input: Remove jobs from a raw queue with their raw params. ### Response: def remove_raw_jobs(self, params_list): """ Remove jobs from a raw queue with their raw params. """ if len(params_list) == 0: return # ZSET ...
def find_rmlst_type(kma_report, rmlst_report): """ Uses a report generated by KMA to determine what allele is present for each rMLST gene. :param kma_report: The .res report generated by KMA. :param rmlst_report: rMLST report file to write information to. :return: a sorted list of loci present, in f...
Uses a report generated by KMA to determine what allele is present for each rMLST gene. :param kma_report: The .res report generated by KMA. :param rmlst_report: rMLST report file to write information to. :return: a sorted list of loci present, in format gene_allele
Below is the the instruction that describes the task: ### Input: Uses a report generated by KMA to determine what allele is present for each rMLST gene. :param kma_report: The .res report generated by KMA. :param rmlst_report: rMLST report file to write information to. :return: a sorted list of loci pre...
def populate_parallel_text(extract_dir: str, file_sets: List[Tuple[str, str, str]], dest_prefix: str, keep_separate: bool, head_n: int = 0): """ Create raw parallel train, dev, or test files with a given ...
Create raw parallel train, dev, or test files with a given prefix. :param extract_dir: Directory where raw files (inputs) are extracted. :param file_sets: Sets of files to use. :param dest_prefix: Prefix for output files. :param keep_separate: True if each file set (source-target pair) should have ...
Below is the the instruction that describes the task: ### Input: Create raw parallel train, dev, or test files with a given prefix. :param extract_dir: Directory where raw files (inputs) are extracted. :param file_sets: Sets of files to use. :param dest_prefix: Prefix for output files. :param keep_...
def _rdf2dot_simple(g, stream): """Create a simple graph of processes and artifacts.""" from itertools import chain import re path_re = re.compile( r'file:///(?P<type>[a-zA-Z]+)/' r'(?P<commit>\w+)' r'(?P<path>.+)?' ) inputs = g.query( """ SELECT ?input...
Create a simple graph of processes and artifacts.
Below is the the instruction that describes the task: ### Input: Create a simple graph of processes and artifacts. ### Response: def _rdf2dot_simple(g, stream): """Create a simple graph of processes and artifacts.""" from itertools import chain import re path_re = re.compile( r'file:///(?...
def cronitor(self): """Wrap run with requests to cronitor.""" url = f'https://cronitor.link/{self.opts.cronitor}/{{}}' try: run_url = url.format('run') self.logger.debug(f'Pinging {run_url}') requests.get(run_url, timeout=self.opts.timeout) except re...
Wrap run with requests to cronitor.
Below is the the instruction that describes the task: ### Input: Wrap run with requests to cronitor. ### Response: def cronitor(self): """Wrap run with requests to cronitor.""" url = f'https://cronitor.link/{self.opts.cronitor}/{{}}' try: run_url = url.format('run') ...
def create_vlan_interface(self, interface, subnet, **kwargs): """Create a vlan interface :param interface: Name of interface to be created. :type interface: str :param subnet: Subnet associated with interface to be created :type subnet: str :param \*\*kwargs: See the RES...
Create a vlan interface :param interface: Name of interface to be created. :type interface: str :param subnet: Subnet associated with interface to be created :type subnet: str :param \*\*kwargs: See the REST API Guide on your array for the documentatio...
Below is the the instruction that describes the task: ### Input: Create a vlan interface :param interface: Name of interface to be created. :type interface: str :param subnet: Subnet associated with interface to be created :type subnet: str :param \*\*kwargs: See the REST AP...
def synset(self): """Returns synset into which the given lemma belongs to. Returns ------- Synset Synset into which the given lemma belongs to. """ return synset('%s.%s.%s.%s'%(self.synset_literal,self.synset_pos,self.synset_sense,self.lite...
Returns synset into which the given lemma belongs to. Returns ------- Synset Synset into which the given lemma belongs to.
Below is the the instruction that describes the task: ### Input: Returns synset into which the given lemma belongs to. Returns ------- Synset Synset into which the given lemma belongs to. ### Response: def synset(self): """Returns synset into which the given lemma...
def write_render_callable(self, node, name, args, buffered, filtered, cached): """write a top-level render callable. this could be the main render() method or that of a top-level def.""" if self.in_def: decorator = node.decorator if decorator: ...
write a top-level render callable. this could be the main render() method or that of a top-level def.
Below is the the instruction that describes the task: ### Input: write a top-level render callable. this could be the main render() method or that of a top-level def. ### Response: def write_render_callable(self, node, name, args, buffered, filtered, cached): """write a top-level rende...
def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else ''
Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain>
Below is the the instruction that describes the task: ### Input: Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ### Response: def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: ...
def from_yamlfile(cls, fp, selector_handler=None, strict=False, debug=False): """ Create a Parselet instance from a file containing the Parsley script as a YAML object >>> import parslepy >>> with open('parselet.yml') as fp: ... parslepy.Parselet.from_yamlfile(fp) ...
Create a Parselet instance from a file containing the Parsley script as a YAML object >>> import parslepy >>> with open('parselet.yml') as fp: ... parslepy.Parselet.from_yamlfile(fp) ... <parslepy.base.Parselet object at 0x2014e50> :param file fp: an open fi...
Below is the the instruction that describes the task: ### Input: Create a Parselet instance from a file containing the Parsley script as a YAML object >>> import parslepy >>> with open('parselet.yml') as fp: ... parslepy.Parselet.from_yamlfile(fp) ... <parslepy.b...
def gfstep(time): """ Return the time step set by the most recent call to :func:`gfsstp`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstep_c.html :param time: Ignored ET value. :type time: float :return: Time step to take. :rtype: float """ time = ctypes.c_double(time...
Return the time step set by the most recent call to :func:`gfsstp`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstep_c.html :param time: Ignored ET value. :type time: float :return: Time step to take. :rtype: float
Below is the the instruction that describes the task: ### Input: Return the time step set by the most recent call to :func:`gfsstp`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstep_c.html :param time: Ignored ET value. :type time: float :return: Time step to take. :rtype: float ...
def to_json(self, depth=-1, **kwargs): """Returns a JSON representation of the object.""" return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs)
Returns a JSON representation of the object.
Below is the the instruction that describes the task: ### Input: Returns a JSON representation of the object. ### Response: def to_json(self, depth=-1, **kwargs): """Returns a JSON representation of the object.""" return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs)
def to_date(ts: float) -> datetime.date: """Convert timestamp to date. >>> to_date(978393600.0) datetime.date(2001, 1, 2) """ return datetime.datetime.fromtimestamp( ts, tz=datetime.timezone.utc).date()
Convert timestamp to date. >>> to_date(978393600.0) datetime.date(2001, 1, 2)
Below is the the instruction that describes the task: ### Input: Convert timestamp to date. >>> to_date(978393600.0) datetime.date(2001, 1, 2) ### Response: def to_date(ts: float) -> datetime.date: """Convert timestamp to date. >>> to_date(978393600.0) datetime.date(2001, 1, 2) """ re...
def get_ticker(self): """Return the latest ticker information. :return: Latest ticker information. :rtype: dict """ self._log('get ticker') return self._rest_client.get( endpoint='/ticker', params={'book': self.name} )
Return the latest ticker information. :return: Latest ticker information. :rtype: dict
Below is the the instruction that describes the task: ### Input: Return the latest ticker information. :return: Latest ticker information. :rtype: dict ### Response: def get_ticker(self): """Return the latest ticker information. :return: Latest ticker information. :rtype: ...
def addnot(self, action=None, subject=None, **conditions): """ Defines an ability which cannot be done. """ self.add_rule(Rule(False, action, subject, **conditions))
Defines an ability which cannot be done.
Below is the the instruction that describes the task: ### Input: Defines an ability which cannot be done. ### Response: def addnot(self, action=None, subject=None, **conditions): """ Defines an ability which cannot be done. """ self.add_rule(Rule(False, action, subject, **conditions...
def attribute_invoked(self, sender, name, args, kwargs): "Handles the creation of ExpectationBuilder when an attribute is invoked." return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__call__')(*args, **kwargs)
Handles the creation of ExpectationBuilder when an attribute is invoked.
Below is the the instruction that describes the task: ### Input: Handles the creation of ExpectationBuilder when an attribute is invoked. ### Response: def attribute_invoked(self, sender, name, args, kwargs): "Handles the creation of ExpectationBuilder when an attribute is invoked." return Expectat...
def createproject(self, name, **kwargs): """ Creates a new project owned by the authenticated user. :param name: new project name :param path: custom repository name for new project. By default generated based on name :param namespace_id: namespace for the new project (defaults ...
Creates a new project owned by the authenticated user. :param name: new project name :param path: custom repository name for new project. By default generated based on name :param namespace_id: namespace for the new project (defaults to user) :param description: short project descriptio...
Below is the the instruction that describes the task: ### Input: Creates a new project owned by the authenticated user. :param name: new project name :param path: custom repository name for new project. By default generated based on name :param namespace_id: namespace for the new project (d...
def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], passage_text: str, ...
Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use in a reading comprehension model. Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both ``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if both ``answer_text...
Below is the the instruction that describes the task: ### Input: Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use in a reading comprehension model. Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both ``TextFields``; and ``...
def transformSkyCoordinates(self, phi, theta): """ Converts sky coordinates from one reference system to another, making use of the rotation matrix with which the class was initialized. Inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- phi - V...
Converts sky coordinates from one reference system to another, making use of the rotation matrix with which the class was initialized. Inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- phi - Value of the azimuthal angle (right ascension, longitude) in radians...
Below is the the instruction that describes the task: ### Input: Converts sky coordinates from one reference system to another, making use of the rotation matrix with which the class was initialized. Inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- phi -...
def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx): """Merge all columns and place text string in widened cell.""" hdridxval = len(self.hdrs) - 1 worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt) return row_idx + 1
Merge all columns and place text string in widened cell.
Below is the the instruction that describes the task: ### Input: Merge all columns and place text string in widened cell. ### Response: def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx): """Merge all columns and place text string in widened cell.""" hdridxval = len(self.hdrs) - 1 w...
def give_dots_yield(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots without numpy using yield. ''' def x(theta): return (R-r) * math.cos(theta) + r_*math.cos((R-r) / r * theta) def y(theta): return (R-r) * math.sin(theta) - r_*math.sin((R-r) / r * theta) thet...
Generate Spirograph dots without numpy using yield.
Below is the the instruction that describes the task: ### Input: Generate Spirograph dots without numpy using yield. ### Response: def give_dots_yield(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots without numpy using yield. ''' def x(theta): return (R-r) * math.cos(thet...
def format_page(text): """Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string. """ width = max(map(len, text.splitlines())) page = "+-" + "-" * width + "-+\n" for line in...
Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string.
Below is the the instruction that describes the task: ### Input: Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string. ### Response: def format_page(text): """Format the text for output ...
def categorytree(self, category, depth=5): """ Generate the Category Tree for the given categories Args: category(str or list of strings): Category name(s) depth(int): Depth to traverse the tree Returns: dict: Category tree structure ...
Generate the Category Tree for the given categories Args: category(str or list of strings): Category name(s) depth(int): Depth to traverse the tree Returns: dict: Category tree structure Note: Set depth to **None** to g...
Below is the the instruction that describes the task: ### Input: Generate the Category Tree for the given categories Args: category(str or list of strings): Category name(s) depth(int): Depth to traverse the tree Returns: dict: Category tree s...
def _add_session(self, session, start_info, groups_by_name): """Adds a new Session protobuffer to the 'groups_by_name' dictionary. Called by _build_session_groups when we encounter a new session. Creates the Session protobuffer and adds it to the relevant group in the 'groups_by_name' dict. Creates the...
Adds a new Session protobuffer to the 'groups_by_name' dictionary. Called by _build_session_groups when we encounter a new session. Creates the Session protobuffer and adds it to the relevant group in the 'groups_by_name' dict. Creates the session group if this is the first time we encounter it. A...
Below is the the instruction that describes the task: ### Input: Adds a new Session protobuffer to the 'groups_by_name' dictionary. Called by _build_session_groups when we encounter a new session. Creates the Session protobuffer and adds it to the relevant group in the 'groups_by_name' dict. Creates th...
def check_syntax(self, cmd, line): """Syntax check a line of RiveScript code. Args: str cmd: The command symbol for the line of code, such as one of ``+``, ``-``, ``*``, ``>``, etc. str line: The remainder of the line of code, such as the text of ...
Syntax check a line of RiveScript code. Args: str cmd: The command symbol for the line of code, such as one of ``+``, ``-``, ``*``, ``>``, etc. str line: The remainder of the line of code, such as the text of a trigger or reply. Return: ...
Below is the the instruction that describes the task: ### Input: Syntax check a line of RiveScript code. Args: str cmd: The command symbol for the line of code, such as one of ``+``, ``-``, ``*``, ``>``, etc. str line: The remainder of the line of code, such as the t...
def cache_backend(self): """ Get the cache backend Returns ~~~~~~~ Django cache backend """ if not hasattr(self, '_cache_backend'): if hasattr(django.core.cache, 'caches'): self._cache_backend = django.core.cache.caches[_cache_name] ...
Get the cache backend Returns ~~~~~~~ Django cache backend
Below is the the instruction that describes the task: ### Input: Get the cache backend Returns ~~~~~~~ Django cache backend ### Response: def cache_backend(self): """ Get the cache backend Returns ~~~~~~~ Django cache backend """ if...
def download(name, options): """ download a file or all files in a directory """ dire = os.path.dirname(name) # returns the directory name fName = os.path.basename(name) # returns the filename fNameOnly, fExt = os.path.splitext(fName) dwn = 0 if fileExists(fName, dire) and not fileExis...
download a file or all files in a directory
Below is the the instruction that describes the task: ### Input: download a file or all files in a directory ### Response: def download(name, options): """ download a file or all files in a directory """ dire = os.path.dirname(name) # returns the directory name fName = os.path.basename(name) # ...
def references(self, key, value): """Populate the ``references`` key.""" def _has_curator_flag(value): normalized_nine_values = [el.upper() for el in force_list(value.get('9'))] return 'CURATOR' in normalized_nine_values def _is_curated(value): return force_single_element(value.get(...
Populate the ``references`` key.
Below is the the instruction that describes the task: ### Input: Populate the ``references`` key. ### Response: def references(self, key, value): """Populate the ``references`` key.""" def _has_curator_flag(value): normalized_nine_values = [el.upper() for el in force_list(value.get('9'))] r...
def check_tcp(helper, host, port, warning_param, critical_param, session): """ the check logic for check TCP ports """ # from tcpConnState from TCP-MIB tcp_translate = { "1" : "closed", "2" : "listen", "3" : "synSent", "4" : "synReceived", "5" : "established",...
the check logic for check TCP ports
Below is the the instruction that describes the task: ### Input: the check logic for check TCP ports ### Response: def check_tcp(helper, host, port, warning_param, critical_param, session): """ the check logic for check TCP ports """ # from tcpConnState from TCP-MIB tcp_translate = { ...
def pass_actualremoterelease_v1(self): """Update the outlet link sequence |dam_outlets.S|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.s[0] += flu.actualremoterelease
Update the outlet link sequence |dam_outlets.S|.
Below is the the instruction that describes the task: ### Input: Update the outlet link sequence |dam_outlets.S|. ### Response: def pass_actualremoterelease_v1(self): """Update the outlet link sequence |dam_outlets.S|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess ...
def _wake_up_timer(self, kill_event): """Internal. This is the function that the thread will execute. waits on an event so that the thread can make a quick exit when close() is called Args: - kill_event (threading.Event) : Event to wait on """ while True: ...
Internal. This is the function that the thread will execute. waits on an event so that the thread can make a quick exit when close() is called Args: - kill_event (threading.Event) : Event to wait on
Below is the the instruction that describes the task: ### Input: Internal. This is the function that the thread will execute. waits on an event so that the thread can make a quick exit when close() is called Args: - kill_event (threading.Event) : Event to wait on ### Response: def _wak...
def expand_variables_to_segments(v, Nt): ''' expands contextual variables v, by repeating each instance as specified in Nt ''' N_v = len(np.atleast_1d(v[0])) return np.concatenate([np.full((Nt[i], N_v), v[i]) for i in np.arange(len(v))])
expands contextual variables v, by repeating each instance as specified in Nt
Below is the the instruction that describes the task: ### Input: expands contextual variables v, by repeating each instance as specified in Nt ### Response: def expand_variables_to_segments(v, Nt): ''' expands contextual variables v, by repeating each instance as specified in Nt ''' N_v = len(np.atleast_1d...
def rpcexec(self, payload): """ Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises Unauthoriz...
Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized ...
Below is the the instruction that describes the task: ### Input: Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made ...
def email_message( self, recipient, # type: Text subject_template, # type: Text body_template, # type: Text sender=None, # type: Optional[AbstractUser] message_class=EmailMessage, **kwargs ): """ Returns an invitation email message. This ca...
Returns an invitation email message. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent.
Below is the the instruction that describes the task: ### Input: Returns an invitation email message. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent. ### Response: def email_message( self, ...
def shutdown(self, payload=None): """ Close the connection/shutdown the messaging loop. :param payload: None: not used. Here to allow using this method with add_command. """ logging.info("Work queue shutdown.") self.connection.close() self.receiving_messages = Fal...
Close the connection/shutdown the messaging loop. :param payload: None: not used. Here to allow using this method with add_command.
Below is the the instruction that describes the task: ### Input: Close the connection/shutdown the messaging loop. :param payload: None: not used. Here to allow using this method with add_command. ### Response: def shutdown(self, payload=None): """ Close the connection/shutdown the messagin...
def tacacs_server_tacacs_source_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") tacacs_server = ET.SubElement(config, "tacacs-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") tacacs_source_ip = ET.SubElement(tacacs_server, "tacacs-source-ip") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def tacacs_server_tacacs_source_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") tacacs_server = ET.SubElement(config, "tacacs-server", xmlns="urn:brocade.c...
def print_help(self, *args, **kwargs): """ Add pager support to help output. """ if self._command is not None and self._command.session.allow_pager: desc = 'Help\: %s' % '-'.join(self.prog.split()) pager_kwargs = self._command.get_pager_spec() with paging.pager_redire...
Add pager support to help output.
Below is the the instruction that describes the task: ### Input: Add pager support to help output. ### Response: def print_help(self, *args, **kwargs): """ Add pager support to help output. """ if self._command is not None and self._command.session.allow_pager: desc = 'Help\: %s' % '-'....
def to_type(upcast_type, varlist): """Loop over all elements of varlist and convert them to upcasttype. Parameters ---------- upcast_type : data type e.g. complex, float64 or complex128 varlist : list list may contain arrays, mat's, sparse matrices, or scalars the elements m...
Loop over all elements of varlist and convert them to upcasttype. Parameters ---------- upcast_type : data type e.g. complex, float64 or complex128 varlist : list list may contain arrays, mat's, sparse matrices, or scalars the elements may be float, int or complex Returns ...
Below is the the instruction that describes the task: ### Input: Loop over all elements of varlist and convert them to upcasttype. Parameters ---------- upcast_type : data type e.g. complex, float64 or complex128 varlist : list list may contain arrays, mat's, sparse matrices, or sca...
def _turn_sigterm_into_systemexit(): # pragma: no cover """ Attempts to turn a SIGTERM exception into a SystemExit exception. """ try: import signal except ImportError: return def handle_term(signo, frame): raise SystemExit signal.signal(signal.SIGTERM, handle_term)
Attempts to turn a SIGTERM exception into a SystemExit exception.
Below is the the instruction that describes the task: ### Input: Attempts to turn a SIGTERM exception into a SystemExit exception. ### Response: def _turn_sigterm_into_systemexit(): # pragma: no cover """ Attempts to turn a SIGTERM exception into a SystemExit exception. """ try: import sign...
def generate_model_file(filename, project, model, fields): """Creates a webpage for a given instance of a model.""" for field in fields: field.type = field.__class__.__name__ content = open(os.path.join(os.path.dirname(__file__), 'templates/model_page.html'), 'r').read() engine = StatikTemplat...
Creates a webpage for a given instance of a model.
Below is the the instruction that describes the task: ### Input: Creates a webpage for a given instance of a model. ### Response: def generate_model_file(filename, project, model, fields): """Creates a webpage for a given instance of a model.""" for field in fields: field.type = field.__class__.__n...
def _update_index(self, axis, key, value): """Update the current axis index based on a given key or value This is an internal method designed to set the origin or step for an index, whilst updating existing Index arrays as appropriate Examples -------- >>> self._update_...
Update the current axis index based on a given key or value This is an internal method designed to set the origin or step for an index, whilst updating existing Index arrays as appropriate Examples -------- >>> self._update_index("x0", 0) >>> self._update_index("dx", 0)...
Below is the the instruction that describes the task: ### Input: Update the current axis index based on a given key or value This is an internal method designed to set the origin or step for an index, whilst updating existing Index arrays as appropriate Examples -------- >>...
def _deserialization_helper(self, state, ray_forking): """This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. ray_forking: True if this is being called because Ray is forking the actor handle and false if it is b...
This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. ray_forking: True if this is being called because Ray is forking the actor handle and false if it is being called by pickling.
Below is the the instruction that describes the task: ### Input: This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. ray_forking: True if this is being called because Ray is forking the actor handle and false if it i...
def _write_apt_gpg_keyfile(key_name, key_material): """Writes GPG key material into a file at a provided path. :param key_name: A key name to use for a key file (could be a fingerprint) :type key_name: str :param key_material: A GPG key material (binary) :type key_material: (str, bytes) """ ...
Writes GPG key material into a file at a provided path. :param key_name: A key name to use for a key file (could be a fingerprint) :type key_name: str :param key_material: A GPG key material (binary) :type key_material: (str, bytes)
Below is the the instruction that describes the task: ### Input: Writes GPG key material into a file at a provided path. :param key_name: A key name to use for a key file (could be a fingerprint) :type key_name: str :param key_material: A GPG key material (binary) :type key_material: (str, bytes) #...
def get_snpeff_info(snpeff_string, snpeff_header): """Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcript. ...
Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcript. Args: snpeff_string (string): A string with...
Below is the the instruction that describes the task: ### Input: Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcr...
def getLocalDatetime(date, time, tz=None, timeDefault=dt.time.max): """ Get a datetime in the local timezone from date and optionally time """ localTZ = timezone.get_current_timezone() if tz is None or tz == localTZ: localDt = getAwareDatetime(date, time, tz, timeDefault) else: #...
Get a datetime in the local timezone from date and optionally time
Below is the the instruction that describes the task: ### Input: Get a datetime in the local timezone from date and optionally time ### Response: def getLocalDatetime(date, time, tz=None, timeDefault=dt.time.max): """ Get a datetime in the local timezone from date and optionally time """ localTZ = ...
def generate_doc(self, language_predicate, create_jvmdoc_command): """ Generate an execute method given a language predicate and command to create documentation language_predicate: a function that accepts a target and returns True if the target is of that language create_jvmdoc_...
Generate an execute method given a language predicate and command to create documentation language_predicate: a function that accepts a target and returns True if the target is of that language create_jvmdoc_command: (classpath, directory, *targets) -> command (string) that will generat...
Below is the the instruction that describes the task: ### Input: Generate an execute method given a language predicate and command to create documentation language_predicate: a function that accepts a target and returns True if the target is of that language create_jvmdoc_command: (...
def filter(self, func): """Returns a packet list filtered by a truth function""" return self.__class__(list(filter(func,self.res)), name="filtered %s"%self.listname)
Returns a packet list filtered by a truth function
Below is the the instruction that describes the task: ### Input: Returns a packet list filtered by a truth function ### Response: def filter(self, func): """Returns a packet list filtered by a truth function""" return self.__class__(list(filter(func,self.res)), name="f...
def save_dot(self, fd): """ Saves a representation of the case in the Graphviz DOT language. """ from pylon.io import DotWriter DotWriter(self).write(fd)
Saves a representation of the case in the Graphviz DOT language.
Below is the the instruction that describes the task: ### Input: Saves a representation of the case in the Graphviz DOT language. ### Response: def save_dot(self, fd): """ Saves a representation of the case in the Graphviz DOT language. """ from pylon.io import DotWriter DotWriter(s...
def end_tag(self, alt=None): """Return XML end tag for the receiver.""" if alt: name = alt else: name = self.name return "</" + name + ">"
Return XML end tag for the receiver.
Below is the the instruction that describes the task: ### Input: Return XML end tag for the receiver. ### Response: def end_tag(self, alt=None): """Return XML end tag for the receiver.""" if alt: name = alt else: name = self.name return "</" + name + ">"
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Execute queries against SQLite3, merge and return as a dict ''' return SQLite3ExtPillar().fetch(minion_id, pillar, *args, **kwargs)
Execute queries against SQLite3, merge and return as a dict
Below is the the instruction that describes the task: ### Input: Execute queries against SQLite3, merge and return as a dict ### Response: def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Execute queries against SQLite3, merge and return as a dict '''...
def change_email(self, email): """ Change user's login email :param user: AuthUser :param email: :return: """ def cb(): if not utils.is_email_valid(email): raise exceptions.AuthError("Email address invalid") self.user.chang...
Change user's login email :param user: AuthUser :param email: :return:
Below is the the instruction that describes the task: ### Input: Change user's login email :param user: AuthUser :param email: :return: ### Response: def change_email(self, email): """ Change user's login email :param user: AuthUser :param email: :ret...
def _validate(self): """Validate the JPEG 2000 outermost superbox. These checks must be done at a file level. """ # A JP2 file must contain certain boxes. The 2nd box must be a file # type box. if not isinstance(self.box[1], FileTypeBox): msg = "{filename} d...
Validate the JPEG 2000 outermost superbox. These checks must be done at a file level.
Below is the the instruction that describes the task: ### Input: Validate the JPEG 2000 outermost superbox. These checks must be done at a file level. ### Response: def _validate(self): """Validate the JPEG 2000 outermost superbox. These checks must be done at a file level. """ ...
def find_elements(self): """ Returns: Element (list): all the elements """ es = [] for element_id in self.find_element_ids(): e = Element(self.http.new_client(''), element_id) es.append(e) return es
Returns: Element (list): all the elements
Below is the the instruction that describes the task: ### Input: Returns: Element (list): all the elements ### Response: def find_elements(self): """ Returns: Element (list): all the elements """ es = [] for element_id in self.find_element_ids(): ...
def save(self, **kwargs): "Override save() to construct tree_path based on the category's parent." old_tree_path = self.tree_path if self.tree_parent: if self.tree_parent.tree_path: self.tree_path = '%s/%s' % (self.tree_parent.tree_path, self.slug) else: ...
Override save() to construct tree_path based on the category's parent.
Below is the the instruction that describes the task: ### Input: Override save() to construct tree_path based on the category's parent. ### Response: def save(self, **kwargs): "Override save() to construct tree_path based on the category's parent." old_tree_path = self.tree_path if self.tre...
def get_height(self, points, only_in = True, edge=True, full=False): """ Given a set of points, it computes the z value for the parametric equation of the plane where the polygon belongs. Only the two first columns of the points will be taken into account as x and y. ...
Given a set of points, it computes the z value for the parametric equation of the plane where the polygon belongs. Only the two first columns of the points will be taken into account as x and y. By default, the points outside the object will have a NaN value ...
Below is the the instruction that describes the task: ### Input: Given a set of points, it computes the z value for the parametric equation of the plane where the polygon belongs. Only the two first columns of the points will be taken into account as x and y. By d...
def _association_types(self): """Retrieve Custom Indicator Associations types from the ThreatConnect API.""" # Dynamically create custom indicator class r = self.session.get('/v2/types/associationTypes') # check for bad status code and response that is not JSON if not r.ok or 'a...
Retrieve Custom Indicator Associations types from the ThreatConnect API.
Below is the the instruction that describes the task: ### Input: Retrieve Custom Indicator Associations types from the ThreatConnect API. ### Response: def _association_types(self): """Retrieve Custom Indicator Associations types from the ThreatConnect API.""" # Dynamically create custom indicator ...
def is_valid_lval(t): """Checks whether t is valid JS identifier name (no keyword like var, function, if etc) Also returns false on internal""" if not is_internal(t) and is_lval(t) and t not in RESERVED_NAMES: return True return False
Checks whether t is valid JS identifier name (no keyword like var, function, if etc) Also returns false on internal
Below is the the instruction that describes the task: ### Input: Checks whether t is valid JS identifier name (no keyword like var, function, if etc) Also returns false on internal ### Response: def is_valid_lval(t): """Checks whether t is valid JS identifier name (no keyword like var, function, if etc) ...
def keys(self, history=None): """ Get the set of I{all} property names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of property names. @rtype: list """ if history is N...
Get the set of I{all} property names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of property names. @rtype: list
Below is the the instruction that describes the task: ### Input: Get the set of I{all} property names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of property names. @rtype: list ### Response: d...
def add_to_ptr_size(self, ptr_size): # type: (int) -> bool ''' Add the space for a path table record to the volume descriptor. Parameters: ptr_size - The length of the Path Table Record being added to this Volume Descriptor. Returns: True if extents need to be ...
Add the space for a path table record to the volume descriptor. Parameters: ptr_size - The length of the Path Table Record being added to this Volume Descriptor. Returns: True if extents need to be added to the Volume Descriptor, False otherwise.
Below is the the instruction that describes the task: ### Input: Add the space for a path table record to the volume descriptor. Parameters: ptr_size - The length of the Path Table Record being added to this Volume Descriptor. Returns: True if extents need to be added to the Volum...
def paginate_search_results(object_class, search_results, page_size, page): """ Takes edx-search results and returns a Page object populated with db objects for that page. :param object_class: Model class to use when querying the db for objects. :param search_results: edX-search results. :param...
Takes edx-search results and returns a Page object populated with db objects for that page. :param object_class: Model class to use when querying the db for objects. :param search_results: edX-search results. :param page_size: Number of results per page. :param page: Page number. :return: Pagin...
Below is the the instruction that describes the task: ### Input: Takes edx-search results and returns a Page object populated with db objects for that page. :param object_class: Model class to use when querying the db for objects. :param search_results: edX-search results. :param page_size: Number ...
def register_access_db(fullfilename: str, dsn: str, description: str) -> bool: """ (Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database...
(Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
Below is the the instruction that describes the task: ### Input: (Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database Returns: ...
def distinct(): """ Validates that all items in the given field list value are distinct, i.e. that the list contains no duplicates. """ def validate(value): for i, item in enumerate(value): if item in value[i+1:]: return e("{} is not a distinct set of values", val...
Validates that all items in the given field list value are distinct, i.e. that the list contains no duplicates.
Below is the the instruction that describes the task: ### Input: Validates that all items in the given field list value are distinct, i.e. that the list contains no duplicates. ### Response: def distinct(): """ Validates that all items in the given field list value are distinct, i.e. that the list ...
def oauth_register(form): """Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance. """ if form.validate(): data = form.to_dict() if not data.get('password'): data['password'] = '' user = register_user...
Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance.
Below is the the instruction that describes the task: ### Input: Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance. ### Response: def oauth_register(form): """Register user if possible. :param form: A form instance. :returns: A...
def _make_get_request(self, uri, parameters=None, timeout=None): """ Given a request add in the required parameters and return the parsed XML object. """ if not timeout: timeout = self.timeout return self._make_request(requests.get, uri, params=parameters, tim...
Given a request add in the required parameters and return the parsed XML object.
Below is the the instruction that describes the task: ### Input: Given a request add in the required parameters and return the parsed XML object. ### Response: def _make_get_request(self, uri, parameters=None, timeout=None): """ Given a request add in the required parameters and return the ...
def delete_snapshot(snapshots_ids=None, config="root"): ''' Deletes an snapshot config Configuration name. (Default: root) snapshots_ids List of the snapshots IDs to be deleted. CLI example: .. code-block:: bash salt '*' snapper.delete_snapshot 54 salt '*' sn...
Deletes an snapshot config Configuration name. (Default: root) snapshots_ids List of the snapshots IDs to be deleted. CLI example: .. code-block:: bash salt '*' snapper.delete_snapshot 54 salt '*' snapper.delete_snapshot config=root 54 salt '*' snapper.delete...
Below is the the instruction that describes the task: ### Input: Deletes an snapshot config Configuration name. (Default: root) snapshots_ids List of the snapshots IDs to be deleted. CLI example: .. code-block:: bash salt '*' snapper.delete_snapshot 54 salt '*' s...
def _check_fpos(self, fp_, fpos, offset, block): """Check file position matches blocksize""" if (fp_.tell() + offset != fpos): warnings.warn("Actual "+block+" header size does not match expected") return
Check file position matches blocksize
Below is the the instruction that describes the task: ### Input: Check file position matches blocksize ### Response: def _check_fpos(self, fp_, fpos, offset, block): """Check file position matches blocksize""" if (fp_.tell() + offset != fpos): warnings.warn("Actual "+block+" header size...
def _mainthread_poll_readable(self): """Searches for readable client sockets. These sockets are then put in a subthread to be handled by _handle_readable """ events = self._recv_selector.select(self.block_time) for key, mask in events: if mask == selectors.EVENT_READ:...
Searches for readable client sockets. These sockets are then put in a subthread to be handled by _handle_readable
Below is the the instruction that describes the task: ### Input: Searches for readable client sockets. These sockets are then put in a subthread to be handled by _handle_readable ### Response: def _mainthread_poll_readable(self): """Searches for readable client sockets. These sockets are then put i...
def add_signal(self, signal): """Adds "input" signal to connected signals. Internally connects the signal to a control slot.""" self.__signals.append(signal) if self.__connected: # Connects signal if the current state is "connected" self.__connect_signal(sig...
Adds "input" signal to connected signals. Internally connects the signal to a control slot.
Below is the the instruction that describes the task: ### Input: Adds "input" signal to connected signals. Internally connects the signal to a control slot. ### Response: def add_signal(self, signal): """Adds "input" signal to connected signals. Internally connects the signal to a contro...
def readline( file, skip_blank=False ): """Read a line from provided file, skipping any blank or comment lines""" while 1: line = file.readline() #print "every line: %r" % line if not line: return None if line[0] != '#' and not ( skip_blank and line.isspace() ): retu...
Read a line from provided file, skipping any blank or comment lines
Below is the the instruction that describes the task: ### Input: Read a line from provided file, skipping any blank or comment lines ### Response: def readline( file, skip_blank=False ): """Read a line from provided file, skipping any blank or comment lines""" while 1: line = file.readline() ...
def simBirth(self,which_agents): ''' Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period, as well as initializing the perception of aggregate productivity for each Markov state. The representative age...
Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period, as well as initializing the perception of aggregate productivity for each Markov state. The representative agent begins with the correct perception of the ...
Below is the the instruction that describes the task: ### Input: Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period, as well as initializing the perception of aggregate productivity for each Markov state. The re...
def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value ...
Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'.
Below is the the instruction that describes the task: ### Input: Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ### Response: def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command ...
def settzinfo(self, tzinfo, start=2000, end=2030): """ Create appropriate objects in self to represent tzinfo. Collapse DST transitions to rrules as much as possible. Assumptions: - DST <-> Standard transitions occur on the hour - never within a month of one another ...
Create appropriate objects in self to represent tzinfo. Collapse DST transitions to rrules as much as possible. Assumptions: - DST <-> Standard transitions occur on the hour - never within a month of one another - twice or fewer times a year - never in the month of Dece...
Below is the the instruction that describes the task: ### Input: Create appropriate objects in self to represent tzinfo. Collapse DST transitions to rrules as much as possible. Assumptions: - DST <-> Standard transitions occur on the hour - never within a month of one another ...
def addMember(self, imagePtr=None): """ Combines the input image with the static mask that has the same signature. Parameters ---------- imagePtr : object An imageObject reference Notes ----- The signature parameter consists of the tu...
Combines the input image with the static mask that has the same signature. Parameters ---------- imagePtr : object An imageObject reference Notes ----- The signature parameter consists of the tuple:: (instrument/detector, (nx,ny), chip_i...
Below is the the instruction that describes the task: ### Input: Combines the input image with the static mask that has the same signature. Parameters ---------- imagePtr : object An imageObject reference Notes ----- The signature parameter consi...
def get_authors(self, language): """ Return the list of this task's authors """ return self.gettext(language, self._author) if self._author else ""
Return the list of this task's authors
Below is the the instruction that describes the task: ### Input: Return the list of this task's authors ### Response: def get_authors(self, language): """ Return the list of this task's authors """ return self.gettext(language, self._author) if self._author else ""
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Stop CPC (requires DPM mode).""" assert wait_for_completion is True # async not supported yet cpc_oid = uri_parms[0] try: cpc = hmc.cpcs.lookup_by_oid(cpc_oid) ...
Operation: Stop CPC (requires DPM mode).
Below is the the instruction that describes the task: ### Input: Operation: Stop CPC (requires DPM mode). ### Response: def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Stop CPC (requires DPM mode).""" assert wait_for_completion is True #...
def decode_text(s): """Decodes a PDFDocEncoding string to Unicode.""" if s.startswith(b'\xfe\xff'): return unicode(s[2:], 'utf-16be', 'ignore') else: return ''.join(PDFDocEncoding[ord(c)] for c in s)
Decodes a PDFDocEncoding string to Unicode.
Below is the the instruction that describes the task: ### Input: Decodes a PDFDocEncoding string to Unicode. ### Response: def decode_text(s): """Decodes a PDFDocEncoding string to Unicode.""" if s.startswith(b'\xfe\xff'): return unicode(s[2:], 'utf-16be', 'ignore') else: return ''.join...
def nonFinalisedReqs(self, reqKeys: List[Tuple[str, int]]): """ Check if there are any requests which are not finalised, i.e for which there are not enough PROPAGATEs """ return {key for key in reqKeys if not self.requests.is_finalised(key)}
Check if there are any requests which are not finalised, i.e for which there are not enough PROPAGATEs
Below is the the instruction that describes the task: ### Input: Check if there are any requests which are not finalised, i.e for which there are not enough PROPAGATEs ### Response: def nonFinalisedReqs(self, reqKeys: List[Tuple[str, int]]): """ Check if there are any requests which are not...
def _get_deployment_instance_summary(awsclient, deployment_id, instance_id): """instance summary. :param awsclient: :param deployment_id: :param instance_id: return: status, last_event """ client_codedeploy = awsclient.get_client('codedeploy') request = { 'deploymentId': deploym...
instance summary. :param awsclient: :param deployment_id: :param instance_id: return: status, last_event
Below is the the instruction that describes the task: ### Input: instance summary. :param awsclient: :param deployment_id: :param instance_id: return: status, last_event ### Response: def _get_deployment_instance_summary(awsclient, deployment_id, instance_id): """instance summary. :param ...
def get_possible_initializer_keys(cls, num_layers): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed fr...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed from 0) whL: weight for prev state -> H gate for layer ...
Below is the the instruction that describes the task: ### Input: Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (...
def get_article_placeholders(self, article): """ In the project settings set up the variable CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = { 'include': [ 'slot1', 'slot2', etc. ], 'exclude': [ 'slot3', 'slot4', etc. ], } or leave it empty CMS_ARTICLES...
In the project settings set up the variable CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = { 'include': [ 'slot1', 'slot2', etc. ], 'exclude': [ 'slot3', 'slot4', etc. ], } or leave it empty CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {}
Below is the the instruction that describes the task: ### Input: In the project settings set up the variable CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = { 'include': [ 'slot1', 'slot2', etc. ], 'exclude': [ 'slot3', 'slot4', etc. ], } or leave it empty CMS_ARTI...
def bandpass_filter(rate=None, low=None, high=None, order=None): """Butterworth bandpass filter.""" assert low < high assert order >= 1 return signal.butter(order, (low / (rate / 2.), high / (rate / 2.)), 'pass')
Butterworth bandpass filter.
Below is the the instruction that describes the task: ### Input: Butterworth bandpass filter. ### Response: def bandpass_filter(rate=None, low=None, high=None, order=None): """Butterworth bandpass filter.""" assert low < high assert order >= 1 return signal.butter(order, (l...
def include(self, target): """ Determine if a given value is included in the array or object using `is`. """ if self._clean.isDict(): return self._wrap(target in self.obj.values()) else: return self._wrap(target in self.obj)
Determine if a given value is included in the array or object using `is`.
Below is the the instruction that describes the task: ### Input: Determine if a given value is included in the array or object using `is`. ### Response: def include(self, target): """ Determine if a given value is included in the array or object using `is`. """ if se...
def result(i): """ Returns which 8-bit registers are used by an asm instruction to return a result. """ ins = inst(i) op = oper(i) if ins in ('or', 'and') and op == ['a']: return ['f'] if ins in {'xor', 'or', 'and', 'neg', 'cpl', 'daa', 'rld', 'rrd', 'rra', 'rla', 'rrca', 'rlca'}: ...
Returns which 8-bit registers are used by an asm instruction to return a result.
Below is the the instruction that describes the task: ### Input: Returns which 8-bit registers are used by an asm instruction to return a result. ### Response: def result(i): """ Returns which 8-bit registers are used by an asm instruction to return a result. """ ins = inst(i) op = oper(i) ...
def datetime_to_jd(date): """ Convert a `datetime.datetime` object to Julian Day. Parameters ---------- date : `datetime.datetime` instance Returns ------- jd : float Julian day. Examples -------- >>> d = datetime.datetime(1985,2,17,6) >>> d datetime.date...
Convert a `datetime.datetime` object to Julian Day. Parameters ---------- date : `datetime.datetime` instance Returns ------- jd : float Julian day. Examples -------- >>> d = datetime.datetime(1985,2,17,6) >>> d datetime.datetime(1985, 2, 17, 6, 0) >>> jdutil...
Below is the the instruction that describes the task: ### Input: Convert a `datetime.datetime` object to Julian Day. Parameters ---------- date : `datetime.datetime` instance Returns ------- jd : float Julian day. Examples -------- >>> d = datetime.datetime(1985,2,17,6...
def protect_libraries_from_patching(): """ In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patchi...
In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patching by external libraries (e.g. gevent).
Below is the the instruction that describes the task: ### Input: In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protec...
def epilog(self): """Return text formatted for the usage description's epilog.""" bold = '\033[1m' end = '\033[0m' available = self.available.copy() index = available.index(Config.DOWNLOADER_DEFAULT) available[index] = bold + '(' + available[index] + ')' + end fo...
Return text formatted for the usage description's epilog.
Below is the the instruction that describes the task: ### Input: Return text formatted for the usage description's epilog. ### Response: def epilog(self): """Return text formatted for the usage description's epilog.""" bold = '\033[1m' end = '\033[0m' available = self.available.cop...
def _ExtractWithFilter( self, source_path_specs, destination_path, output_writer, artifact_filters, filter_file, artifact_definitions_path, custom_artifacts_path, skip_duplicates=True): """Extracts files using a filter expression. This method runs the file extraction process on the image and ...
Extracts files using a filter expression. This method runs the file extraction process on the image and potentially on every VSS if that is wanted. Args: source_path_specs (list[dfvfs.PathSpec]): path specifications to extract. destination_path (str): path where the extracted files should be s...
Below is the the instruction that describes the task: ### Input: Extracts files using a filter expression. This method runs the file extraction process on the image and potentially on every VSS if that is wanted. Args: source_path_specs (list[dfvfs.PathSpec]): path specifications to extract. ...
def has_source_contents(self, src_id): """Checks if some sources exist.""" return bool(rustcall(_lib.lsm_view_has_source_contents, self._get_ptr(), src_id))
Checks if some sources exist.
Below is the the instruction that describes the task: ### Input: Checks if some sources exist. ### Response: def has_source_contents(self, src_id): """Checks if some sources exist.""" return bool(rustcall(_lib.lsm_view_has_source_contents, self._get_ptr(), src_id))
def looking_for(self): """Copy looking for attributes from the source profile to the destination profile. """ looking_for = self.source_profile.looking_for return self.dest_user.profile.looking_for.update( gentation=looking_for.gentation, single=looking_fo...
Copy looking for attributes from the source profile to the destination profile.
Below is the the instruction that describes the task: ### Input: Copy looking for attributes from the source profile to the destination profile. ### Response: def looking_for(self): """Copy looking for attributes from the source profile to the destination profile. """ lookin...
def create_table(self, table_name, obj=None, **kwargs): """ Dispatch to ImpalaClient.create_table. See that function's docstring for more """ return self.client.create_table( table_name, obj=obj, database=self.name, **kwargs )
Dispatch to ImpalaClient.create_table. See that function's docstring for more
Below is the the instruction that describes the task: ### Input: Dispatch to ImpalaClient.create_table. See that function's docstring for more ### Response: def create_table(self, table_name, obj=None, **kwargs): """ Dispatch to ImpalaClient.create_table. See that function's docstring ...
def padStr(s, field=None): """ Pad the begining of a string with spaces, if necessary. """ if field is None: return s else: if len(s) >= field: return s else: return " " * (field - len(s)) + s
Pad the begining of a string with spaces, if necessary.
Below is the the instruction that describes the task: ### Input: Pad the begining of a string with spaces, if necessary. ### Response: def padStr(s, field=None): """ Pad the begining of a string with spaces, if necessary. """ if field is None: return s else: if len(s) >= field: ...
def __doQuery(self, query, format, convert): """ Inner method that does the actual query """ self.__getFormat(format) self.sparql.setQuery(query) if convert: results = self.sparql.query().convert() else: results = self.sparql.query() return results
Inner method that does the actual query
Below is the the instruction that describes the task: ### Input: Inner method that does the actual query ### Response: def __doQuery(self, query, format, convert): """ Inner method that does the actual query """ self.__getFormat(format) self.sparql.setQuery(query) if convert: results = self.sparql.q...
async def _receive_sack_chunk(self, chunk): """ Handle a SACK chunk. """ if uint32_gt(self._last_sacked_tsn, chunk.cumulative_tsn): return received_time = time.time() self._last_sacked_tsn = chunk.cumulative_tsn cwnd_fully_utilized = (self._flight_siz...
Handle a SACK chunk.
Below is the the instruction that describes the task: ### Input: Handle a SACK chunk. ### Response: async def _receive_sack_chunk(self, chunk): """ Handle a SACK chunk. """ if uint32_gt(self._last_sacked_tsn, chunk.cumulative_tsn): return received_time = time.ti...
def wait_one(self): """Waits until this worker has finished one work item or died.""" while True: try: item = self.output_queue.get(True, self.polltime) except Queue.Empty: continue except KeyboardInterrupt: LOGGER.debug...
Waits until this worker has finished one work item or died.
Below is the the instruction that describes the task: ### Input: Waits until this worker has finished one work item or died. ### Response: def wait_one(self): """Waits until this worker has finished one work item or died.""" while True: try: item = self.output_queue.get(...
def get_contacts(address_books, query, method="all", reverse=False, group=False, sort="first_name"): """Get a list of contacts from one or more address books. :param address_books: the address books to search :type address_books: list(address_book.AddressBook) :param query: a search qu...
Get a list of contacts from one or more address books. :param address_books: the address books to search :type address_books: list(address_book.AddressBook) :param query: a search query to select contacts :type quer: str :param method: the search method, one of "all", "name" or "uid" :type meth...
Below is the the instruction that describes the task: ### Input: Get a list of contacts from one or more address books. :param address_books: the address books to search :type address_books: list(address_book.AddressBook) :param query: a search query to select contacts :type quer: str :param me...
def __demodulate_data(self, data): """ Demodulates received IQ data and adds demodulated bits to messages :param data: :return: """ if len(data) == 0: return power_spectrum = data.real ** 2 + data.imag ** 2 is_above_noise = np.sqrt(np.mean(pow...
Demodulates received IQ data and adds demodulated bits to messages :param data: :return:
Below is the the instruction that describes the task: ### Input: Demodulates received IQ data and adds demodulated bits to messages :param data: :return: ### Response: def __demodulate_data(self, data): """ Demodulates received IQ data and adds demodulated bits to messages :...
def memcpy_htod(self, dest, src): """perform a host to device memory copy :param dest: A GPU memory allocation unit :type dest: pycuda.driver.DeviceAllocation :param src: A numpy array in host memory to store the data :type src: numpy.ndarray """ if isinstance(d...
perform a host to device memory copy :param dest: A GPU memory allocation unit :type dest: pycuda.driver.DeviceAllocation :param src: A numpy array in host memory to store the data :type src: numpy.ndarray
Below is the the instruction that describes the task: ### Input: perform a host to device memory copy :param dest: A GPU memory allocation unit :type dest: pycuda.driver.DeviceAllocation :param src: A numpy array in host memory to store the data :type src: numpy.ndarray ### Respons...
def getCollectorPath(self): """ Returns collector path servers.host.cpu.total.idle return "cpu" """ # If we don't have a host name, assume it's just the third part of the # metric path if self.host is None: return self.path.split('....
Returns collector path servers.host.cpu.total.idle return "cpu"
Below is the the instruction that describes the task: ### Input: Returns collector path servers.host.cpu.total.idle return "cpu" ### Response: def getCollectorPath(self): """ Returns collector path servers.host.cpu.total.idle return "cpu" ...