code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def plot_hurst_hist(): """ Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package ``matplotlib``. """ # local import to avoid dependency for non-debug use import matplotlib.pyplot as plt hs = [nolds.hurst_rs(np.random.random(...
Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package ``matplotlib``.
Below is the the instruction that describes the task: ### Input: Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package ``matplotlib``. ### Response: def plot_hurst_hist(): """ Plots a histogram of values obtained for the hurst ...
def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. """ return iter(nx.topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount >...
Return a topologically-sorted iterator over the terms in ``self`` which need to be computed.
Below is the the instruction that describes the task: ### Input: Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. ### Response: def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which ...
def powerDown(self): """power down the OpenThreadWpan""" print '%s call powerDown' % self.port if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false')[0] != 'Fail': time.sleep(0.5) if self.__sendCommand(WPANCTL_CMD + 'reset')[0] != 'Fail': ...
power down the OpenThreadWpan
Below is the the instruction that describes the task: ### Input: power down the OpenThreadWpan ### Response: def powerDown(self): """power down the OpenThreadWpan""" print '%s call powerDown' % self.port if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false')[0] ...
def collection_for_job(cls, job): """ Helper to return a collection of errors for the given job """ return cls.collection(job_model_repr=job.get_model_repr(), identifier=getattr(job, '_cached_identifier', job.identifier.hget()))
Helper to return a collection of errors for the given job
Below is the the instruction that describes the task: ### Input: Helper to return a collection of errors for the given job ### Response: def collection_for_job(cls, job): """ Helper to return a collection of errors for the given job """ return cls.collection(job_model_repr=job.get_m...
def scan_author_string_for_phrases(s): """Scan a name string and output an object representing its structure. Example: Sample output for the name 'Jingleheimer Schmitt, John Jacob, XVI.' is:: { 'TOKEN_TAG_LIST' : ['lastnames', 'nonlastnames', 'titles', 'raw'], ...
Scan a name string and output an object representing its structure. Example: Sample output for the name 'Jingleheimer Schmitt, John Jacob, XVI.' is:: { 'TOKEN_TAG_LIST' : ['lastnames', 'nonlastnames', 'titles', 'raw'], 'lastnames' : ['Jingleheimer', 'Schmitt'...
Below is the the instruction that describes the task: ### Input: Scan a name string and output an object representing its structure. Example: Sample output for the name 'Jingleheimer Schmitt, John Jacob, XVI.' is:: { 'TOKEN_TAG_LIST' : ['lastnames', 'nonlastnames', 'titles', ...
def as_rgb(self): """ Returns a tuple (r, g, b) of the color. """ html = self.as_html() return ( int(html[1:3], 16), int(html[3:5], 16), int(html[5:7], 16) )
Returns a tuple (r, g, b) of the color.
Below is the the instruction that describes the task: ### Input: Returns a tuple (r, g, b) of the color. ### Response: def as_rgb(self): """ Returns a tuple (r, g, b) of the color. """ html = self.as_html() return ( int(html[1:3], 16), int(html[3:5]...
def text_colour_for_hex(hexx, percent=50, dark='#000000', light='#ffffff'): """ Function to decide what colour to use for a given hex colour. Args: hexx (str): A hexadecimal colour, starting with '#'. Returns: bool: The colour's brightness is less than the given percent. """ re...
Function to decide what colour to use for a given hex colour. Args: hexx (str): A hexadecimal colour, starting with '#'. Returns: bool: The colour's brightness is less than the given percent.
Below is the the instruction that describes the task: ### Input: Function to decide what colour to use for a given hex colour. Args: hexx (str): A hexadecimal colour, starting with '#'. Returns: bool: The colour's brightness is less than the given percent. ### Response: def text_colour_fo...
def _getFullName(self): """get all name hierarchy separated by '.' """ name = "" tmp = self while isinstance(tmp, (InterfaceBase, HObjList)): if hasattr(tmp, "_name"): n = tmp._name else: n = '' if name == '': ...
get all name hierarchy separated by '.'
Below is the the instruction that describes the task: ### Input: get all name hierarchy separated by '.' ### Response: def _getFullName(self): """get all name hierarchy separated by '.' """ name = "" tmp = self while isinstance(tmp, (InterfaceBase, HObjList)): if hasattr...
def _ParseArgs(self, args, known_only): """Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args: args: List of s...
Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args: args: List of strings with the arguments to parse. known...
Below is the the instruction that describes the task: ### Input: Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args:...
def remove_subj(self, subj_str): """Remove all permissions for subject. Args: subj_str : str Subject for which to remove all permissions. Since subjects can only be present in the AccessPolicy when they have one or more permissions, this removes the subject...
Remove all permissions for subject. Args: subj_str : str Subject for which to remove all permissions. Since subjects can only be present in the AccessPolicy when they have one or more permissions, this removes the subject itself as well. The subject ma...
Below is the the instruction that describes the task: ### Input: Remove all permissions for subject. Args: subj_str : str Subject for which to remove all permissions. Since subjects can only be present in the AccessPolicy when they have one or more permissions, this remove...
def get_args(): ''' Parse CLI args ''' parser = argparse.ArgumentParser(description='Process args') parser.Add_argument( '-H', '--host', required=True, action='store', help='Remote host to connect to' ) parser.add_argument( '-P', '--port', type...
Parse CLI args
Below is the the instruction that describes the task: ### Input: Parse CLI args ### Response: def get_args(): ''' Parse CLI args ''' parser = argparse.ArgumentParser(description='Process args') parser.Add_argument( '-H', '--host', required=True, action='store', h...
def collected(self, group, filename=None, host=None, location=None, move=True, all=True): ''' Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return: ...
Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return:
Below is the the instruction that describes the task: ### Input: Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return: ### Response: def collected(self, group, fi...
def create(cls, fqdn, flags, algorithm, public_key): """Create a dnssec key.""" fqdn = fqdn.lower() params = { 'flags': flags, 'algorithm': algorithm, 'public_key': public_key, } result = cls.call('domain.dnssec.create', fqdn, params) ...
Create a dnssec key.
Below is the the instruction that describes the task: ### Input: Create a dnssec key. ### Response: def create(cls, fqdn, flags, algorithm, public_key): """Create a dnssec key.""" fqdn = fqdn.lower() params = { 'flags': flags, 'algorithm': algorithm, 'pu...
def detalhe(self, posicao=0): """Retorna o detalhe de um CEP da última lista de resultados""" handle = self._url_open('detalheCEPAction.do', {'Metodo': 'detalhe', 'TipoCep': 2, 'Posicao': posi...
Retorna o detalhe de um CEP da última lista de resultados
Below is the the instruction that describes the task: ### Input: Retorna o detalhe de um CEP da última lista de resultados ### Response: def detalhe(self, posicao=0): """Retorna o detalhe de um CEP da última lista de resultados""" handle = self._url_open('detalheCEPAction.do', {'Metodo': 'detalhe',...
def current_jobs(self): """ Returns a snapshot of the Jobs that are currently being processed by the ThreadPool. These jobs can not be found in the #pending_jobs() list. """ jobs = [] with synchronized(self.__queue): for worker in self.__threads: with synchronized(worker): ...
Returns a snapshot of the Jobs that are currently being processed by the ThreadPool. These jobs can not be found in the #pending_jobs() list.
Below is the the instruction that describes the task: ### Input: Returns a snapshot of the Jobs that are currently being processed by the ThreadPool. These jobs can not be found in the #pending_jobs() list. ### Response: def current_jobs(self): """ Returns a snapshot of the Jobs that are currently bein...
def get_transactionlist(delegate_pubkey): """returns a list of named tuples of all transactions relevant to a specific delegates voters. Flow: finds all voters and unvoters, SELECTs all transactions of those voters, names all transactions according to the scheme: 'transaction', 'id amount timestamp recipien...
returns a list of named tuples of all transactions relevant to a specific delegates voters. Flow: finds all voters and unvoters, SELECTs all transactions of those voters, names all transactions according to the scheme: 'transaction', 'id amount timestamp recipientId senderId rawasset type fee blockId
Below is the the instruction that describes the task: ### Input: returns a list of named tuples of all transactions relevant to a specific delegates voters. Flow: finds all voters and unvoters, SELECTs all transactions of those voters, names all transactions according to the scheme: 'transaction', 'id amoun...
def depend(*args): """ Decorator to declare dependencies to other modules. Recommended usage is:: import other_module @depend(other_module.ModuleClass) class MyModule(Module): ... :param \*args: depended module classes. """ def decfunc(cls): ...
Decorator to declare dependencies to other modules. Recommended usage is:: import other_module @depend(other_module.ModuleClass) class MyModule(Module): ... :param \*args: depended module classes.
Below is the the instruction that describes the task: ### Input: Decorator to declare dependencies to other modules. Recommended usage is:: import other_module @depend(other_module.ModuleClass) class MyModule(Module): ... :param \*args: depended module clas...
def setup_communication_daemon(self): # pylint: disable=no-member """ Setup HTTP server daemon to listen for incoming HTTP requests from other Alignak daemons :return: True if initialization is ok, else False """ ca_cert = ssl_cert = ssl_key = server_dh = None #...
Setup HTTP server daemon to listen for incoming HTTP requests from other Alignak daemons :return: True if initialization is ok, else False
Below is the the instruction that describes the task: ### Input: Setup HTTP server daemon to listen for incoming HTTP requests from other Alignak daemons :return: True if initialization is ok, else False ### Response: def setup_communication_daemon(self): # pylint: disable=no-member ...
def edit(self, title, state=github.GithubObject.NotSet, description=github.GithubObject.NotSet, due_on=github.GithubObject.NotSet): """ :calls: `PATCH /repos/:owner/:repo/milestones/:number <http://developer.github.com/v3/issues/milestones>`_ :param title: string :param state: string ...
:calls: `PATCH /repos/:owner/:repo/milestones/:number <http://developer.github.com/v3/issues/milestones>`_ :param title: string :param state: string :param description: string :param due_on: date :rtype: None
Below is the the instruction that describes the task: ### Input: :calls: `PATCH /repos/:owner/:repo/milestones/:number <http://developer.github.com/v3/issues/milestones>`_ :param title: string :param state: string :param description: string :param due_on: date :rtype: None ##...
def index(): """Handle /unapi set of pages.""" # Prepare mappings from configuration. mapping = cfg['UNAPI_FORMAT_MAPPING'] names = {mapping[k]: k for k in mapping} # Clean request arguments. identifier = request.values.get('id', type=int) format_ = request.values.get('format') format_ =...
Handle /unapi set of pages.
Below is the the instruction that describes the task: ### Input: Handle /unapi set of pages. ### Response: def index(): """Handle /unapi set of pages.""" # Prepare mappings from configuration. mapping = cfg['UNAPI_FORMAT_MAPPING'] names = {mapping[k]: k for k in mapping} # Clean request argumen...
def write_table(self, d): """Write out a Python dictionary made of up string keys, and values that are strings, signed integers, Decimal, datetime.datetime, or sub-dictionaries following the same constraints.""" self._flushbits() table_data = AMQPWriter() for k, v in item...
Write out a Python dictionary made of up string keys, and values that are strings, signed integers, Decimal, datetime.datetime, or sub-dictionaries following the same constraints.
Below is the the instruction that describes the task: ### Input: Write out a Python dictionary made of up string keys, and values that are strings, signed integers, Decimal, datetime.datetime, or sub-dictionaries following the same constraints. ### Response: def write_table(self, d): """Wri...
def _winapi(self, func, *a, **kw): """ Flush and call win API function. """ self.flush() if _DEBUG_RENDER_OUTPUT: self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n') self.LOG.write(b' ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b...
Flush and call win API function.
Below is the the instruction that describes the task: ### Input: Flush and call win API function. ### Response: def _winapi(self, func, *a, **kw): """ Flush and call win API function. """ self.flush() if _DEBUG_RENDER_OUTPUT: self.LOG.write(('%r' % func.__name__...
def generate_jwt(claims, priv_key=None, algorithm='PS512', lifetime=None, expires=None, not_before=None, jti_size=16, other_headers=None): """ Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict ...
Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an empty cryptographic signature and :obj:`algorithm` will be forced to...
Below is the the instruction that describes the task: ### Input: Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an...
def addVote(self, prepare: Prepare, voter: str) -> None: """ Add the specified PREPARE to this replica's list of received PREPAREs. :param prepare: the PREPARE to add to the list :param voter: the name of the node who sent the PREPARE """ self._add_msg(prepare, v...
Add the specified PREPARE to this replica's list of received PREPAREs. :param prepare: the PREPARE to add to the list :param voter: the name of the node who sent the PREPARE
Below is the the instruction that describes the task: ### Input: Add the specified PREPARE to this replica's list of received PREPAREs. :param prepare: the PREPARE to add to the list :param voter: the name of the node who sent the PREPARE ### Response: def addVote(self, prepare: Prepare, v...
def pre_sql_setup(self): """ Adds the JOINS and SELECTS for fetching multilingual data. """ super(MultilingualSQLCompiler, self).pre_sql_setup() if not self.query.include_translation_data: return opts = self.query.model._meta qn = self.quote_name_unl...
Adds the JOINS and SELECTS for fetching multilingual data.
Below is the the instruction that describes the task: ### Input: Adds the JOINS and SELECTS for fetching multilingual data. ### Response: def pre_sql_setup(self): """ Adds the JOINS and SELECTS for fetching multilingual data. """ super(MultilingualSQLCompiler, self).pre_sql_setup() ...
def find_by_id(self, tag, params={}, **options): """Returns the complete tag record for a single tag. Parameters ---------- tag : {Id} The tag to get. [params] : {Object} Parameters for the request """ path = "/tags/%s" % (tag) return self.client.get(pat...
Returns the complete tag record for a single tag. Parameters ---------- tag : {Id} The tag to get. [params] : {Object} Parameters for the request
Below is the the instruction that describes the task: ### Input: Returns the complete tag record for a single tag. Parameters ---------- tag : {Id} The tag to get. [params] : {Object} Parameters for the request ### Response: def find_by_id(self, tag, params={}, **options): ...
async def RemoveBlocks(self, all_): ''' all_ : bool Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Controller', request='RemoveBlocks', version=5, params=_params) ...
all_ : bool Returns -> None
Below is the the instruction that describes the task: ### Input: all_ : bool Returns -> None ### Response: async def RemoveBlocks(self, all_): ''' all_ : bool Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Controlle...
def remove_piece_at(self, square, into_hand=False): '''Removes a piece from the given square if present.''' piece_type = self.piece_type_at(square) if piece_type == NONE: return if into_hand: self.add_piece_into_hand(piece_type, self.turn) mask = BB_SQU...
Removes a piece from the given square if present.
Below is the the instruction that describes the task: ### Input: Removes a piece from the given square if present. ### Response: def remove_piece_at(self, square, into_hand=False): '''Removes a piece from the given square if present.''' piece_type = self.piece_type_at(square) if piece_type...
def registerJavaUDAF(self, name, javaClassName): """Register a Java user-defined aggregate function as a SQL function. :param name: name of the user-defined aggregate function :param javaClassName: fully qualified name of java class >>> spark.udf.registerJavaUDAF("javaUDAF", "test.org....
Register a Java user-defined aggregate function as a SQL function. :param name: name of the user-defined aggregate function :param javaClassName: fully qualified name of java class >>> spark.udf.registerJavaUDAF("javaUDAF", "test.org.apache.spark.sql.MyDoubleAvg") >>> df = spark.create...
Below is the the instruction that describes the task: ### Input: Register a Java user-defined aggregate function as a SQL function. :param name: name of the user-defined aggregate function :param javaClassName: fully qualified name of java class >>> spark.udf.registerJavaUDAF("javaUDAF", "...
def hash(self): """ Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only. """ renderer_str = "{}|{...
Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only.
Below is the the instruction that describes the task: ### Input: Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only. ### Resp...
def compute_venn3_colors(set_colors): ''' Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111). >>> compute_venn3_colors(['r', 'g', 'b']) (array([ 1.,...
Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111). >>> compute_venn3_colors(['r', 'g', 'b']) (array([ 1., 0., 0.]),..., array([ 0.4, 0.2, 0.4]))
Below is the the instruction that describes the task: ### Input: Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111). >>> compute_venn3_colors(['r', 'g', 'b'...
def check_existing_git_tag(repo, t_tag, **kwargs): """ Check for a pre-existng tag in the github repo. Parameters ---------- repo : github.Repository.Repository repo to inspect for an existing tagsdf t_tag: codekit.pygithub.TargetTag dict repesenting a target git tag Return...
Check for a pre-existng tag in the github repo. Parameters ---------- repo : github.Repository.Repository repo to inspect for an existing tagsdf t_tag: codekit.pygithub.TargetTag dict repesenting a target git tag Returns ------- insync : `bool` True if tag exists an...
Below is the the instruction that describes the task: ### Input: Check for a pre-existng tag in the github repo. Parameters ---------- repo : github.Repository.Repository repo to inspect for an existing tagsdf t_tag: codekit.pygithub.TargetTag dict repesenting a target git tag ...
def is_always_accessible(self): """ Returns true if the course/task is always accessible """ return self._val[0] == datetime.min and self._val[1] == datetime.max
Returns true if the course/task is always accessible
Below is the the instruction that describes the task: ### Input: Returns true if the course/task is always accessible ### Response: def is_always_accessible(self): """ Returns true if the course/task is always accessible """ return self._val[0] == datetime.min and self._val[1] == datetime.max
def _onDeviceEvent(self, client, userdata, pahoMessage): """ Internal callback for device event messages, parses source device from topic string and passes the information on to the registerd device event callback """ try: event = Event(pahoMessage, self._messageCodec...
Internal callback for device event messages, parses source device from topic string and passes the information on to the registerd device event callback
Below is the the instruction that describes the task: ### Input: Internal callback for device event messages, parses source device from topic string and passes the information on to the registerd device event callback ### Response: def _onDeviceEvent(self, client, userdata, pahoMessage): """ ...
def envelope(**kwargs): """Create OAI-PMH envelope for response.""" e_oaipmh = Element(etree.QName(NS_OAIPMH, 'OAI-PMH'), nsmap=NSMAP) e_oaipmh.set(etree.QName(NS_XSI, 'schemaLocation'), '{0} {1}'.format(NS_OAIPMH, NS_OAIPMH_XSD)) e_tree = ElementTree(element=e_oaipmh) if current_a...
Create OAI-PMH envelope for response.
Below is the the instruction that describes the task: ### Input: Create OAI-PMH envelope for response. ### Response: def envelope(**kwargs): """Create OAI-PMH envelope for response.""" e_oaipmh = Element(etree.QName(NS_OAIPMH, 'OAI-PMH'), nsmap=NSMAP) e_oaipmh.set(etree.QName(NS_XSI, 'schemaLocation'),...
def _copy_margin(self, cli, lazy_screen, new_screen, write_position, move_x, width): """ Copy characters from the margin screen to the real screen. """ xpos = write_position.xpos + move_x ypos = write_position.ypos margin_write_position = WritePosition(xpos, ypos, width,...
Copy characters from the margin screen to the real screen.
Below is the the instruction that describes the task: ### Input: Copy characters from the margin screen to the real screen. ### Response: def _copy_margin(self, cli, lazy_screen, new_screen, write_position, move_x, width): """ Copy characters from the margin screen to the real screen. """ ...
def create_polygon(self, geopolygon, name=None): """ Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new...
Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new polygon :type name: str :return: a `pyowm.agro10.pol...
Below is the the instruction that describes the task: ### Input: Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new...
def compute_ffill_by_group( df, id_cols: List[str], reference_cols: List[str], value_col: str ): """ Compute `ffill` with `groupby` Dedicated method as there is a performance issue with a simple groupby/fillna (2017/07) The method `ffill` propagates last valid value forwa...
Compute `ffill` with `groupby` Dedicated method as there is a performance issue with a simple groupby/fillna (2017/07) The method `ffill` propagates last valid value forward to next values. --- ### Parameters *mandatory :* - `id_cols` (*list of str*): names of columns used to create each grou...
Below is the the instruction that describes the task: ### Input: Compute `ffill` with `groupby` Dedicated method as there is a performance issue with a simple groupby/fillna (2017/07) The method `ffill` propagates last valid value forward to next values. --- ### Parameters *mandatory :* -...
def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None): """Checks if file exists in working_directory otherwise tries to dowload the file, and optionally also tries to extract the file if format is ".zip" or ".tar" Parameters ----------- filename...
Checks if file exists in working_directory otherwise tries to dowload the file, and optionally also tries to extract the file if format is ".zip" or ".tar" Parameters ----------- filename : str The name of the (to be) dowloaded file. working_directory : str A folder path to search f...
Below is the the instruction that describes the task: ### Input: Checks if file exists in working_directory otherwise tries to dowload the file, and optionally also tries to extract the file if format is ".zip" or ".tar" Parameters ----------- filename : str The name of the (to be) dowloade...
def ehh_decay(h, truncate=False): """Compute the decay of extended haplotype homozygosity (EHH) moving away from the first variant. Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. truncate : bool, optional If True, the return array wi...
Compute the decay of extended haplotype homozygosity (EHH) moving away from the first variant. Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. truncate : bool, optional If True, the return array will exclude trailing zeros. Returns ...
Below is the the instruction that describes the task: ### Input: Compute the decay of extended haplotype homozygosity (EHH) moving away from the first variant. Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. truncate : bool, optional ...
def __insert_child(self, parent_tree_node, index, tree_node): """ Called from the root tree node when a new node is inserted into tree. This method creates properties to represent the node for display and inserts it into the item model controller. """ # manage the item mo...
Called from the root tree node when a new node is inserted into tree. This method creates properties to represent the node for display and inserts it into the item model controller.
Below is the the instruction that describes the task: ### Input: Called from the root tree node when a new node is inserted into tree. This method creates properties to represent the node for display and inserts it into the item model controller. ### Response: def __insert_child(self, parent_tree_node,...
def area(self): """ Return the area of the polygons interior. Returns --------- area: float, total area of polygons minus interiors """ area = float(sum(i.area for i in self.polygons_full)) return area
Return the area of the polygons interior. Returns --------- area: float, total area of polygons minus interiors
Below is the the instruction that describes the task: ### Input: Return the area of the polygons interior. Returns --------- area: float, total area of polygons minus interiors ### Response: def area(self): """ Return the area of the polygons interior. Returns ...
def parseRangeString(s, convertToZeroBased=False): """ Parse a range string of the form 1-5,12,100-200. @param s: A C{str} specifiying a set of numbers, given in the form of comma separated numeric ranges or individual indices. @param convertToZeroBased: If C{True} all indices will have one ...
Parse a range string of the form 1-5,12,100-200. @param s: A C{str} specifiying a set of numbers, given in the form of comma separated numeric ranges or individual indices. @param convertToZeroBased: If C{True} all indices will have one subtracted from them. @return: A C{set} of all C{int}s...
Below is the the instruction that describes the task: ### Input: Parse a range string of the form 1-5,12,100-200. @param s: A C{str} specifiying a set of numbers, given in the form of comma separated numeric ranges or individual indices. @param convertToZeroBased: If C{True} all indices will have o...
def get_instance(self, payload): """ Build an instance of RecordInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.RecordInstance :rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance """ ...
Build an instance of RecordInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.RecordInstance :rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance
Below is the the instruction that describes the task: ### Input: Build an instance of RecordInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.RecordInstance :rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance ### ...
def alias_asset(self, asset_id, alias_id): """Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility. The primary ``Id`` of the ``Asset`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another asse...
Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility. The primary ``Id`` of the ``Asset`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another asset, it is reassigned to the given asset ``Id``....
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility. The primary ``Id`` of the ``Asset`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer ...
def load(): """ | Load the configuration file. | Add dynamically configuration to the module. :rtype: None """ config = ConfigParser.RawConfigParser(DEFAULTS) config.readfp(open(CONF_PATH)) for section in config.sections(): globals()[section] = {} for key, val in config....
| Load the configuration file. | Add dynamically configuration to the module. :rtype: None
Below is the the instruction that describes the task: ### Input: | Load the configuration file. | Add dynamically configuration to the module. :rtype: None ### Response: def load(): """ | Load the configuration file. | Add dynamically configuration to the module. :rtype: None """ ...
def clear(self): """ Clear all contents in the relay memory """ self.states[:] = 0 self.actions[:] = 0 self.rewards[:] = 0 self.terminate_flags[:] = 0 self.top = 0 self.size = 0
Clear all contents in the relay memory
Below is the the instruction that describes the task: ### Input: Clear all contents in the relay memory ### Response: def clear(self): """ Clear all contents in the relay memory """ self.states[:] = 0 self.actions[:] = 0 self.rewards[:] = 0 self.terminate_fla...
def _Open(self, path_spec, mode='rb'): """Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the acces...
Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: ...
Below is the the instruction that describes the task: ### Input: Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: Ac...
def writer_acquire(self): """Acquire the lock to write""" self._order_mutex.acquire() self._access_mutex.acquire() self._order_mutex.release()
Acquire the lock to write
Below is the the instruction that describes the task: ### Input: Acquire the lock to write ### Response: def writer_acquire(self): """Acquire the lock to write""" self._order_mutex.acquire() self._access_mutex.acquire() self._order_mutex.release()
def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None...
Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack'
Below is the the instruction that describes the task: ### Input: Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ### Response: def drop_extension(name, if_exists=None, restrict=None, ...
def __serial_transform(self, jam, steps): '''A serial transformation union''' # This uses the round-robin itertools recipe if six.PY2: attr = 'next' else: attr = '__next__' pending = len(steps) nexts = itertools.cycle(getattr(iter(D.transform(jam...
A serial transformation union
Below is the the instruction that describes the task: ### Input: A serial transformation union ### Response: def __serial_transform(self, jam, steps): '''A serial transformation union''' # This uses the round-robin itertools recipe if six.PY2: attr = 'next' else: ...
def mod(x, y, context=None): """ Return the remainder of x divided by y, with sign matching that of y. """ return _apply_function_in_current_context( BigFloat, mpfr_mod, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), co...
Return the remainder of x divided by y, with sign matching that of y.
Below is the the instruction that describes the task: ### Input: Return the remainder of x divided by y, with sign matching that of y. ### Response: def mod(x, y, context=None): """ Return the remainder of x divided by y, with sign matching that of y. """ return _apply_function_in_current_context(...
def cli(code, cif, parameters, daemon): """Run any cod-tools calculation for the given ``CifData`` node. The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed to the calculation, and by extension the cod-tools script. Example:: launch_calc...
Run any cod-tools calculation for the given ``CifData`` node. The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed to the calculation, and by extension the cod-tools script. Example:: launch_calculation_cod_tools -X cif-filter -N 95 -p '--use...
Below is the the instruction that describes the task: ### Input: Run any cod-tools calculation for the given ``CifData`` node. The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed to the calculation, and by extension the cod-tools script. Example:...
def rename_node(self, name, new_name): # noqa: D302 r""" Rename a tree node. It is typical to have a root node name with more than one hierarchy level after using :py:meth:`ptrie.Trie.make_root`. In this instance the root node *can* be renamed as long as the new root name has t...
r""" Rename a tree node. It is typical to have a root node name with more than one hierarchy level after using :py:meth:`ptrie.Trie.make_root`. In this instance the root node *can* be renamed as long as the new root name has the same or less hierarchy levels as the existing root...
Below is the the instruction that describes the task: ### Input: r""" Rename a tree node. It is typical to have a root node name with more than one hierarchy level after using :py:meth:`ptrie.Trie.make_root`. In this instance the root node *can* be renamed as long as the new root na...
def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor): """Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running and there are no tasks elig...
Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running and there are no tasks eligible to be retried. Args: provider: job service provider job_id: a single...
Below is the the instruction that describes the task: ### Input: Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running and there are no tasks eligible to be retr...
def _wait_dialog(self): """Wait for dialogs and handle them until done. """ logger.debug('waiting for dialog') done = False error = False logger.info("self timeout %d",self.timeout) while not done and self.timeout: try: dialog = self._...
Wait for dialogs and handle them until done.
Below is the the instruction that describes the task: ### Input: Wait for dialogs and handle them until done. ### Response: def _wait_dialog(self): """Wait for dialogs and handle them until done. """ logger.debug('waiting for dialog') done = False error = False logg...
def filter_all_reachable_leaves_many(self, identifier_filters, language, forbidden_identifiers=None): """ Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of ide...
Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of identifier filters language (str): language used for further filtering (some objects for differen...
Below is the the instruction that describes the task: ### Input: Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of identifier filters language (str): language ...
def _memory_usage_ps(): """return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True """ out = subprocess.Popen( ['ps', 'v', '-p', str(os.getpid())], stdout=subprocess.PIPE).communicate()[0].split(b'\n') vsz_index = out[0].split().index(b'RSS') ...
return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True
Below is the the instruction that describes the task: ### Input: return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True ### Response: def _memory_usage_ps(): """return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True ""...
def has_option_tag(self, section, option, tag): """ Convenience function accessing has_option_tags() for a single tag: see documentation for that function. NB calling has_option_tags() directly is preferred for simplicity. Parameters ----------- self : ConfigPars...
Convenience function accessing has_option_tags() for a single tag: see documentation for that function. NB calling has_option_tags() directly is preferred for simplicity. Parameters ----------- self : ConfigParser object The ConfigParser object (automatically passed ...
Below is the the instruction that describes the task: ### Input: Convenience function accessing has_option_tags() for a single tag: see documentation for that function. NB calling has_option_tags() directly is preferred for simplicity. Parameters ----------- self : ConfigPar...
def hotspotAt(self, point): """ Returns the hotspot at the inputed point. :param point | <QPoint> :return <XNodeHotspot> || None """ for hotspot in self._hotspots: rect = hotspot.rect() if rect.contains(point): ...
Returns the hotspot at the inputed point. :param point | <QPoint> :return <XNodeHotspot> || None
Below is the the instruction that describes the task: ### Input: Returns the hotspot at the inputed point. :param point | <QPoint> :return <XNodeHotspot> || None ### Response: def hotspotAt(self, point): """ Returns the hotspot at the inputed point. ...
def get_version_info(): """Get VCS info and write version info to version.py """ from pycbc import _version_helper class vdummy(object): def __getattr__(self, attr): return '' # If this is a pycbc git repo always populate version information using GIT try: vinfo = _...
Get VCS info and write version info to version.py
Below is the the instruction that describes the task: ### Input: Get VCS info and write version info to version.py ### Response: def get_version_info(): """Get VCS info and write version info to version.py """ from pycbc import _version_helper class vdummy(object): def __getattr__(self, at...
def _POUpdateBuilder(env, **kw): """ Create an object of `POUpdate` builder """ import SCons.Action from SCons.Tool.GettextCommon import _POFileBuilder action = SCons.Action.Action(_update_or_init_po_files, None) return _POFileBuilder(env, action=action, target_alias='$POUPDATE_ALIAS')
Create an object of `POUpdate` builder
Below is the the instruction that describes the task: ### Input: Create an object of `POUpdate` builder ### Response: def _POUpdateBuilder(env, **kw): """ Create an object of `POUpdate` builder """ import SCons.Action from SCons.Tool.GettextCommon import _POFileBuilder action = SCons.Action.Action(_update_...
def init_options(self): """ Initialize the underlying map options. """ self.options = GoogleMapOptions() d = self.declaration self.set_map_type(d.map_type) if d.ambient_mode: self.set_ambient_mode(d.ambient_mode) if (d.camera_position or d.camera_zoom...
Initialize the underlying map options.
Below is the the instruction that describes the task: ### Input: Initialize the underlying map options. ### Response: def init_options(self): """ Initialize the underlying map options. """ self.options = GoogleMapOptions() d = self.declaration self.set_map_type(d.map_type) ...
def getall(self, key, type=None): """Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list. """ values = [] ...
Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list.
Below is the the instruction that describes the task: ### Input: Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list. ### Resp...
def complete(self, text: str, state: int) -> Optional[str]: """Override of command method which returns the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. T...
Override of command method which returns the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. This method gets called directly by readline because it is set as the ta...
Below is the the instruction that describes the task: ### Input: Override of command method which returns the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. Thi...
def authorize(scope, password=[None]): """ Looks for a password prompt on the current connection and enters the given password. If a password is not given, the function uses the same password that was used at the last login attempt; it is an error if no such attempt was made before. :type ...
Looks for a password prompt on the current connection and enters the given password. If a password is not given, the function uses the same password that was used at the last login attempt; it is an error if no such attempt was made before. :type password: string :param password: A password.
Below is the the instruction that describes the task: ### Input: Looks for a password prompt on the current connection and enters the given password. If a password is not given, the function uses the same password that was used at the last login attempt; it is an error if no such attempt was made be...
def _update_svrg_gradients(self): """Calculates gradients based on the SVRG update rule. """ param_names = self._exec_group.param_names for ctx in range(self._ctx_len): for index, name in enumerate(param_names): g_curr_batch_reg = self._exec_group.grad_arrays[...
Calculates gradients based on the SVRG update rule.
Below is the the instruction that describes the task: ### Input: Calculates gradients based on the SVRG update rule. ### Response: def _update_svrg_gradients(self): """Calculates gradients based on the SVRG update rule. """ param_names = self._exec_group.param_names for ctx in range...
def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, timestamp=None): """Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name ...
Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (dic...
Below is the the instruction that describes the task: ### Input: Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (st...
def solve_limited(self, assumptions=[]): """ Solve internal formula using given budgets for conflicts and propagations. """ if self.minicard: if self.use_timer: start_time = time.clock() # saving default SIGINT handler ...
Solve internal formula using given budgets for conflicts and propagations.
Below is the the instruction that describes the task: ### Input: Solve internal formula using given budgets for conflicts and propagations. ### Response: def solve_limited(self, assumptions=[]): """ Solve internal formula using given budgets for conflicts and propagation...
def RunSphinxAPIDoc(_): """Runs sphinx-apidoc to auto-generate documentation.""" current_directory = os.path.abspath(os.path.dirname(__file__)) module = os.path.join(current_directory, '..', 'plaso') api_directory = os.path.join(current_directory, 'sources', 'api') apidoc.main(['-o', api_directory, module, '-...
Runs sphinx-apidoc to auto-generate documentation.
Below is the the instruction that describes the task: ### Input: Runs sphinx-apidoc to auto-generate documentation. ### Response: def RunSphinxAPIDoc(_): """Runs sphinx-apidoc to auto-generate documentation.""" current_directory = os.path.abspath(os.path.dirname(__file__)) module = os.path.join(current_direc...
def init_with_context(self, context): """ Find the current URL based on the context. It uses :func:`get_edited_object` to find the model, and calls ``get_absolute_url()`` to get the frontend URL. """ super(ReturnToSiteItem, self).init_with_context(context) # See ...
Find the current URL based on the context. It uses :func:`get_edited_object` to find the model, and calls ``get_absolute_url()`` to get the frontend URL.
Below is the the instruction that describes the task: ### Input: Find the current URL based on the context. It uses :func:`get_edited_object` to find the model, and calls ``get_absolute_url()`` to get the frontend URL. ### Response: def init_with_context(self, context): """ Find the...
def browserify_libs(lib_dirs, output_file, babelify=False): """ Browserify one or more library directories into a single javascript file. Generates source maps in debug mode. Minifies the output in release mode. The final directory name in each of lib_dirs is the library name for importing. Eg....
Browserify one or more library directories into a single javascript file. Generates source maps in debug mode. Minifies the output in release mode. The final directory name in each of lib_dirs is the library name for importing. Eg.:: lib_dirs = ['cordova_libs/jskit'] var MyClass = req...
Below is the the instruction that describes the task: ### Input: Browserify one or more library directories into a single javascript file. Generates source maps in debug mode. Minifies the output in release mode. The final directory name in each of lib_dirs is the library name for importing. Eg.:: ...
def command_int_send(self, target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, force_mavlink1=False): ''' Message encoding a command with parameters as scaled integers. Scaling depends on the actual command valu...
Message encoding a command with parameters as scaled integers. Scaling depends on the actual command value. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) frame : The coordinate syste...
Below is the the instruction that describes the task: ### Input: Message encoding a command with parameters as scaled integers. Scaling depends on the actual command value. target_system : System ID (uint8_t) target_component : Component ID (uint...
def save(self): """ Save a record to the database, creating it if needed, updating it otherwise. Also saves related records (children and dependents) as needed. """ with Repo.db: self._do_save() our_name = inflector.singularize(Repo.table_name(self...
Save a record to the database, creating it if needed, updating it otherwise. Also saves related records (children and dependents) as needed.
Below is the the instruction that describes the task: ### Input: Save a record to the database, creating it if needed, updating it otherwise. Also saves related records (children and dependents) as needed. ### Response: def save(self): """ Save a record to the database, creating it ...
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: logs /containers/<id>/logs power /containers/<id>/power ``super`` is called otherwise. """ i...
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: logs /containers/<id>/logs power /containers/<id>/power ``super`` is called otherwise.
Below is the the instruction that describes the task: ### Input: Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: logs /containers/<id>/logs power /containers/<id>/power ``super`` is called oth...
def get_feedback(self, feedback_id, model=None, **kwargs): """ List a specified feedback entry. Lists a feedback entry with a specified `feedback_id`. :param str feedback_id: A string that specifies the feedback entry to be included in the output. :param str model: The ...
List a specified feedback entry. Lists a feedback entry with a specified `feedback_id`. :param str feedback_id: A string that specifies the feedback entry to be included in the output. :param str model: The analysis model to be used by the service. For the **Element classificat...
Below is the the instruction that describes the task: ### Input: List a specified feedback entry. Lists a feedback entry with a specified `feedback_id`. :param str feedback_id: A string that specifies the feedback entry to be included in the output. :param str model: The analysis m...
def to_number(obj): ''' Cast an arbitrary object or sequence to a number type ''' if isinstance(obj, LiteralWrapper): val = obj.obj elif isinstance(obj, Iterable) and not isinstance(obj, str): val = next(obj, None) else: val = obj if val is None: #FIXME: Shoul...
Cast an arbitrary object or sequence to a number type
Below is the the instruction that describes the task: ### Input: Cast an arbitrary object or sequence to a number type ### Response: def to_number(obj): ''' Cast an arbitrary object or sequence to a number type ''' if isinstance(obj, LiteralWrapper): val = obj.obj elif isinstance(obj, I...
def format_notification(self, notification): """ Formats given notification. :param notification: Notification to format. :type notification: Notification :return: Method success. :rtype: bool """ return "{0} | '{1}'".format(time.ctime(notification.time)...
Formats given notification. :param notification: Notification to format. :type notification: Notification :return: Method success. :rtype: bool
Below is the the instruction that describes the task: ### Input: Formats given notification. :param notification: Notification to format. :type notification: Notification :return: Method success. :rtype: bool ### Response: def format_notification(self, notification): """ ...
def getJson(url): """Download json and return simplejson object""" site = urllib2.urlopen(url, timeout=300) return json.load(site)
Download json and return simplejson object
Below is the the instruction that describes the task: ### Input: Download json and return simplejson object ### Response: def getJson(url): """Download json and return simplejson object""" site = urllib2.urlopen(url, timeout=300) return json.load(site)
def correct_rates(rates, opt_qes, combs): """Applies optimal qes to rates. Should be closer to fitted_rates afterwards. Parameters ---------- rates: numpy array of rates of all PMT combinations opt_qes: numpy array of optimal qe values for all PMTs combs: pmt combinations used to correct ...
Applies optimal qes to rates. Should be closer to fitted_rates afterwards. Parameters ---------- rates: numpy array of rates of all PMT combinations opt_qes: numpy array of optimal qe values for all PMTs combs: pmt combinations used to correct Returns ------- corrected_rates: nump...
Below is the the instruction that describes the task: ### Input: Applies optimal qes to rates. Should be closer to fitted_rates afterwards. Parameters ---------- rates: numpy array of rates of all PMT combinations opt_qes: numpy array of optimal qe values for all PMTs combs: pmt combinatio...
def update(self, gradient, step): """Update the search direction given the latest gradient and step""" do_sd = self.gradient_old is None self.gradient_old = self.gradient self.gradient = gradient if do_sd: self._update_sd() else: self._update_cg()
Update the search direction given the latest gradient and step
Below is the the instruction that describes the task: ### Input: Update the search direction given the latest gradient and step ### Response: def update(self, gradient, step): """Update the search direction given the latest gradient and step""" do_sd = self.gradient_old is None self.gradien...
def _find_file(filename): """ Find the file path, first checking if it exists and then looking in the data directory """ import os if os.path.exists(filename): path = filename else: path = os.path.dirname(__file__) path = os.path.join(path, 'data', filename) if n...
Find the file path, first checking if it exists and then looking in the data directory
Below is the the instruction that describes the task: ### Input: Find the file path, first checking if it exists and then looking in the data directory ### Response: def _find_file(filename): """ Find the file path, first checking if it exists and then looking in the data directory """ impo...
def Pack(self): """Returns this message in an over-the-wire format.""" return struct.pack(self.format, self.command, self.arg0, self.arg1, len(self.data), self.checksum, self.magic)
Returns this message in an over-the-wire format.
Below is the the instruction that describes the task: ### Input: Returns this message in an over-the-wire format. ### Response: def Pack(self): """Returns this message in an over-the-wire format.""" return struct.pack(self.format, self.command, self.arg0, self.arg1, len(s...
def fill_login_form(self, username, username_field, user_password, user_password_field): """Fills form with login info :param username: user login :param username_field: name of field to fill with username :param user_password: login password :param user_...
Fills form with login info :param username: user login :param username_field: name of field to fill with username :param user_password: login password :param user_password_field: name of field to fill with user password
Below is the the instruction that describes the task: ### Input: Fills form with login info :param username: user login :param username_field: name of field to fill with username :param user_password: login password :param user_password_field: name of field to fill with user passwor...
def create_plan(self, *, plan_code, description, interval, interval_count, max_payments_allowed, payment_attempts_delay, plan_value, plan_tax, plan_tax_return_base, currency, max_payment_attempts=None, max_pending_payments=None, trial_days=None): """ Creating a ne...
Creating a new plan for subscriptions associated with the merchant. Args: plan_code: Unique code assigned by the merchant to the plan in order to identify it. Alphanumeric. Min: 1 Max: 255. description: Plan description. Alphanumeric. Min: 1 Max: 255. ...
Below is the the instruction that describes the task: ### Input: Creating a new plan for subscriptions associated with the merchant. Args: plan_code: Unique code assigned by the merchant to the plan in order to identify it. Alphanumeric. Min: 1 Max: 255. description: P...
def parse_allele_name(name, species_prefix=None): """Takes an allele name and splits it into four parts: 1) species prefix 2) gene name 3) allele family 4) allele code If species_prefix is provided, that is used instead of getting the species prefix from the name. (And in th...
Takes an allele name and splits it into four parts: 1) species prefix 2) gene name 3) allele family 4) allele code If species_prefix is provided, that is used instead of getting the species prefix from the name. (And in that case, a species prefix in the name will result in an e...
Below is the the instruction that describes the task: ### Input: Takes an allele name and splits it into four parts: 1) species prefix 2) gene name 3) allele family 4) allele code If species_prefix is provided, that is used instead of getting the species prefix from the name. ...
def parse(code): """Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str) """ try: ast_tree = ast.parse(code) except Exception: raise RuntimeError('Bad Python code') transformer = Transformer() try: ...
Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str)
Below is the the instruction that describes the task: ### Input: Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str) ### Response: def parse(code): """Annotate user code. Return annotated code (str) if annotation detected; retur...
def _get_dependent_value(tag_values, dependent_tag_id): '''Extract (float) value of dependent tag or None if absent.''' try: values = tag_values[dependent_tag_id].split(",") return max([float(value) for value in values]) except KeyError: return None ex...
Extract (float) value of dependent tag or None if absent.
Below is the the instruction that describes the task: ### Input: Extract (float) value of dependent tag or None if absent. ### Response: def _get_dependent_value(tag_values, dependent_tag_id): '''Extract (float) value of dependent tag or None if absent.''' try: values = tag_values[depen...
def heartbeat_encode(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=2): ''' The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat f...
The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat further messages from this system appropriate (e.g. by laying out the user interface based on the autopilot)...
Below is the the instruction that describes the task: ### Input: The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat further messages from this system appropriate (e.g. by ...
def run(self): """ Copy the required directory to the build directory and super().run() """ self.announce("Moving scripts files", level=3) self.skip_build = True bin_dir = self.distribution.bin_dir scripts_dirs = [os.path.join(bin_dir, _dir) for _dir in ...
Copy the required directory to the build directory and super().run()
Below is the the instruction that describes the task: ### Input: Copy the required directory to the build directory and super().run() ### Response: def run(self): """ Copy the required directory to the build directory and super().run() """ self.announce("Moving scripts files", leve...
def upgrade(self, flag): """Upgrade Slackware binary packages with new """ for pkg in self.binary: try: subprocess.call("upgradepkg {0} {1}".format(flag, pkg), shell=True) check = pkg[:-4].split("/")[-1] ...
Upgrade Slackware binary packages with new
Below is the the instruction that describes the task: ### Input: Upgrade Slackware binary packages with new ### Response: def upgrade(self, flag): """Upgrade Slackware binary packages with new """ for pkg in self.binary: try: subprocess.call("upgradepkg {0} {1}"....
def monthly(date=datetime.date.today()): """ Take a date object and return the first day of the month. """ return datetime.date(date.year, date.month, 1)
Take a date object and return the first day of the month.
Below is the the instruction that describes the task: ### Input: Take a date object and return the first day of the month. ### Response: def monthly(date=datetime.date.today()): """ Take a date object and return the first day of the month. """ return datetime.date(date.year, date.month, 1)
def app_factory(global_settings, **local_settings): # pylint: disable=W0613 """ Default factory for creating a WSGI application using the everest configurator and root factory. :param dict global_settings: Global settings extracted from an ini file. Not used in this default app factory. :pa...
Default factory for creating a WSGI application using the everest configurator and root factory. :param dict global_settings: Global settings extracted from an ini file. Not used in this default app factory. :param dict local_settings: App settings extracted from an ini file.
Below is the the instruction that describes the task: ### Input: Default factory for creating a WSGI application using the everest configurator and root factory. :param dict global_settings: Global settings extracted from an ini file. Not used in this default app factory. :param dict local_sett...
def get_context_dict(self): """ return a context dict of the desired state """ context_dict = {} for s in self.sections(): for k, v in self.manifest.items(s): context_dict["%s:%s" % (s, k)] = v for k, v in self.inputs.values().items(): context_dict...
return a context dict of the desired state
Below is the the instruction that describes the task: ### Input: return a context dict of the desired state ### Response: def get_context_dict(self): """ return a context dict of the desired state """ context_dict = {} for s in self.sections(): for k, v in self.manifest.items(s)...
def plot_cadence_wheel( log, cadenceDictionary, pathToOutputPlotFolder): """ *Generate the cadence wheel for the survey* **Key Arguments:** - ``log`` -- logger - ``cadenceDictionary`` -- the cadence for the survey - ``pathToOutputPlotDirectory`` -- path to ad...
*Generate the cadence wheel for the survey* **Key Arguments:** - ``log`` -- logger - ``cadenceDictionary`` -- the cadence for the survey - ``pathToOutputPlotDirectory`` -- path to add plots to **Return:** - None
Below is the the instruction that describes the task: ### Input: *Generate the cadence wheel for the survey* **Key Arguments:** - ``log`` -- logger - ``cadenceDictionary`` -- the cadence for the survey - ``pathToOutputPlotDirectory`` -- path to add plots to **Return:** - No...
def _choose_node(self, nodes=None): """ Chooses a random node from the list of nodes in the client, taking into account each node's recent error rate. :rtype RiakNode """ if not nodes: nodes = self.nodes # Prefer nodes which have gone a reasonable tim...
Chooses a random node from the list of nodes in the client, taking into account each node's recent error rate. :rtype RiakNode
Below is the the instruction that describes the task: ### Input: Chooses a random node from the list of nodes in the client, taking into account each node's recent error rate. :rtype RiakNode ### Response: def _choose_node(self, nodes=None): """ Chooses a random node from the list o...
def get_context_data(self, **kwargs): """ Add error and pattern in context. """ context = super(BaseEntrySearch, self).get_context_data(**kwargs) context.update({'error': self.error, 'pattern': self.pattern}) return context
Add error and pattern in context.
Below is the the instruction that describes the task: ### Input: Add error and pattern in context. ### Response: def get_context_data(self, **kwargs): """ Add error and pattern in context. """ context = super(BaseEntrySearch, self).get_context_data(**kwargs) context.update({...
def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields...
Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (optional) Limit returned list length. :param page: (optional) Pa...
Below is the the instruction that describes the task: ### Input: Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (opt...
def ready_argument_list(self, arguments): """ready argument list to be passed to the C function :param arguments: List of arguments to be passed to the C function. The order should match the argument list on the C function. Allowed values are numpy.ndarray, and/or numpy.int32, n...
ready argument list to be passed to the C function :param arguments: List of arguments to be passed to the C function. The order should match the argument list on the C function. Allowed values are numpy.ndarray, and/or numpy.int32, numpy.float32, and so on. :type arguments: lis...
Below is the the instruction that describes the task: ### Input: ready argument list to be passed to the C function :param arguments: List of arguments to be passed to the C function. The order should match the argument list on the C function. Allowed values are numpy.ndarray, and/o...
def render(file): """Pretty print the JSON file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) json_data = json.loads(file_content, object_pairs_hook=OrderedDict) return json.dumps(json_data, ind...
Pretty print the JSON file for rendering.
Below is the the instruction that describes the task: ### Input: Pretty print the JSON file for rendering. ### Response: def render(file): """Pretty print the JSON file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(...