code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def convertPath(srcpath, dstdir): """Given `srcpath`, return a corresponding path within `dstdir`""" bits = srcpath.split("/") bits.pop(0) # Strip out leading 'unsigned' from paths like unsigned/update/win32/... if bits[0] == 'unsigned': bits.pop(0) return os.path.join(dstdir, *bits)
Given `srcpath`, return a corresponding path within `dstdir`
Below is the the instruction that describes the task: ### Input: Given `srcpath`, return a corresponding path within `dstdir` ### Response: def convertPath(srcpath, dstdir): """Given `srcpath`, return a corresponding path within `dstdir`""" bits = srcpath.split("/") bits.pop(0) # Strip out leading ...
def render_graph(result, cfg, **kwargs): """ Render to output a result that can be parsed as an RDF graph """ # Mapping from MIME types to formats accepted by RDFlib rdflib_formats = {'text/rdf+n3': 'n3', 'text/turtle': 'turtle', 'application/x-turtle': 't...
Render to output a result that can be parsed as an RDF graph
Below is the the instruction that describes the task: ### Input: Render to output a result that can be parsed as an RDF graph ### Response: def render_graph(result, cfg, **kwargs): """ Render to output a result that can be parsed as an RDF graph """ # Mapping from MIME types to formats accepted by ...
def _system_call(cmd, stdoutfilename=None): """Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfilename : str ...
Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfilename : str Name of the file to save stderr to or None ...
Below is the the instruction that describes the task: ### Input: Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfile...
def keywords(self): '''Generator which returns all keywords in the suite''' for table in self.tables: if isinstance(table, KeywordTable): for keyword in table.keywords: yield keyword
Generator which returns all keywords in the suite
Below is the the instruction that describes the task: ### Input: Generator which returns all keywords in the suite ### Response: def keywords(self): '''Generator which returns all keywords in the suite''' for table in self.tables: if isinstance(table, KeywordTable): for ...
def _parse_key_val(stream): """Parse key, value combination return (tuple): Parsed key (string) Parsed value (either a string, array, or dict) """ logger.debug("parsing key/val") key = _parse_key(stream) val = _parse_val(stream) logger.debug("parsed key/val") logger.deb...
Parse key, value combination return (tuple): Parsed key (string) Parsed value (either a string, array, or dict)
Below is the the instruction that describes the task: ### Input: Parse key, value combination return (tuple): Parsed key (string) Parsed value (either a string, array, or dict) ### Response: def _parse_key_val(stream): """Parse key, value combination return (tuple): Parsed key (...
def fCZ_std_errs(self): """ Get a dictionary of the standard errors of the CZ fidelities from the specs, keyed by targets (qubit-qubit pairs). :return: A dictionary of CZ fidelities, normalized to unity. :rtype: Dict[tuple(int, int), float] """ return {tuple(es.t...
Get a dictionary of the standard errors of the CZ fidelities from the specs, keyed by targets (qubit-qubit pairs). :return: A dictionary of CZ fidelities, normalized to unity. :rtype: Dict[tuple(int, int), float]
Below is the the instruction that describes the task: ### Input: Get a dictionary of the standard errors of the CZ fidelities from the specs, keyed by targets (qubit-qubit pairs). :return: A dictionary of CZ fidelities, normalized to unity. :rtype: Dict[tuple(int, int), float] ### Response:...
def _do_synchronise_jobs(walltime, machines): """ This returns a common reservation date for all the jobs. This reservation date is really only a hint and will be supplied to each oar server. Without this *common* reservation_date, one oar server can decide to postpone the start of the job while the ot...
This returns a common reservation date for all the jobs. This reservation date is really only a hint and will be supplied to each oar server. Without this *common* reservation_date, one oar server can decide to postpone the start of the job while the other are already running. But this doens't prevent ...
Below is the the instruction that describes the task: ### Input: This returns a common reservation date for all the jobs. This reservation date is really only a hint and will be supplied to each oar server. Without this *common* reservation_date, one oar server can decide to postpone the start of the j...
def process_all(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts`." if self.n_cpus <= 1: return self._process_all_1(texts) with ProcessPoolExecutor(self.n_cpus) as e: return sum(e.map(self._process_all_1, partition_by_cores(texts, self.n_cpus)), [])
Process a list of `texts`.
Below is the the instruction that describes the task: ### Input: Process a list of `texts`. ### Response: def process_all(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts`." if self.n_cpus <= 1: return self._process_all_1(texts) with ProcessPoolExecutor(self.n_cpus...
def read_core_registers_raw(self, reg_list): """ Read one or more core registers Read core registers in reg_list and return a list of values. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER. """ ...
Read one or more core registers Read core registers in reg_list and return a list of values. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER.
Below is the the instruction that describes the task: ### Input: Read one or more core registers Read core registers in reg_list and return a list of values. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER. ### Response:...
def neighbors(self, type=None, direction="to", failed=None): """Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" ...
Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" (default), "from", "either", or "both".
Below is the the instruction that describes the task: ### Input: Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" (...
def get_connections_by_dests(self, dests): '''Search for all connections involving this and all other ports.''' with self._mutex: res = [] for c in self.connections: if not c.has_port(self): continue has_dest = False ...
Search for all connections involving this and all other ports.
Below is the the instruction that describes the task: ### Input: Search for all connections involving this and all other ports. ### Response: def get_connections_by_dests(self, dests): '''Search for all connections involving this and all other ports.''' with self._mutex: res = [] ...
def delete(self, account_id, user_id): """ Only the primary on the account can add or remove user's access to an account :param account_id: int of the account_id for the account :param user_id: int of the user_id to grant access :return: Access dict """ retur...
Only the primary on the account can add or remove user's access to an account :param account_id: int of the account_id for the account :param user_id: int of the user_id to grant access :return: Access dict
Below is the the instruction that describes the task: ### Input: Only the primary on the account can add or remove user's access to an account :param account_id: int of the account_id for the account :param user_id: int of the user_id to grant access :return: Access dict ### Res...
def lloyd_aggregation(C, ratio=0.03, distance='unit', maxiter=10): """Aggregate nodes using Lloyd Clustering. Parameters ---------- C : csr_matrix strength of connection matrix ratio : scalar Fraction of the nodes which will be seeds. distance : ['unit','abs','inv',None] ...
Aggregate nodes using Lloyd Clustering. Parameters ---------- C : csr_matrix strength of connection matrix ratio : scalar Fraction of the nodes which will be seeds. distance : ['unit','abs','inv',None] Distance assigned to each edge of the graph G used in Lloyd clustering ...
Below is the the instruction that describes the task: ### Input: Aggregate nodes using Lloyd Clustering. Parameters ---------- C : csr_matrix strength of connection matrix ratio : scalar Fraction of the nodes which will be seeds. distance : ['unit','abs','inv',None] Dist...
def get_edge_type(self, edge_type): """Returns all edges with the specified edge type. Parameters ---------- edge_type : int An integer specifying what type of edges to return. Returns ------- out : list of 2-tuples A list of 2-tuples rep...
Returns all edges with the specified edge type. Parameters ---------- edge_type : int An integer specifying what type of edges to return. Returns ------- out : list of 2-tuples A list of 2-tuples representing the edges in the graph wi...
Below is the the instruction that describes the task: ### Input: Returns all edges with the specified edge type. Parameters ---------- edge_type : int An integer specifying what type of edges to return. Returns ------- out : list of 2-tuples ...
def object(self, session): '''Instance of :attr:`model_type` with id :attr:`object_id`.''' if not hasattr(self, '_object'): pkname = self.model_type._meta.pkname() query = session.query(self.model_type).filter(**{pkname: ...
Instance of :attr:`model_type` with id :attr:`object_id`.
Below is the the instruction that describes the task: ### Input: Instance of :attr:`model_type` with id :attr:`object_id`. ### Response: def object(self, session): '''Instance of :attr:`model_type` with id :attr:`object_id`.''' if not hasattr(self, '_object'): pkname = self.model_typ...
def __search_files(self, files): """ Searches in given files. :param files: Files. :type files: list """ for file in files: if self.__interrupt: return if not foundations.common.path_exists(file): continue ...
Searches in given files. :param files: Files. :type files: list
Below is the the instruction that describes the task: ### Input: Searches in given files. :param files: Files. :type files: list ### Response: def __search_files(self, files): """ Searches in given files. :param files: Files. :type files: list """ ...
def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_): """ KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param...
KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param s...
Below is the the instruction that describes the task: ### Input: KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A...
def get_similarity_measures(self): """Helper function for computing similarity measures.""" if not self.quiet: print print "Computing", self.current_similarity_measure, "similarity..." self.compute_similarity_scores()
Helper function for computing similarity measures.
Below is the the instruction that describes the task: ### Input: Helper function for computing similarity measures. ### Response: def get_similarity_measures(self): """Helper function for computing similarity measures.""" if not self.quiet: print print "Computing", self.curr...
def acell(self, label, value_render_option='FORMATTED_VALUE'): """Returns an instance of a :class:`gspread.models.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values sh...
Returns an instance of a :class:`gspread.models.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values should be rendered in the the output. Se...
Below is the the instruction that describes the task: ### Input: Returns an instance of a :class:`gspread.models.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values should ...
def DownloadFile(hUcs, source, destination): """ Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs. """ import urllib2 from sys import stdout from time import sleep httpAddress = "%s/%s" % (hUcs.Uri(),...
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs.
Below is the the instruction that describes the task: ### Input: Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs. ### Response: def DownloadFile(hUcs, source, destination): """ Method provides the function...
def debug_tag(self, tag): """Setter for the debug tag. By default, the tag is the serial of the device, but sometimes it may be more descriptive to use a different tag of the user's choice. Changing debug tag changes part of the prefix of debug info emitted by this object, like...
Setter for the debug tag. By default, the tag is the serial of the device, but sometimes it may be more descriptive to use a different tag of the user's choice. Changing debug tag changes part of the prefix of debug info emitted by this object, like log lines and the message of DeviceE...
Below is the the instruction that describes the task: ### Input: Setter for the debug tag. By default, the tag is the serial of the device, but sometimes it may be more descriptive to use a different tag of the user's choice. Changing debug tag changes part of the prefix of debug info emit...
def CirrusIamUserReady(iam_aws_id, iam_aws_secret): """ Returns true if provided IAM credentials are ready to use. """ is_ready = False try: s3 = core.CreateTestedS3Connection(iam_aws_id, iam_aws_secret) if s3: if core.CirrusAccessIdMetadata(s3, iam_aws_id).IsInitialized(): is_ready = True ...
Returns true if provided IAM credentials are ready to use.
Below is the the instruction that describes the task: ### Input: Returns true if provided IAM credentials are ready to use. ### Response: def CirrusIamUserReady(iam_aws_id, iam_aws_secret): """ Returns true if provided IAM credentials are ready to use. """ is_ready = False try: s3 = core.CreateTestedS3Co...
def _calc_size_stats(self): """ get the size in bytes and num records of the content """ self.total_records = 0 self.total_length = 0 self.total_nodes = 0 if type(self.content['data']) is dict: self.total_length += len(str(self.content['data'])) ...
get the size in bytes and num records of the content
Below is the the instruction that describes the task: ### Input: get the size in bytes and num records of the content ### Response: def _calc_size_stats(self): """ get the size in bytes and num records of the content """ self.total_records = 0 self.total_length = 0 s...
def activate(self, branches, exclusive=False): """ Activate branches Parameters ---------- branches : str or list branch or list of branches to activate exclusive : bool, optional (default=False) if True deactivate the remaining branches ...
Activate branches Parameters ---------- branches : str or list branch or list of branches to activate exclusive : bool, optional (default=False) if True deactivate the remaining branches
Below is the the instruction that describes the task: ### Input: Activate branches Parameters ---------- branches : str or list branch or list of branches to activate exclusive : bool, optional (default=False) if True deactivate the remaining branches ### Re...
def queue_it(queue=g_queue, **put_args): """ Wrapper. Instead of returning the result of the function, add it to a queue. .. code: python import reusables import queue my_queue = queue.Queue() @reusables.queue_it(my_queue) def func(a): return a ...
Wrapper. Instead of returning the result of the function, add it to a queue. .. code: python import reusables import queue my_queue = queue.Queue() @reusables.queue_it(my_queue) def func(a): return a func(10) print(my_queue.get()) # 1...
Below is the the instruction that describes the task: ### Input: Wrapper. Instead of returning the result of the function, add it to a queue. .. code: python import reusables import queue my_queue = queue.Queue() @reusables.queue_it(my_queue) def func(a): ...
def extract_causal_relations(self): """Extract causal relations as Statements.""" # Get the extractions that are labeled as directed and causal relations = [e for e in self.doc.extractions if 'DirectedRelation' in e['labels'] and 'Causal' in e['labels']]...
Extract causal relations as Statements.
Below is the the instruction that describes the task: ### Input: Extract causal relations as Statements. ### Response: def extract_causal_relations(self): """Extract causal relations as Statements.""" # Get the extractions that are labeled as directed and causal relations = [e for e in self...
def dump_np_vars(self, store_format='csv', delimiter=','): """ Dump the TDS simulation data to files by calling subroutines `write_lst` and `write_np_dat`. Parameters ----------- store_format : str dump format in `('csv', 'txt', 'hdf5')` delimiter :...
Dump the TDS simulation data to files by calling subroutines `write_lst` and `write_np_dat`. Parameters ----------- store_format : str dump format in `('csv', 'txt', 'hdf5')` delimiter : str delimiter for the `csv` and `txt` format Returns ...
Below is the the instruction that describes the task: ### Input: Dump the TDS simulation data to files by calling subroutines `write_lst` and `write_np_dat`. Parameters ----------- store_format : str dump format in `('csv', 'txt', 'hdf5')` delimiter : str ...
def calculateFields(self): """Write calculated fields for read buffer.""" pf1 = self.m_blk_b[Field.Cos_Theta_Ln_1][MeterData.StringValue] pf2 = self.m_blk_b[Field.Cos_Theta_Ln_2][MeterData.StringValue] pf3 = self.m_blk_b[Field.Cos_Theta_Ln_3][MeterData.StringValue] pf1_int = sel...
Write calculated fields for read buffer.
Below is the the instruction that describes the task: ### Input: Write calculated fields for read buffer. ### Response: def calculateFields(self): """Write calculated fields for read buffer.""" pf1 = self.m_blk_b[Field.Cos_Theta_Ln_1][MeterData.StringValue] pf2 = self.m_blk_b[Field.Cos_Thet...
def _find_files(dirpath: str) -> 'Iterable[str]': """Find files recursively. Returns a generator that yields paths in no particular order. """ for dirpath, dirnames, filenames in os.walk(dirpath, topdown=True, followlinks=True): if os.path.basenam...
Find files recursively. Returns a generator that yields paths in no particular order.
Below is the the instruction that describes the task: ### Input: Find files recursively. Returns a generator that yields paths in no particular order. ### Response: def _find_files(dirpath: str) -> 'Iterable[str]': """Find files recursively. Returns a generator that yields paths in no particular orde...
def _colors_to_code(self, fg_color, bg_color): " Return a tuple with the vt100 values that represent this color. " # When requesting ANSI colors only, and both fg/bg color were converted # to ANSI, ensure that the foreground and background color are not the # same. (Unless they were exp...
Return a tuple with the vt100 values that represent this color.
Below is the the instruction that describes the task: ### Input: Return a tuple with the vt100 values that represent this color. ### Response: def _colors_to_code(self, fg_color, bg_color): " Return a tuple with the vt100 values that represent this color. " # When requesting ANSI colors only, and...
def add_ip(self, family='IPv4'): """ Allocate a new (random) IP-address to the Server. """ IP = self.cloud_manager.attach_ip(self.uuid, family) self.ip_addresses.append(IP) return IP
Allocate a new (random) IP-address to the Server.
Below is the the instruction that describes the task: ### Input: Allocate a new (random) IP-address to the Server. ### Response: def add_ip(self, family='IPv4'): """ Allocate a new (random) IP-address to the Server. """ IP = self.cloud_manager.attach_ip(self.uuid, family) se...
def onMessage(self, payload, isBinary): """ Send the payload onto the {slack.[payload['type]'} channel. The message is transalated from IDs to human-readable identifiers. Note: The slack API only sends JSON, isBinary will always be false. """ msg = self.translate(unpack(...
Send the payload onto the {slack.[payload['type]'} channel. The message is transalated from IDs to human-readable identifiers. Note: The slack API only sends JSON, isBinary will always be false.
Below is the the instruction that describes the task: ### Input: Send the payload onto the {slack.[payload['type]'} channel. The message is transalated from IDs to human-readable identifiers. Note: The slack API only sends JSON, isBinary will always be false. ### Response: def onMessage(self, payl...
async def close_interface(self, conn_id, interface): """Close an interface on this IOTile device. See :meth:`AbstractDeviceAdapter.close_interface`. """ resp = await self._execute(self._adapter.close_interface_sync, conn_id, interface) _raise_error(conn_id, 'close_interface', r...
Close an interface on this IOTile device. See :meth:`AbstractDeviceAdapter.close_interface`.
Below is the the instruction that describes the task: ### Input: Close an interface on this IOTile device. See :meth:`AbstractDeviceAdapter.close_interface`. ### Response: async def close_interface(self, conn_id, interface): """Close an interface on this IOTile device. See :meth:`Abstract...
def hessianFreqs(self,jr,jphi,jz,**kwargs): """ NAME: hessianFreqs PURPOSE: return the Hessian d Omega / d J and frequencies Omega corresponding to a torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) jz...
NAME: hessianFreqs PURPOSE: return the Hessian d Omega / d J and frequencies Omega corresponding to a torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) tol= (object-wide value)...
Below is the the instruction that describes the task: ### Input: NAME: hessianFreqs PURPOSE: return the Hessian d Omega / d J and frequencies Omega corresponding to a torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) ...
def ds9_objects_to_string(regions, coordsys='fk5', fmt='.6f', radunit='deg'): """ Converts a `list` of `~regions.Region` to DS9 region string. Parameters ---------- regions : `list` List of `~regions.Region` objects coordsys : `str`, optional This overrides the coordinate system...
Converts a `list` of `~regions.Region` to DS9 region string. Parameters ---------- regions : `list` List of `~regions.Region` objects coordsys : `str`, optional This overrides the coordinate system frame for all regions. Default is 'fk5'. fmt : `str`, optional A pyth...
Below is the the instruction that describes the task: ### Input: Converts a `list` of `~regions.Region` to DS9 region string. Parameters ---------- regions : `list` List of `~regions.Region` objects coordsys : `str`, optional This overrides the coordinate system frame for all region...
def itemFromTag( self, tag ): """ Returns the item assigned to the given tag. :param tag | <str> :return <XMultiTagItem> || None """ for row in range(self.count() - 1): item = self.item(row) if ( item and item.t...
Returns the item assigned to the given tag. :param tag | <str> :return <XMultiTagItem> || None
Below is the the instruction that describes the task: ### Input: Returns the item assigned to the given tag. :param tag | <str> :return <XMultiTagItem> || None ### Response: def itemFromTag( self, tag ): """ Returns the item assigned to the given tag...
def _find_workflows(mcs, attrs): """Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects. """ workflows = {} for k, v in attrs.items(): if isinsta...
Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects.
Below is the the instruction that describes the task: ### Input: Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects. ### Response: def _find_workflows(mcs, attrs): """Find wor...
def sorted_migrations(self): """ Sort migrations if necessary and store in self._sorted_migrations """ if not self._sorted_migrations: self._sorted_migrations = sorted( self.migration_registry.items(), # sort on the key... the migration number ...
Sort migrations if necessary and store in self._sorted_migrations
Below is the the instruction that describes the task: ### Input: Sort migrations if necessary and store in self._sorted_migrations ### Response: def sorted_migrations(self): """ Sort migrations if necessary and store in self._sorted_migrations """ if not self._sorted_migrations: ...
def goto_time(timeval): '''Go to a specific time (in nanoseconds) in the current trajectory. ''' i = bisect.bisect(viewer.frame_times, timeval * 1000) goto_frame(i)
Go to a specific time (in nanoseconds) in the current trajectory.
Below is the the instruction that describes the task: ### Input: Go to a specific time (in nanoseconds) in the current trajectory. ### Response: def goto_time(timeval): '''Go to a specific time (in nanoseconds) in the current trajectory. ''' i = bisect.bisect(viewer.frame_times, timeval * 1000...
def create(*context, **kwargs): """ Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instanc...
Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instances. Here is an example illustrating various...
Below is the the instruction that describes the task: ### Input: Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain Con...
def coerce_many(schema=str): """Expect the input to be a sequence of items which conform to `schema`.""" def validate(val): """Apply schema check/version to each item.""" return [volup.Coerce(schema)(x) for x in val] return validate
Expect the input to be a sequence of items which conform to `schema`.
Below is the the instruction that describes the task: ### Input: Expect the input to be a sequence of items which conform to `schema`. ### Response: def coerce_many(schema=str): """Expect the input to be a sequence of items which conform to `schema`.""" def validate(val): """Apply schema check/vers...
def get_image_by_kind(self, kind): """ returns a image of a specific kind """ for ss in self.images: if ss.kind == kind: return ss return None
returns a image of a specific kind
Below is the the instruction that describes the task: ### Input: returns a image of a specific kind ### Response: def get_image_by_kind(self, kind): """ returns a image of a specific kind """ for ss in self.images: if ss.kind == kind: return ss return None
def sendCMD (self, vel): ''' Sends CMDVel. @param vel: CMDVel to publish @type vel: CMDVel ''' self.lock.acquire() self.vel = vel self.lock.release()
Sends CMDVel. @param vel: CMDVel to publish @type vel: CMDVel
Below is the the instruction that describes the task: ### Input: Sends CMDVel. @param vel: CMDVel to publish @type vel: CMDVel ### Response: def sendCMD (self, vel): ''' Sends CMDVel. @param vel: CMDVel to publish @type vel: CMDVel ''' self.lock....
def density_2d(self, x, y, rho0, Ra, Rs, center_x=0, center_y=0): """ projected density :param x: :param y: :param rho0: :param Ra: :param Rs: :param center_x: :param center_y: :return: """ Ra, Rs = self._sort_ra_rs(Ra, Rs) ...
projected density :param x: :param y: :param rho0: :param Ra: :param Rs: :param center_x: :param center_y: :return:
Below is the the instruction that describes the task: ### Input: projected density :param x: :param y: :param rho0: :param Ra: :param Rs: :param center_x: :param center_y: :return: ### Response: def density_2d(self, x, y, rho0, Ra, Rs, center_x=0, cen...
def page(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of FaxInstance records from the API. ...
Retrieve a single page of FaxInstance records from the API. Request is executed immediately :param unicode from_: Retrieve only those faxes sent from this phone number :param unicode to: Retrieve only those faxes sent to this phone number :param datetime date_created_on_or_before: Retri...
Below is the the instruction that describes the task: ### Input: Retrieve a single page of FaxInstance records from the API. Request is executed immediately :param unicode from_: Retrieve only those faxes sent from this phone number :param unicode to: Retrieve only those faxes sent to this ...
def lookup_field_label(self, context, field, default=None): """ Figures out what the field label should be for the passed in field name. We overload this so as to use our form to see if there is label set there. If so then we'll pass that as the default instead of having our parent der...
Figures out what the field label should be for the passed in field name. We overload this so as to use our form to see if there is label set there. If so then we'll pass that as the default instead of having our parent derive the field from the name.
Below is the the instruction that describes the task: ### Input: Figures out what the field label should be for the passed in field name. We overload this so as to use our form to see if there is label set there. If so then we'll pass that as the default instead of having our parent derive ...
def sentiment(self): """Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :rtype: named tuple of the form ``Senti...
Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :rtype: named tuple of the form ``Sentiment(polarity=0.0, subjectivity=...
Below is the the instruction that describes the task: ### Input: Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :r...
async def send(self, metric): """Transform metric to JSON bytestring and send to server. Args: metric (dict): Complete metric to send as JSON. """ message = json.dumps(metric).encode('utf-8') await self.loop.create_datagram_endpoint( lambda: UDPClientProt...
Transform metric to JSON bytestring and send to server. Args: metric (dict): Complete metric to send as JSON.
Below is the the instruction that describes the task: ### Input: Transform metric to JSON bytestring and send to server. Args: metric (dict): Complete metric to send as JSON. ### Response: async def send(self, metric): """Transform metric to JSON bytestring and send to server. ...
def _parse_depot_section(f): """Parse TSPLIB DEPOT_SECTION data part from file descriptor f Args ---- f : str File descriptor Returns ------- int an array of depots """ depots = [] for line in f: line = strip(line) if line == '-1' or line == ...
Parse TSPLIB DEPOT_SECTION data part from file descriptor f Args ---- f : str File descriptor Returns ------- int an array of depots
Below is the the instruction that describes the task: ### Input: Parse TSPLIB DEPOT_SECTION data part from file descriptor f Args ---- f : str File descriptor Returns ------- int an array of depots ### Response: def _parse_depot_section(f): """Parse TSPLIB DEPOT_SEC...
def pop_marker(self, reset): """ Pop a marker off of the marker stack. If reset is True then the iterator will be returned to the state it was in before the corresponding call to push_marker(). """ marker = self.markers.pop() if reset: # Make the values ava...
Pop a marker off of the marker stack. If reset is True then the iterator will be returned to the state it was in before the corresponding call to push_marker().
Below is the the instruction that describes the task: ### Input: Pop a marker off of the marker stack. If reset is True then the iterator will be returned to the state it was in before the corresponding call to push_marker(). ### Response: def pop_marker(self, reset): """ Pop a marker off o...
def close(self): '''Close Gdx file and free up resources.''' h = self.gdx_handle gdxcc.gdxClose(h) gdxcc.gdxFree(h)
Close Gdx file and free up resources.
Below is the the instruction that describes the task: ### Input: Close Gdx file and free up resources. ### Response: def close(self): '''Close Gdx file and free up resources.''' h = self.gdx_handle gdxcc.gdxClose(h) gdxcc.gdxFree(h)
def get_default_for(prop, value): """ Ensures complex property types have the correct default values """ prop = prop.strip('_') # Handle alternate props (leading underscores) val = reduce_value(value) # Filtering of value happens here if prop in _COMPLEX_LISTS: return wrap_value(val) ...
Ensures complex property types have the correct default values
Below is the the instruction that describes the task: ### Input: Ensures complex property types have the correct default values ### Response: def get_default_for(prop, value): """ Ensures complex property types have the correct default values """ prop = prop.strip('_') # Handle alternate props (leadin...
def identify_id(id: str) -> bool: """ Try to identify whether this is an ActivityPub ID. """ return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None
Try to identify whether this is an ActivityPub ID.
Below is the the instruction that describes the task: ### Input: Try to identify whether this is an ActivityPub ID. ### Response: def identify_id(id: str) -> bool: """ Try to identify whether this is an ActivityPub ID. """ return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None
def set_fc_volume(self, port_id, target_wwn, target_lun=0, boot_prio=1, initiator_wwnn=None, initiator_wwpn=None): """Set FibreChannel volume information to configuration. :param port_id: Physical port ID. :param target_wwn: WWN of target. :pa...
Set FibreChannel volume information to configuration. :param port_id: Physical port ID. :param target_wwn: WWN of target. :param target_lun: LUN number of target. :param boot_prio: Boot priority of the volume. 1 indicates the highest priority. :param initiator_wwn...
Below is the the instruction that describes the task: ### Input: Set FibreChannel volume information to configuration. :param port_id: Physical port ID. :param target_wwn: WWN of target. :param target_lun: LUN number of target. :param boot_prio: Boot priority of the volume. 1 indica...
def requestFields(self, field_names, required=False, strict=False): """Add the given list of fields to the request @param field_names: The simple registration data fields to request @type field_names: [str] @param required: Whether these values should be presented to the us...
Add the given list of fields to the request @param field_names: The simple registration data fields to request @type field_names: [str] @param required: Whether these values should be presented to the user as required @param strict: whether to raise an exception when a fie...
Below is the the instruction that describes the task: ### Input: Add the given list of fields to the request @param field_names: The simple registration data fields to request @type field_names: [str] @param required: Whether these values should be presented to the user as requ...
def is_py_script(filename): "Returns True if a file is a python executable." if not os.path.exists(filename) and os.path.isfile(filename): return False elif filename.endswith(".py"): return True elif not os.access(filename, os.X_OK): return False else: try: ...
Returns True if a file is a python executable.
Below is the the instruction that describes the task: ### Input: Returns True if a file is a python executable. ### Response: def is_py_script(filename): "Returns True if a file is a python executable." if not os.path.exists(filename) and os.path.isfile(filename): return False elif filename.end...
def _get_token(self, token, http_conn_id): """ Given either a manually set token or a conn_id, return the webhook_token to use :param token: The manually provided token :type token: str :param http_conn_id: The conn_id provided :type http_conn_id: str :return: web...
Given either a manually set token or a conn_id, return the webhook_token to use :param token: The manually provided token :type token: str :param http_conn_id: The conn_id provided :type http_conn_id: str :return: webhook_token (str) to use
Below is the the instruction that describes the task: ### Input: Given either a manually set token or a conn_id, return the webhook_token to use :param token: The manually provided token :type token: str :param http_conn_id: The conn_id provided :type http_conn_id: str :retur...
def _parse_docstring(docstring): """ Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse arguments. Any other text is combined and added to the ...
Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse arguments. Any other text is combined and added to the argparse description. example: \...
Below is the the instruction that describes the task: ### Input: Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse arguments. Any other text is co...
def cns_vwl_str_len_wb_sb(self): """ Return a new IPAString, containing only: 1. the consonants, 2. the vowels, and 3. the stress diacritics, 4. the length diacritics, 5. the word breaks, and 6. the syllable breaks in the current string. ...
Return a new IPAString, containing only: 1. the consonants, 2. the vowels, and 3. the stress diacritics, 4. the length diacritics, 5. the word breaks, and 6. the syllable breaks in the current string. :rtype: IPAString
Below is the the instruction that describes the task: ### Input: Return a new IPAString, containing only: 1. the consonants, 2. the vowels, and 3. the stress diacritics, 4. the length diacritics, 5. the word breaks, and 6. the syllable breaks in the ...
def name_match(self, wfn): """ Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :ret...
Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. ...
Below is the the instruction that describes the task: ### Input: Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CP...
def get_domain_connect_template_async_context(self, domain, provider_id, service_id, redirect_uri, params=None, state=None, service_id_in_path=False): """Makes full Domain Connect discovery of a domain and returns full context to request async consent. ...
Makes full Domain Connect discovery of a domain and returns full context to request async consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param service_id_in_path: bool ...
Below is the the instruction that describes the task: ### Input: Makes full Domain Connect discovery of a domain and returns full context to request async consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict ...
def get_file(self, file_key): '''Gets file information Args: file_key key for the file to get return (status code, dict of file info) ''' uri = '/'.join([ self.api_uri, self.files_suffix, file_key ]) return self._req('get', uri)
Gets file information Args: file_key key for the file to get return (status code, dict of file info)
Below is the the instruction that describes the task: ### Input: Gets file information Args: file_key key for the file to get return (status code, dict of file info) ### Response: def get_file(self, file_key): '''Gets file information Args: file_key key for the file to get return (status co...
def tuple(self): """ Tuple conversion to (value, dimensions), e.g.: (123, {dimension_1: "foo", dimension_2: "bar"}) """ return (self.value, {dv.id: dv.value for dv in self.dimensionvalues})
Tuple conversion to (value, dimensions), e.g.: (123, {dimension_1: "foo", dimension_2: "bar"})
Below is the the instruction that describes the task: ### Input: Tuple conversion to (value, dimensions), e.g.: (123, {dimension_1: "foo", dimension_2: "bar"}) ### Response: def tuple(self): """ Tuple conversion to (value, dimensions), e.g.: (123, {dimension_1: "foo", dimension_2: "bar"})...
def _parse_xmatch_catalog_header(xc, xk): ''' This parses the header for a catalog file and returns it as a file object. Parameters ---------- xc : str The file name of an xmatch catalog prepared previously. xk : list of str This is a list of column names to extract from the x...
This parses the header for a catalog file and returns it as a file object. Parameters ---------- xc : str The file name of an xmatch catalog prepared previously. xk : list of str This is a list of column names to extract from the xmatch catalog. Returns ------- tuple ...
Below is the the instruction that describes the task: ### Input: This parses the header for a catalog file and returns it as a file object. Parameters ---------- xc : str The file name of an xmatch catalog prepared previously. xk : list of str This is a list of column names to ext...
def pxconfig(self, line): """configure default targets/blocking for %px magics""" args = magic_arguments.parse_argstring(self.pxconfig, line) if args.targets: self.view.targets = self._eval_target_str(args.targets) if args.block is not None: self.view.block = args...
configure default targets/blocking for %px magics
Below is the the instruction that describes the task: ### Input: configure default targets/blocking for %px magics ### Response: def pxconfig(self, line): """configure default targets/blocking for %px magics""" args = magic_arguments.parse_argstring(self.pxconfig, line) if args.targets: ...
def _split_cluster_by_most_vote(c, p): """split cluster by most-vote strategy""" old, new = c[p[0]], c[p[1]] old_size = _get_seqs(old) new_size = _get_seqs(new) logger.debug("_most_vote: size of %s with %s - %s with %s" % (old.id, len(old_size), new.id, len(new_size))) if len(old_size) > len(new...
split cluster by most-vote strategy
Below is the the instruction that describes the task: ### Input: split cluster by most-vote strategy ### Response: def _split_cluster_by_most_vote(c, p): """split cluster by most-vote strategy""" old, new = c[p[0]], c[p[1]] old_size = _get_seqs(old) new_size = _get_seqs(new) logger.debug("_most...
def _bstar_set(beta, alpha, yTBy, yTBX, yTBM, XTBX, XTBM, MTBM): """ Compute -2𝐲ᵀBEⱼ𝐛ⱼ + (𝐛ⱼEⱼ)ᵀBEⱼ𝐛ⱼ. For 𝐛ⱼ = [𝜷ⱼᵀ 𝜶ⱼᵀ]ᵀ. """ from numpy_sugar import epsilon r = yTBy r -= 2 * add.reduce([i @ beta for i in yTBX]) r -= 2 * add.reduce([i @ alpha for i in yTBM]) r += add.redu...
Compute -2𝐲ᵀBEⱼ𝐛ⱼ + (𝐛ⱼEⱼ)ᵀBEⱼ𝐛ⱼ. For 𝐛ⱼ = [𝜷ⱼᵀ 𝜶ⱼᵀ]ᵀ.
Below is the the instruction that describes the task: ### Input: Compute -2𝐲ᵀBEⱼ𝐛ⱼ + (𝐛ⱼEⱼ)ᵀBEⱼ𝐛ⱼ. For 𝐛ⱼ = [𝜷ⱼᵀ 𝜶ⱼᵀ]ᵀ. ### Response: def _bstar_set(beta, alpha, yTBy, yTBX, yTBM, XTBX, XTBM, MTBM): """ Compute -2𝐲ᵀBEⱼ𝐛ⱼ + (𝐛ⱼEⱼ)ᵀBEⱼ𝐛ⱼ. For 𝐛ⱼ = [𝜷ⱼᵀ 𝜶ⱼᵀ]ᵀ. """ from numpy_su...
def get_parquet_metadata( self, path='.' ): """ OUTPUT PARQUET METADATA COLUMNS :param path: FOR INTERNAL USE :return: LIST OF SchemaElement """ children = [] for name, child_schema in sort_using_key(self.more.items(), lambda p: p[0]): ...
OUTPUT PARQUET METADATA COLUMNS :param path: FOR INTERNAL USE :return: LIST OF SchemaElement
Below is the the instruction that describes the task: ### Input: OUTPUT PARQUET METADATA COLUMNS :param path: FOR INTERNAL USE :return: LIST OF SchemaElement ### Response: def get_parquet_metadata( self, path='.' ): """ OUTPUT PARQUET METADATA COLUMNS :pa...
def _check_args(logZ, f, x, samples, weights): """ Sanity-check the arguments for :func:`fgivenx.drivers.compute_samples`. Parameters ---------- f, x, samples, weights: see arguments for :func:`fgivenx.drivers.compute_samples` """ # convert to arrays if logZ is None: logZ = ...
Sanity-check the arguments for :func:`fgivenx.drivers.compute_samples`. Parameters ---------- f, x, samples, weights: see arguments for :func:`fgivenx.drivers.compute_samples`
Below is the the instruction that describes the task: ### Input: Sanity-check the arguments for :func:`fgivenx.drivers.compute_samples`. Parameters ---------- f, x, samples, weights: see arguments for :func:`fgivenx.drivers.compute_samples` ### Response: def _check_args(logZ, f, x, samples, we...
def _pre_analysis(self): """ Executed before analysis starts. Necessary initializations are performed here. :return: None """ l.debug("Starting from %#x", self._start) # initialize the task stack self._task_stack = [ ] # initialize the execution counte...
Executed before analysis starts. Necessary initializations are performed here. :return: None
Below is the the instruction that describes the task: ### Input: Executed before analysis starts. Necessary initializations are performed here. :return: None ### Response: def _pre_analysis(self): """ Executed before analysis starts. Necessary initializations are performed here. :...
def scan(self, cursor=0, match=None, count=None): """ Incrementally return lists of key names. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns """ piece...
Incrementally return lists of key names. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns
Below is the the instruction that describes the task: ### Input: Incrementally return lists of key names. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ### Response: def scan(se...
def make_public(self, client=None): """Update blob's ACL, granting read access to anonymous users. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to th...
Update blob's ACL, granting read access to anonymous users. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the blob's bucket.
Below is the the instruction that describes the task: ### Input: Update blob's ACL, granting read access to anonymous users. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back ...
def fold_all(self): """Folds/unfolds all levels in the editor""" line_count = self.GetLineCount() expanding = True # find out if we are folding or unfolding for line_num in range(line_count): if self.GetFoldLevel(line_num) & stc.STC_FOLDLEVELHEADERFLAG: ...
Folds/unfolds all levels in the editor
Below is the the instruction that describes the task: ### Input: Folds/unfolds all levels in the editor ### Response: def fold_all(self): """Folds/unfolds all levels in the editor""" line_count = self.GetLineCount() expanding = True # find out if we are folding or unfolding ...
def tokenize(self, line: str, expand: bool = True) -> List[str]: """ Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed :param line: the command line being lexed :param expand: If True, then aliases and shortcuts will be expanded. ...
Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed :param line: the command line being lexed :param expand: If True, then aliases and shortcuts will be expanded. Set this to False if no expansion should occur because the command name i...
Below is the the instruction that describes the task: ### Input: Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed :param line: the command line being lexed :param expand: If True, then aliases and shortcuts will be expanded. Set ...
def get_default_config(self): """ Returns the default collector settings """ config = super(PostqueueCollector, self).get_default_config() config.update({ 'path': 'postqueue', 'bin': '/usr/bin/postqueue', 'use_sudo': ...
Returns the default collector settings
Below is the the instruction that describes the task: ### Input: Returns the default collector settings ### Response: def get_default_config(self): """ Returns the default collector settings """ config = super(PostqueueCollector, self).get_default_config() config.update({ ...
def sim_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False): """Return the Monge-Elkan similarity of two strings. This is a wrapper for :py:meth:`MongeElkan.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison ...
Return the Monge-Elkan similarity of two strings. This is a wrapper for :py:meth:`MongeElkan.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison sim_func : function Rhe internal similarity metric to employ symmet...
Below is the the instruction that describes the task: ### Input: Return the Monge-Elkan similarity of two strings. This is a wrapper for :py:meth:`MongeElkan.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison sim_func :...
def _make_query_from_terms(self, terms, limit=None): """ Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple of (TextClause, dict): First element is FTS query, second is parameters of the quer...
Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple of (TextClause, dict): First element is FTS query, second is parameters of the query. Element of the execution of the query is pair: (vid, score).
Below is the the instruction that describes the task: ### Input: Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple of (TextClause, dict): First element is FTS query, second is parameters of the ...
def mark_featured(self, request, queryset): """ Mark selected as featured post. """ queryset.update(featured=True) self.message_user( request, _('Selected entries are now marked as featured.'))
Mark selected as featured post.
Below is the the instruction that describes the task: ### Input: Mark selected as featured post. ### Response: def mark_featured(self, request, queryset): """ Mark selected as featured post. """ queryset.update(featured=True) self.message_user( request, _('Select...
def save_data(self, trigger_id, **data): """ get the data from the service :param trigger_id: id of the trigger :params data, dict :rtype: dict """ status = False service = TriggerService.objects.get(id=trigger_id) desc = service.d...
get the data from the service :param trigger_id: id of the trigger :params data, dict :rtype: dict
Below is the the instruction that describes the task: ### Input: get the data from the service :param trigger_id: id of the trigger :params data, dict :rtype: dict ### Response: def save_data(self, trigger_id, **data): """ get the data from the service ...
def list_records_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords for a given BuildConfiguration """ data = list_records_for_build_configuration_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_l...
List all BuildRecords for a given BuildConfiguration
Below is the the instruction that describes the task: ### Input: List all BuildRecords for a given BuildConfiguration ### Response: def list_records_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords for a given BuildConfiguration """ ...
def smoothing(labels, smoothing_window): """ Applies a smoothing on VAD""" if numpy.sum(labels)< smoothing_window: return labels segments = [] for k in range(1,len(labels)-1): if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 : labels[k]=1 for k in range(1,len(labels)-1): if labels[k]==...
Applies a smoothing on VAD
Below is the the instruction that describes the task: ### Input: Applies a smoothing on VAD ### Response: def smoothing(labels, smoothing_window): """ Applies a smoothing on VAD""" if numpy.sum(labels)< smoothing_window: return labels segments = [] for k in range(1,len(labels)-1): if labels[k]==0 ...
def sendLocalVoiceClips( self, clip_paths, message=None, thread_id=None, thread_type=ThreadType.USER ): """ Sends local voice clips to a thread :param clip_paths: Paths of clips to upload and send :param message: Additional message :param thread_id: User/Group ID to ...
Sends local voice clips to a thread :param clip_paths: Paths of clips to upload and send :param message: Additional message :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` :type thread_type: models.ThreadType ...
Below is the the instruction that describes the task: ### Input: Sends local voice clips to a thread :param clip_paths: Paths of clips to upload and send :param message: Additional message :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :...
def get_file_network_traffic(self, resources): """Retrieves a report about the network traffic of a md5, sha1, and/or sha2 hash of file, when it is executed. Args: resources: list of string hashes. """ api_name = 'virustotal-file-network-traffic' api_endpo...
Retrieves a report about the network traffic of a md5, sha1, and/or sha2 hash of file, when it is executed. Args: resources: list of string hashes.
Below is the the instruction that describes the task: ### Input: Retrieves a report about the network traffic of a md5, sha1, and/or sha2 hash of file, when it is executed. Args: resources: list of string hashes. ### Response: def get_file_network_traffic(self, resources): "...
def refactor_docstring(self, input, filename): """Refactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be continued with "..." prompts, as long as the "..." is indented ...
Refactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be continued with "..." prompts, as long as the "..." is indented the same as the ">>>". (Unfortunately we can't us...
Below is the the instruction that describes the task: ### Input: Refactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be continued with "..." prompts, as long as the "..." is indent...
def init_board(self): """Init a valid board by given settings. Parameters ---------- mine_map : numpy.ndarray the map that defines the mine 0 is empty, 1 is mine info_map : numpy.ndarray the map that presents to gamer 0-8 is number...
Init a valid board by given settings. Parameters ---------- mine_map : numpy.ndarray the map that defines the mine 0 is empty, 1 is mine info_map : numpy.ndarray the map that presents to gamer 0-8 is number of mines in srrounding. ...
Below is the the instruction that describes the task: ### Input: Init a valid board by given settings. Parameters ---------- mine_map : numpy.ndarray the map that defines the mine 0 is empty, 1 is mine info_map : numpy.ndarray the map that present...
def _register_rp(session, url_prefix, rp_name): """Synchronously register the RP is paremeter. Return False if we have a reason to believe this didn't work """ post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name) get_url = "{}providers/{}?api-version=2016-02-0...
Synchronously register the RP is paremeter. Return False if we have a reason to believe this didn't work
Below is the the instruction that describes the task: ### Input: Synchronously register the RP is paremeter. Return False if we have a reason to believe this didn't work ### Response: def _register_rp(session, url_prefix, rp_name): """Synchronously register the RP is paremeter. Return False i...
def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ if inspect.isclass(value): cls = value else: cls = value.__class__ if ...
Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name
Below is the the instruction that describes the task: ### Input: Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name ### Response: def type_name(value): """ Returns a user-readable...
def patched_forkpty(self): """Fork a new process with a new pseudo-terminal as controlling tty.""" pid, master_fd = self.original_os_forkpty() if not pid: _LOG('Fork detected. Reinstalling Manhole.') self.reinstall() return pid, master_fd
Fork a new process with a new pseudo-terminal as controlling tty.
Below is the the instruction that describes the task: ### Input: Fork a new process with a new pseudo-terminal as controlling tty. ### Response: def patched_forkpty(self): """Fork a new process with a new pseudo-terminal as controlling tty.""" pid, master_fd = self.original_os_forkpty() if ...
def check_pkgs_integrity(filelist, logger, ftp_connector, timeout=120, sleep_time=10): """ Checks if files are not being uploaded to server. @timeout - time after which the script will register an error. """ ref_1 = [] ref_2 = [] i = 1 print >> sys.stdout, "\nChe...
Checks if files are not being uploaded to server. @timeout - time after which the script will register an error.
Below is the the instruction that describes the task: ### Input: Checks if files are not being uploaded to server. @timeout - time after which the script will register an error. ### Response: def check_pkgs_integrity(filelist, logger, ftp_connector, timeout=120, sleep_time=10): """...
def request(self, method, *, path=None, json=None, params=None, headers=None, timeout=None, backoff_cap=None, **kwargs): """Performs an HTTP request with the given parameters. Implements exponential backoff. If `ConnectionError` occurs, a timestamp equal t...
Performs an HTTP request with the given parameters. Implements exponential backoff. If `ConnectionError` occurs, a timestamp equal to now + the default delay (`BACKOFF_DELAY`) is assigned to the object. The timestamp is in UTC. Next time the function is called, it either ...
Below is the the instruction that describes the task: ### Input: Performs an HTTP request with the given parameters. Implements exponential backoff. If `ConnectionError` occurs, a timestamp equal to now + the default delay (`BACKOFF_DELAY`) is assigned to the object. Th...
def _setSolidEdgeGeometry(self): """Sets the solid edge line geometry if needed""" if self._lineLengthEdge is not None: cr = self.contentsRect() # contents margin usually gives 1 # cursor rectangle left edge for the very first character usually # gives 4 ...
Sets the solid edge line geometry if needed
Below is the the instruction that describes the task: ### Input: Sets the solid edge line geometry if needed ### Response: def _setSolidEdgeGeometry(self): """Sets the solid edge line geometry if needed""" if self._lineLengthEdge is not None: cr = self.contentsRect() # cont...
def makeProducer(self, request, fileForReading): """ Make a L{StaticProducer} that will produce the body of this response. This method will also set the response code and Content-* headers. @param request: The L{Request} object. @param fileForReading: The file object containing...
Make a L{StaticProducer} that will produce the body of this response. This method will also set the response code and Content-* headers. @param request: The L{Request} object. @param fileForReading: The file object containing the resource. @return: A L{StaticProducer}. Calling C{.star...
Below is the the instruction that describes the task: ### Input: Make a L{StaticProducer} that will produce the body of this response. This method will also set the response code and Content-* headers. @param request: The L{Request} object. @param fileForReading: The file object containing...
def import_yaml(file_name, **kwargs): """ Imports curves and surfaces from files in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :para...
Imports curves and surfaces from files in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type ...
Below is the the instruction that describes the task: ### Input: Imports curves and surfaces from files in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation ...
def setDisabledAlternateColor(self, color): """ Sets the alternate color used when drawing this node as disabled. :param color | <QColor> """ color = QColor(color) if self._palette is None: self._palette = XNodePalette(self._scenePalette) ...
Sets the alternate color used when drawing this node as disabled. :param color | <QColor>
Below is the the instruction that describes the task: ### Input: Sets the alternate color used when drawing this node as disabled. :param color | <QColor> ### Response: def setDisabledAlternateColor(self, color): """ Sets the alternate color used when drawing this node as disa...
def remote_file(self, branch='master', filename=''): """Read the remote file on Git Server. Args: branch (str): Git Branch to find file. filename (str): Name of file to retrieve relative to root of repository. Returns: str: Contents of remote...
Read the remote file on Git Server. Args: branch (str): Git Branch to find file. filename (str): Name of file to retrieve relative to root of repository. Returns: str: Contents of remote file. Raises: FileNotFoundError: Requested...
Below is the the instruction that describes the task: ### Input: Read the remote file on Git Server. Args: branch (str): Git Branch to find file. filename (str): Name of file to retrieve relative to root of repository. Returns: str: Contents of r...
def build_if_needed(db): """Little helper method for making tables in SQL-Alchemy with SQLite""" if len(db.engine.table_names()) == 0: # import all classes here from my_site.models.tables.user import User db.create_all()
Little helper method for making tables in SQL-Alchemy with SQLite
Below is the the instruction that describes the task: ### Input: Little helper method for making tables in SQL-Alchemy with SQLite ### Response: def build_if_needed(db): """Little helper method for making tables in SQL-Alchemy with SQLite""" if len(db.engine.table_names()) == 0: # import all classe...
def _start(self): """ Starts the instantiation queue (called by its bundle activator) """ try: # Try to register to factory events with use_ipopo(self.__context) as ipopo: ipopo.add_listener(self) except BundleException: # Servi...
Starts the instantiation queue (called by its bundle activator)
Below is the the instruction that describes the task: ### Input: Starts the instantiation queue (called by its bundle activator) ### Response: def _start(self): """ Starts the instantiation queue (called by its bundle activator) """ try: # Try to register to factory even...
def parse_cookie(self, string): ''' Parses a cookie string like returned in a Set-Cookie header @param string: The cookie string @return: the cookie dict ''' results = re.findall('([^=]+)=([^\;]+);?\s?', string) my_dict = {} for item in results: ...
Parses a cookie string like returned in a Set-Cookie header @param string: The cookie string @return: the cookie dict
Below is the the instruction that describes the task: ### Input: Parses a cookie string like returned in a Set-Cookie header @param string: The cookie string @return: the cookie dict ### Response: def parse_cookie(self, string): ''' Parses a cookie string like returned in a Set-Cook...
def run(self, fnames=None): """Run Python scripts""" if fnames is None: fnames = self.get_selected_filenames() for fname in fnames: self.sig_run.emit(fname)
Run Python scripts
Below is the the instruction that describes the task: ### Input: Run Python scripts ### Response: def run(self, fnames=None): """Run Python scripts""" if fnames is None: fnames = self.get_selected_filenames() for fname in fnames: self.sig_run.emit(fname)
def static_rev(path): """ Gets a joined path with the STATIC_URL setting, and applies revisioning depending on DEBUG setting. Usage:: {% load rev %} {% static_rev "css/base.css" %} Example:: {% static_rev "css/base.css" %} On DEBUG=True will return: /static/css/base...
Gets a joined path with the STATIC_URL setting, and applies revisioning depending on DEBUG setting. Usage:: {% load rev %} {% static_rev "css/base.css" %} Example:: {% static_rev "css/base.css" %} On DEBUG=True will return: /static/css/base.css?d9wdjs On DEBUG=False...
Below is the the instruction that describes the task: ### Input: Gets a joined path with the STATIC_URL setting, and applies revisioning depending on DEBUG setting. Usage:: {% load rev %} {% static_rev "css/base.css" %} Example:: {% static_rev "css/base.css" %} On DEBUG...