code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _draw_polygons(self, feature, bg, colour, extent, polygons, xo, yo): """Draw a set of polygons from a vector tile.""" coords = [] for polygon in polygons: coords.append([self._scale_coords(x, y, extent, xo, yo) for x, y in polygon]) # Polygons are expensive to draw and th...
Draw a set of polygons from a vector tile.
Below is the the instruction that describes the task: ### Input: Draw a set of polygons from a vector tile. ### Response: def _draw_polygons(self, feature, bg, colour, extent, polygons, xo, yo): """Draw a set of polygons from a vector tile.""" coords = [] for polygon in polygons: ...
def Define_TreeTable(self, heads, heads2=None): ''' Define a TreeTable with a heading row and optionally a second heading row. ''' display_heads = [] display_heads.append(tuple(heads[2:])) self.tree_table = TreeTable() self.tree_table.append_from_list(display_...
Define a TreeTable with a heading row and optionally a second heading row.
Below is the the instruction that describes the task: ### Input: Define a TreeTable with a heading row and optionally a second heading row. ### Response: def Define_TreeTable(self, heads, heads2=None): ''' Define a TreeTable with a heading row and optionally a second heading row. ...
def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) re...
Acquires & releases a interprocess lock around call into decorated function.
Below is the the instruction that describes the task: ### Input: Acquires & releases a interprocess lock around call into decorated function. ### Response: def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLoc...
def _merge_fields(a, b): """Merge two lists of fields. Fields in `b` override fields in `a`. Fields in `a` are output first. """ a_names = set(x[0] for x in a) b_names = set(x[0] for x in b) a_keep = a_names - b_names fields = [] for name, field in a: if name in a_keep: ...
Merge two lists of fields. Fields in `b` override fields in `a`. Fields in `a` are output first.
Below is the the instruction that describes the task: ### Input: Merge two lists of fields. Fields in `b` override fields in `a`. Fields in `a` are output first. ### Response: def _merge_fields(a, b): """Merge two lists of fields. Fields in `b` override fields in `a`. Fields in `a` are output first. ...
def set_params_value(self, *params): """ This interface is used to set parameter value for an function in abi file. """ if len(params) != len(self.parameters): raise Exception("parameter error") temp = self.parameters self.parameters = [] for i in rang...
This interface is used to set parameter value for an function in abi file.
Below is the the instruction that describes the task: ### Input: This interface is used to set parameter value for an function in abi file. ### Response: def set_params_value(self, *params): """ This interface is used to set parameter value for an function in abi file. """ if len(pa...
def get_all_loopbacks(engine): """ Get all loopback interfaces for a given engine """ data = [] if 'fw_cluster' in engine.type: for cvi in engine.data.get('loopback_cluster_virtual_interface', []): data.append( LoopbackClusterInterface(cvi, engine)) for node ...
Get all loopback interfaces for a given engine
Below is the the instruction that describes the task: ### Input: Get all loopback interfaces for a given engine ### Response: def get_all_loopbacks(engine): """ Get all loopback interfaces for a given engine """ data = [] if 'fw_cluster' in engine.type: for cvi in engine.data.get('loopb...
def run(command, encoding=None, decode=True, cwd=None): """Run a command [cmd, arg1, arg2, ...]. Returns the output (stdout + stderr). Raises CommandFailed in cases of error. """ if not encoding: encoding = locale.getpreferredencoding() try: with open(os.devnull, 'rb') as devnu...
Run a command [cmd, arg1, arg2, ...]. Returns the output (stdout + stderr). Raises CommandFailed in cases of error.
Below is the the instruction that describes the task: ### Input: Run a command [cmd, arg1, arg2, ...]. Returns the output (stdout + stderr). Raises CommandFailed in cases of error. ### Response: def run(command, encoding=None, decode=True, cwd=None): """Run a command [cmd, arg1, arg2, ...]. Retu...
def guest_reboot(self, userid): """Reboot a guest vm.""" LOG.info("Begin to reboot vm %s", userid) self._smtclient.guest_reboot(userid) LOG.info("Complete reboot vm %s", userid)
Reboot a guest vm.
Below is the the instruction that describes the task: ### Input: Reboot a guest vm. ### Response: def guest_reboot(self, userid): """Reboot a guest vm.""" LOG.info("Begin to reboot vm %s", userid) self._smtclient.guest_reboot(userid) LOG.info("Complete reboot vm %s", userid)
def currentPixmapRect(self): """ Returns the rect that defines the boundary for the current pixmap based on the size of the button and the size of the pixmap. :return <QtCore.QRect> """ pixmap = self.currentPixmap() rect = self.rect() ...
Returns the rect that defines the boundary for the current pixmap based on the size of the button and the size of the pixmap. :return <QtCore.QRect>
Below is the the instruction that describes the task: ### Input: Returns the rect that defines the boundary for the current pixmap based on the size of the button and the size of the pixmap. :return <QtCore.QRect> ### Response: def currentPixmapRect(self): """ Retu...
def getp(self, name): """ Get the named parameter. Parameters ---------- name : string The parameter name. Returns ------- param : The parameter object. """ name = self._mapping.get(name,name) return self...
Get the named parameter. Parameters ---------- name : string The parameter name. Returns ------- param : The parameter object.
Below is the the instruction that describes the task: ### Input: Get the named parameter. Parameters ---------- name : string The parameter name. Returns ------- param : The parameter object. ### Response: def getp(self, name): """ ...
def update(self, volume, display_name=None, display_description=None): """ Update the specified values on the specified volume. You may specify one or more values to update. If no values are specified as non-None, the call is a no-op; no exception will be raised. """ retu...
Update the specified values on the specified volume. You may specify one or more values to update. If no values are specified as non-None, the call is a no-op; no exception will be raised.
Below is the the instruction that describes the task: ### Input: Update the specified values on the specified volume. You may specify one or more values to update. If no values are specified as non-None, the call is a no-op; no exception will be raised. ### Response: def update(self, volume, displa...
def build_year(self, dt): """ Build the page for the provided year. """ self.year = str(dt.year) logger.debug("Building %s" % self.year) self.request = self.create_request(self.get_url()) target_path = self.get_build_path() self.build_file(target_path, sel...
Build the page for the provided year.
Below is the the instruction that describes the task: ### Input: Build the page for the provided year. ### Response: def build_year(self, dt): """ Build the page for the provided year. """ self.year = str(dt.year) logger.debug("Building %s" % self.year) self.request ...
def mgz_to_nifti(filename,prefix=None,gzip=True): '''Convert ``filename`` to a NIFTI file using ``mri_convert``''' setup_freesurfer() if prefix==None: prefix = nl.prefix(filename) + '.nii' if gzip and not prefix.endswith('.gz'): prefix += '.gz' nl.run([os.path.join(freesurfer_home,'b...
Convert ``filename`` to a NIFTI file using ``mri_convert``
Below is the the instruction that describes the task: ### Input: Convert ``filename`` to a NIFTI file using ``mri_convert`` ### Response: def mgz_to_nifti(filename,prefix=None,gzip=True): '''Convert ``filename`` to a NIFTI file using ``mri_convert``''' setup_freesurfer() if prefix==None: prefix...
def _set_cfg(self, v, load=False): """ Setter method for cfg, mapped from YANG variable /zoning/defined_configuration/cfg (list) If this variable is read-only (config: false) in the source YANG file, then _set_cfg is considered as a private method. Backends looking to populate this variable should ...
Setter method for cfg, mapped from YANG variable /zoning/defined_configuration/cfg (list) If this variable is read-only (config: false) in the source YANG file, then _set_cfg is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cfg() directl...
Below is the the instruction that describes the task: ### Input: Setter method for cfg, mapped from YANG variable /zoning/defined_configuration/cfg (list) If this variable is read-only (config: false) in the source YANG file, then _set_cfg is considered as a private method. Backends looking to populate ...
def _create_query(node, context): """Create a query from a SqlNode. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Selectable, selectable of the generated query. """ visited_nodes = [node] output_colum...
Create a query from a SqlNode. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Selectable, selectable of the generated query.
Below is the the instruction that describes the task: ### Input: Create a query from a SqlNode. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Selectable, selectable of the generated query. ### Response: def _cre...
def as_number(self): """ >>> round(SummableVersion('1.9.3').as_number(), 12) 1.93 """ def combine(subver, ver): return subver / 10 + ver return reduce(combine, reversed(self.version))
>>> round(SummableVersion('1.9.3').as_number(), 12) 1.93
Below is the the instruction that describes the task: ### Input: >>> round(SummableVersion('1.9.3').as_number(), 12) 1.93 ### Response: def as_number(self): """ >>> round(SummableVersion('1.9.3').as_number(), 12) 1.93 """ def combine(subver, ver): return subver / 10 + ver return reduce(combine, re...
def help_cli_search(self): """ Help for Workbench CLI Search """ help = '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green) help += '\n\n\t%sSearch for all samples in the database that are known bad pe files,' % (color.Green) help += '\...
Help for Workbench CLI Search
Below is the the instruction that describes the task: ### Input: Help for Workbench CLI Search ### Response: def help_cli_search(self): """ Help for Workbench CLI Search """ help = '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green) help +=...
def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''): ''' Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label...
Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label (str): x-axis label. y_label (str): y-axis label.
Below is the the instruction that describes the task: ### Input: Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label (str): x...
def _get_status_tokens(self): " The tokens for the status bar. " result = [] # Display panes. for i, w in enumerate(self.pymux.arrangement.windows): if i > 0: result.append(('', ' ')) if w == self.pymux.arrangement.get_active_window(): ...
The tokens for the status bar.
Below is the the instruction that describes the task: ### Input: The tokens for the status bar. ### Response: def _get_status_tokens(self): " The tokens for the status bar. " result = [] # Display panes. for i, w in enumerate(self.pymux.arrangement.windows): if i > 0: ...
def _build_contract_creation_tx_with_valid_signature(self, tx_dict: Dict[str, None], s: int) -> Transaction: """ Use pyethereum `Transaction` to generate valid tx using a random signature :param tx_dict: Web3 tx dictionary :param s: Signature s value :return: PyEthereum creation ...
Use pyethereum `Transaction` to generate valid tx using a random signature :param tx_dict: Web3 tx dictionary :param s: Signature s value :return: PyEthereum creation tx for the proxy contract
Below is the the instruction that describes the task: ### Input: Use pyethereum `Transaction` to generate valid tx using a random signature :param tx_dict: Web3 tx dictionary :param s: Signature s value :return: PyEthereum creation tx for the proxy contract ### Response: def _build_contract...
def getAllConfig(self, fmt='json'): """ return all element configurations as json string file. could be further processed by beamline.Lattice class :param fmt: 'json' (default) or 'dict' """ for e in self.getCtrlConf(msgout=False): self._lattice_c...
return all element configurations as json string file. could be further processed by beamline.Lattice class :param fmt: 'json' (default) or 'dict'
Below is the the instruction that describes the task: ### Input: return all element configurations as json string file. could be further processed by beamline.Lattice class :param fmt: 'json' (default) or 'dict' ### Response: def getAllConfig(self, fmt='json'): """ retu...
def kwonly_args(kws, required, withdefaults=(), leftovers=False): """ Based on the snippet by Eric Snow http://code.activestate.com/recipes/577940 SPDX-License-Identifier: MIT """ if hasattr(withdefaults, 'items'): # allows for OrderedDict to be passed withdefaults = withdefaul...
Based on the snippet by Eric Snow http://code.activestate.com/recipes/577940 SPDX-License-Identifier: MIT
Below is the the instruction that describes the task: ### Input: Based on the snippet by Eric Snow http://code.activestate.com/recipes/577940 SPDX-License-Identifier: MIT ### Response: def kwonly_args(kws, required, withdefaults=(), leftovers=False): """ Based on the snippet by Eric Snow http:...
def replace(dict,line): """ Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed. ...
Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed.
Below is the the instruction that describes the task: ### Input: Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A ...
def _setup_piddir(self): """Create the directory for the PID file if necessary.""" if self.pidfile is None: return piddir = os.path.dirname(self.pidfile) if not os.path.isdir(piddir): # Create the directory with sensible mode and ownership os.makedirs(...
Create the directory for the PID file if necessary.
Below is the the instruction that describes the task: ### Input: Create the directory for the PID file if necessary. ### Response: def _setup_piddir(self): """Create the directory for the PID file if necessary.""" if self.pidfile is None: return piddir = os.path.dirname(self.pid...
def wait(self, till=None): """ THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED """ waiter = Signal() if self.waiting: ...
THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED
Below is the the instruction that describes the task: ### Input: THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED ### Response: def wait(self, till=None): ...
def nphase_border(im, include_diagonals=False): r''' Identifies the voxels in regions that border *N* other regions. Useful for finding triple-phase boundaries. Parameters ---------- im : ND-array An ND image of the porous material containing discrete values in the pore space i...
r''' Identifies the voxels in regions that border *N* other regions. Useful for finding triple-phase boundaries. Parameters ---------- im : ND-array An ND image of the porous material containing discrete values in the pore space identifying different regions. e.g. the result of a ...
Below is the the instruction that describes the task: ### Input: r''' Identifies the voxels in regions that border *N* other regions. Useful for finding triple-phase boundaries. Parameters ---------- im : ND-array An ND image of the porous material containing discrete values in the ...
def check_rollout(edits_service, package_name, days): """Check if package_name has a release on staged rollout for too long""" edit = edits_service.insert(body={}, packageName=package_name).execute() response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execu...
Check if package_name has a release on staged rollout for too long
Below is the the instruction that describes the task: ### Input: Check if package_name has a release on staged rollout for too long ### Response: def check_rollout(edits_service, package_name, days): """Check if package_name has a release on staged rollout for too long""" edit = edits_service.insert(body={...
def default_number_converter(number_str): """ Converts the string representation of a json number into its python object equivalent, an int, long, float or whatever type suits. """ is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit() # FIXME: this handles a ...
Converts the string representation of a json number into its python object equivalent, an int, long, float or whatever type suits.
Below is the the instruction that describes the task: ### Input: Converts the string representation of a json number into its python object equivalent, an int, long, float or whatever type suits. ### Response: def default_number_converter(number_str): """ Converts the string representation of a json nu...
def train(self, data, target, **kwargs): """ Used in the training phase. Override. """ non_predictors = [i.replace(" ", "_").lower() for i in list(set(data['team']))] + ["team", "next_year_wins"] self.column_names = [l for l in list(data.columns) if l not in non_predictors] ...
Used in the training phase. Override.
Below is the the instruction that describes the task: ### Input: Used in the training phase. Override. ### Response: def train(self, data, target, **kwargs): """ Used in the training phase. Override. """ non_predictors = [i.replace(" ", "_").lower() for i in list(set(data['team'])...
def add_aliases(self_or_cls, **kwargs): """ Conveniently add new aliases as keyword arguments. For instance you can add a new alias with add_aliases(short='Longer string') """ self_or_cls.aliases.update({v:k for k,v in kwargs.items()})
Conveniently add new aliases as keyword arguments. For instance you can add a new alias with add_aliases(short='Longer string')
Below is the the instruction that describes the task: ### Input: Conveniently add new aliases as keyword arguments. For instance you can add a new alias with add_aliases(short='Longer string') ### Response: def add_aliases(self_or_cls, **kwargs): """ Conveniently add new aliases as keyword ...
def get_gebouw_by_id(self, id): ''' Retrieve a `Gebouw` by the Id. :param integer id: the Id of the `Gebouw` :rtype: :class:`Gebouw` ''' def creator(): res = crab_gateway_request( self.client, 'GetGebouwByIdentificatorGebouw', id )...
Retrieve a `Gebouw` by the Id. :param integer id: the Id of the `Gebouw` :rtype: :class:`Gebouw`
Below is the the instruction that describes the task: ### Input: Retrieve a `Gebouw` by the Id. :param integer id: the Id of the `Gebouw` :rtype: :class:`Gebouw` ### Response: def get_gebouw_by_id(self, id): ''' Retrieve a `Gebouw` by the Id. :param integer id: the Id of t...
def _update_limits_from_api(self): """ Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information. """ logger.debug('Setting CloudFormation limits from API') self.connect() resp = self.co...
Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information.
Below is the the instruction that describes the task: ### Input: Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information. ### Response: def _update_limits_from_api(self): """ Call the service's API action to ret...
async def load(cls, db, identifier=None, redis_key=None): """Load the object from redis. Use the identifier (colon-separated composite keys or the primary key) or the redis_key. """ if not identifier and not redis_key: raise InvalidQuery('Must supply identifier or redis_key')...
Load the object from redis. Use the identifier (colon-separated composite keys or the primary key) or the redis_key.
Below is the the instruction that describes the task: ### Input: Load the object from redis. Use the identifier (colon-separated composite keys or the primary key) or the redis_key. ### Response: async def load(cls, db, identifier=None, redis_key=None): """Load the object from redis. Use the identi...
def from_lal_unit(lunit): """Convert a LALUnit` into a `~astropy.units.Unit` Parameters ---------- lunit : `lal.Unit` the input unit Returns ------- unit : `~astropy.units.Unit` the Astropy representation of the input Raises ------ TypeError if ``lunit`...
Convert a LALUnit` into a `~astropy.units.Unit` Parameters ---------- lunit : `lal.Unit` the input unit Returns ------- unit : `~astropy.units.Unit` the Astropy representation of the input Raises ------ TypeError if ``lunit`` cannot be converted to `lal.Uni...
Below is the the instruction that describes the task: ### Input: Convert a LALUnit` into a `~astropy.units.Unit` Parameters ---------- lunit : `lal.Unit` the input unit Returns ------- unit : `~astropy.units.Unit` the Astropy representation of the input Raises ----...
def encode_binary_dict(array, buffers): ''' Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype...
Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype' : << dtype name >>, 'order' ...
Below is the the instruction that describes the task: ### Input: Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >...
def get_assignments(self, site): """ Gets a list of assignments associated with a site (class). Returns a list of TSquareAssignment objects. @param site (TSquareSite) - The site to use with the assignment query @returns - A list of TSquareSite objects. May be an empty list if ...
Gets a list of assignments associated with a site (class). Returns a list of TSquareAssignment objects. @param site (TSquareSite) - The site to use with the assignment query @returns - A list of TSquareSite objects. May be an empty list if the site has defined no assignments.
Below is the the instruction that describes the task: ### Input: Gets a list of assignments associated with a site (class). Returns a list of TSquareAssignment objects. @param site (TSquareSite) - The site to use with the assignment query @returns - A list of TSquareSite objects. May be an ...
def get_name_dictionary_extractor(name_trie): """Method for creating default name dictionary extractor""" return DictionaryExtractor()\ .set_trie(name_trie)\ .set_pre_filter(VALID_TOKEN_RE.match)\ .set_pre_process(lambda x: x.lower())\ .set_metadata({'extractor': 'dig_name_dicti...
Method for creating default name dictionary extractor
Below is the the instruction that describes the task: ### Input: Method for creating default name dictionary extractor ### Response: def get_name_dictionary_extractor(name_trie): """Method for creating default name dictionary extractor""" return DictionaryExtractor()\ .set_trie(name_trie)\ ...
def get_tunnel_statistics_output_tunnel_stat_rx_bytes(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_statistics = ET.Element("get_tunnel_statistics") config = get_tunnel_statistics output = ET.SubElement(get_tunnel_statistics, "output...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_tunnel_statistics_output_tunnel_stat_rx_bytes(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_statistics = ET.Element("get_tunnel_statistic...
def to_record(cls, attr_names, values): """ Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| ...
Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| :raises ValueError: If the ``values`` is invalid.
Below is the the instruction that describes the task: ### Input: Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tupl...
def _get_pdm(cls, df, windows): """ +DM, positive directional moving If window is not 1, calculate the SMMA of +DM :param df: data :param windows: range :return: """ window = cls.get_only_one_positive_int(windows) column_name = 'pdm_{}'.format(wi...
+DM, positive directional moving If window is not 1, calculate the SMMA of +DM :param df: data :param windows: range :return:
Below is the the instruction that describes the task: ### Input: +DM, positive directional moving If window is not 1, calculate the SMMA of +DM :param df: data :param windows: range :return: ### Response: def _get_pdm(cls, df, windows): """ +DM, positive directional m...
def do_termchar(self, args): """Get or set termination character for resource in use. <termchar> can be one of: CR, LF, CRLF, NUL or None. None is used to disable termination character Get termination character: termchar Set termination character read or re...
Get or set termination character for resource in use. <termchar> can be one of: CR, LF, CRLF, NUL or None. None is used to disable termination character Get termination character: termchar Set termination character read or read+write: termchar <termcha...
Below is the the instruction that describes the task: ### Input: Get or set termination character for resource in use. <termchar> can be one of: CR, LF, CRLF, NUL or None. None is used to disable termination character Get termination character: termchar Set ter...
def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image""" self.renderer.draw_image(imdata=utils.image_to_base64(image), extent=image.get_extent(), coordinates="data", ...
Process a matplotlib image object and call renderer.draw_image
Below is the the instruction that describes the task: ### Input: Process a matplotlib image object and call renderer.draw_image ### Response: def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image""" self.renderer.draw_image(imdata=utils.image_to_base64(i...
def add_index(self, field, value): """ add_index(field, value) Tag this object with the specified field/value pair for indexing. :param field: The index field. :type field: string :param value: The index value. :type value: string or integer :rty...
add_index(field, value) Tag this object with the specified field/value pair for indexing. :param field: The index field. :type field: string :param value: The index value. :type value: string or integer :rtype: :class:`RiakObject <riak.riak_object.RiakObject>`
Below is the the instruction that describes the task: ### Input: add_index(field, value) Tag this object with the specified field/value pair for indexing. :param field: The index field. :type field: string :param value: The index value. :type value: string or intege...
def tree_walk(cls, directory, tree): """Walks a tree returned by `cls.list_to_tree` returning a list of 3-tuples as if from os.walk().""" results = [] dirs = [d for d in tree if d != FILE_MARKER] files = tree[FILE_MARKER] results.append((directory, dirs, files)) f...
Walks a tree returned by `cls.list_to_tree` returning a list of 3-tuples as if from os.walk().
Below is the the instruction that describes the task: ### Input: Walks a tree returned by `cls.list_to_tree` returning a list of 3-tuples as if from os.walk(). ### Response: def tree_walk(cls, directory, tree): """Walks a tree returned by `cls.list_to_tree` returning a list of 3-tuples as i...
def xcorr(x, y=None, maxlags=None, norm='biased'): """Cross-correlation using numpy.correlate Estimates the cross-correlation (and autocorrelation) sequence of a random process of length N. By default, there is no normalisation and the output sequence of the cross-correlation has a length 2*N+1. :...
Cross-correlation using numpy.correlate Estimates the cross-correlation (and autocorrelation) sequence of a random process of length N. By default, there is no normalisation and the output sequence of the cross-correlation has a length 2*N+1. :param array x: first data array of length N :param arr...
Below is the the instruction that describes the task: ### Input: Cross-correlation using numpy.correlate Estimates the cross-correlation (and autocorrelation) sequence of a random process of length N. By default, there is no normalisation and the output sequence of the cross-correlation has a length 2*...
def state(self): """Which state the session is in. Starting - all messages needed to get stream started. Playing - keep-alive messages every self.session_timeout. """ if self.method in ['OPTIONS', 'DESCRIBE', 'SETUP', 'PLAY']: state = STATE_STARTING elif self...
Which state the session is in. Starting - all messages needed to get stream started. Playing - keep-alive messages every self.session_timeout.
Below is the the instruction that describes the task: ### Input: Which state the session is in. Starting - all messages needed to get stream started. Playing - keep-alive messages every self.session_timeout. ### Response: def state(self): """Which state the session is in. Starting...
def provider_parser(subparser): """Configure a provider parser for Hetzner""" subparser.add_argument('--auth-account', help='specify type of Hetzner account: by default Hetzner Robot ' '(robot) or Hetzner konsoleH (konsoleh)') subparser.add_argument('--a...
Configure a provider parser for Hetzner
Below is the the instruction that describes the task: ### Input: Configure a provider parser for Hetzner ### Response: def provider_parser(subparser): """Configure a provider parser for Hetzner""" subparser.add_argument('--auth-account', help='specify type of Hetzner account: by ...
def get_content(self): """Open content as a stream for reading. See DAVResource.get_content() """ filestream = compat.StringIO() tableName, primKey = self.provider._split_path(self.path) if primKey is not None: conn = self.provider._init_connection() ...
Open content as a stream for reading. See DAVResource.get_content()
Below is the the instruction that describes the task: ### Input: Open content as a stream for reading. See DAVResource.get_content() ### Response: def get_content(self): """Open content as a stream for reading. See DAVResource.get_content() """ filestream = compat.StringIO...
def ec2_network_network_acl_id(self, lookup, default=None): """ Args: lookup: the friendly name of the network ACL we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the network ACL, or None if no match found """ net...
Args: lookup: the friendly name of the network ACL we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the network ACL, or None if no match found
Below is the the instruction that describes the task: ### Input: Args: lookup: the friendly name of the network ACL we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the network ACL, or None if no match found ### Response: def...
def end(self): """Shutdown the curses window.""" if hasattr(curses, 'echo'): curses.echo() if hasattr(curses, 'nocbreak'): curses.nocbreak() if hasattr(curses, 'curs_set'): try: curses.curs_set(1) except Exception: ...
Shutdown the curses window.
Below is the the instruction that describes the task: ### Input: Shutdown the curses window. ### Response: def end(self): """Shutdown the curses window.""" if hasattr(curses, 'echo'): curses.echo() if hasattr(curses, 'nocbreak'): curses.nocbreak() if hasattr(...
def get_summary(list_all=[], **kwargs): ''' summarize the report data @param list_all: a list which save the report data @param kwargs: such as show_all: True/False report show all status cases proj_name: project name home_pag...
summarize the report data @param list_all: a list which save the report data @param kwargs: such as show_all: True/False report show all status cases proj_name: project name home_page: home page url
Below is the the instruction that describes the task: ### Input: summarize the report data @param list_all: a list which save the report data @param kwargs: such as show_all: True/False report show all status cases proj_name: project name ...
def determine_type(filename): '''Determine the file type and return it.''' ftype = magic.from_file(filename, mime=True).decode('utf8') if ftype == 'text/plain': ftype = 'text' elif ftype == 'image/svg+xml': ftype = 'svg' else: ftype = ftype.split('/')[1] return ftype
Determine the file type and return it.
Below is the the instruction that describes the task: ### Input: Determine the file type and return it. ### Response: def determine_type(filename): '''Determine the file type and return it.''' ftype = magic.from_file(filename, mime=True).decode('utf8') if ftype == 'text/plain': ftype = 'text' ...
def get_posts(self, include_draft=False, filter_functions=None): """ Get all posts from filesystem. :param include_draft: return draft posts or not :param filter_functions: filter to apply BEFORE result being sorted :return: an iterable of Post objects (the first is the latest p...
Get all posts from filesystem. :param include_draft: return draft posts or not :param filter_functions: filter to apply BEFORE result being sorted :return: an iterable of Post objects (the first is the latest post)
Below is the the instruction that describes the task: ### Input: Get all posts from filesystem. :param include_draft: return draft posts or not :param filter_functions: filter to apply BEFORE result being sorted :return: an iterable of Post objects (the first is the latest post) ### Respons...
def finalize(self): """ Get the base64-encoded signature itself. Can only be called once. """ signature = self.signer.finalize() sig_r, sig_s = decode_dss_signature(signature) sig_b64 = encode_signature(sig_r, sig_s) return sig_b64
Get the base64-encoded signature itself. Can only be called once.
Below is the the instruction that describes the task: ### Input: Get the base64-encoded signature itself. Can only be called once. ### Response: def finalize(self): """ Get the base64-encoded signature itself. Can only be called once. """ signature = self.signer.fina...
def emit(self, record): """Prints a record out to some streams. If FLAGS.logtostderr is set, it will print to sys.stderr ONLY. If FLAGS.alsologtostderr is set, it will print to sys.stderr. If FLAGS.logtostderr is not set, it will log to the stream associated with the current thread. Args: ...
Prints a record out to some streams. If FLAGS.logtostderr is set, it will print to sys.stderr ONLY. If FLAGS.alsologtostderr is set, it will print to sys.stderr. If FLAGS.logtostderr is not set, it will log to the stream associated with the current thread. Args: record: logging.LogRecord, ...
Below is the the instruction that describes the task: ### Input: Prints a record out to some streams. If FLAGS.logtostderr is set, it will print to sys.stderr ONLY. If FLAGS.alsologtostderr is set, it will print to sys.stderr. If FLAGS.logtostderr is not set, it will log to the stream associated ...
def title(self, gender: Optional[Gender] = None, title_type: Optional[TitleType] = None) -> str: """Generate a random title for name. You can generate random prefix or suffix for name using this method. :param gender: The gender. :param title_type: TitleType enum ...
Generate a random title for name. You can generate random prefix or suffix for name using this method. :param gender: The gender. :param title_type: TitleType enum object. :return: The title. :raises NonEnumerableError: if gender or title_type in incorrect format. ...
Below is the the instruction that describes the task: ### Input: Generate a random title for name. You can generate random prefix or suffix for name using this method. :param gender: The gender. :param title_type: TitleType enum object. :return: The title. :raises N...
def forward(self, input, target): """ NB: It's for debug only, please use optimizer.optimize() in production. Takes an input object, and computes the corresponding loss of the criterion, compared with `target` :param input: ndarray or list of ndarray :param target: ndarr...
NB: It's for debug only, please use optimizer.optimize() in production. Takes an input object, and computes the corresponding loss of the criterion, compared with `target` :param input: ndarray or list of ndarray :param target: ndarray or list of ndarray :return: value of loss
Below is the the instruction that describes the task: ### Input: NB: It's for debug only, please use optimizer.optimize() in production. Takes an input object, and computes the corresponding loss of the criterion, compared with `target` :param input: ndarray or list of ndarray :para...
def _wait_for_read_ready_or_timeout(self, timeout): """Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read or a ...
Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read or a SIGTSTP triggered by dsusp has been received
Below is the the instruction that describes the task: ### Input: Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read...
def has_property(self, property_name): """ Check if schema has property :param property_name: str, name to check :return: bool """ if property_name in self.properties: return True elif property_name in self.entities: return True eli...
Check if schema has property :param property_name: str, name to check :return: bool
Below is the the instruction that describes the task: ### Input: Check if schema has property :param property_name: str, name to check :return: bool ### Response: def has_property(self, property_name): """ Check if schema has property :param property_name: str, name to check...
def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the BB models and the estimates""" stratum_idx = extra_info['stratum'] self._BB_TP.update(ell*ell_hat, stratum_idx) self._BB_PP.update(ell_hat, stratum_idx) ...
Update the BB models and the estimates
Below is the the instruction that describes the task: ### Input: Update the BB models and the estimates ### Response: def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the BB models and the estimates""" stratum_idx = e...
def loadJSON(self, filename): """Adds the data from a JSON file. The file is expected to be in datapoint format:: d = DatapointArray().loadJSON("myfile.json") """ with open(filename, "r") as f: self.merge(json.load(f)) return self
Adds the data from a JSON file. The file is expected to be in datapoint format:: d = DatapointArray().loadJSON("myfile.json")
Below is the the instruction that describes the task: ### Input: Adds the data from a JSON file. The file is expected to be in datapoint format:: d = DatapointArray().loadJSON("myfile.json") ### Response: def loadJSON(self, filename): """Adds the data from a JSON file. The file is expected to ...
def get(id_, hwid, type_, unit, precision, as_json): """Get temperature of a specific sensor""" if id_ and (hwid or type_): raise click.BadOptionUsage( "If --id is given --hwid and --type are not allowed." ) if id_: try: sensor = W1ThermSensor.get_available_s...
Get temperature of a specific sensor
Below is the the instruction that describes the task: ### Input: Get temperature of a specific sensor ### Response: def get(id_, hwid, type_, unit, precision, as_json): """Get temperature of a specific sensor""" if id_ and (hwid or type_): raise click.BadOptionUsage( "If --id is given -...
def gep(self, ptr, indices, inbounds=False, name=''): """ Compute effective address (getelementptr): name = getelementptr ptr, <indices...> """ instr = instructions.GEPInstr(self.block, ptr, indices, inbounds=inbounds, name=name) ...
Compute effective address (getelementptr): name = getelementptr ptr, <indices...>
Below is the the instruction that describes the task: ### Input: Compute effective address (getelementptr): name = getelementptr ptr, <indices...> ### Response: def gep(self, ptr, indices, inbounds=False, name=''): """ Compute effective address (getelementptr): name = getele...
def cds_column_replace(source, data): """ Determine if the CDS.data requires a full replacement or simply needs to be updated. A replacement is required if untouched columns are not the same length as the columns being updated. """ current_length = [len(v) for v in source.data.values() if isinst...
Determine if the CDS.data requires a full replacement or simply needs to be updated. A replacement is required if untouched columns are not the same length as the columns being updated.
Below is the the instruction that describes the task: ### Input: Determine if the CDS.data requires a full replacement or simply needs to be updated. A replacement is required if untouched columns are not the same length as the columns being updated. ### Response: def cds_column_replace(source, data): ...
def dsort(fname, order, has_header=True, frow=0, ofname=None): r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the com...
r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the comma-separated values file to sort has column ...
Below is the the instruction that describes the task: ### Input: r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the c...
def mark_entries(self, entries): ''' Mark one entry as main entry and the rest as resource entry. Main entry is the entry that contain response's body of the requested URL. ''' for entry in entries: self._set_entry_type(entry, RESOURCE_ENTRY) # If f...
Mark one entry as main entry and the rest as resource entry. Main entry is the entry that contain response's body of the requested URL.
Below is the the instruction that describes the task: ### Input: Mark one entry as main entry and the rest as resource entry. Main entry is the entry that contain response's body of the requested URL. ### Response: def mark_entries(self, entries): ''' Mark one entry as main entry a...
def build_genome_alignment_from_file(ga_path, ref_spec, idx_path=None, verbose=False): """ build a genome alignment by loading from a single MAF file. :param ga_path: the path to the file to load. :param ref_spec: which species in the MAF file is the reference? :param id...
build a genome alignment by loading from a single MAF file. :param ga_path: the path to the file to load. :param ref_spec: which species in the MAF file is the reference? :param idx_path: if provided, use this index to generate a just-in-time genome alignment, instead of loading the file imme...
Below is the the instruction that describes the task: ### Input: build a genome alignment by loading from a single MAF file. :param ga_path: the path to the file to load. :param ref_spec: which species in the MAF file is the reference? :param idx_path: if provided, use this index to generate a just-in-time ...
async def _send_report(self, status): """ Call all subscribed coroutines in _notify whenever a status update occurs. This method is a coroutine """ if len(self._notify) > 0: # Each client gets its own copy of the dict. asyncio.gather(*[coro(dict(s...
Call all subscribed coroutines in _notify whenever a status update occurs. This method is a coroutine
Below is the the instruction that describes the task: ### Input: Call all subscribed coroutines in _notify whenever a status update occurs. This method is a coroutine ### Response: async def _send_report(self, status): """ Call all subscribed coroutines in _notify whenever a status...
def reviews(self, last_item, filter_=None): """Get the reviews starting from last_item.""" cmd = self._get_gerrit_cmd(last_item, filter_) logger.debug("Getting reviews with command: %s", cmd) raw_data = self.__execute(cmd) raw_data = str(raw_data, "UTF-8") return raw_d...
Get the reviews starting from last_item.
Below is the the instruction that describes the task: ### Input: Get the reviews starting from last_item. ### Response: def reviews(self, last_item, filter_=None): """Get the reviews starting from last_item.""" cmd = self._get_gerrit_cmd(last_item, filter_) logger.debug("Getting reviews w...
def run(args): """ Args: args (argparse.Namespace) """ with warnings.catch_warnings(): warnings.simplefilter('ignore') query = prepareQuery(args.query_file.read()) ds = Dataset() res_indices_prev = set() # de-duplication res_indices = set() # ...
Args: args (argparse.Namespace)
Below is the the instruction that describes the task: ### Input: Args: args (argparse.Namespace) ### Response: def run(args): """ Args: args (argparse.Namespace) """ with warnings.catch_warnings(): warnings.simplefilter('ignore') query = prepareQuery(args.query_fil...
def _parse_tensor(self, indices=False): '''Parse a tensor.''' if indices: self.line = self._skip_lines(1) tensor = np.zeros((3, 3)) for i in range(3): tokens = self.line.split() if indices: tensor[i][0] = float(tokens[1]) ...
Parse a tensor.
Below is the the instruction that describes the task: ### Input: Parse a tensor. ### Response: def _parse_tensor(self, indices=False): '''Parse a tensor.''' if indices: self.line = self._skip_lines(1) tensor = np.zeros((3, 3)) for i in range(3): tokens = sel...
def save(df, path, data_paths): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one ...
Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one component of the datapoint.
Below is the the instruction that describes the task: ### Input: Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspo...
def set_project_filenames(self, recent_files): """Set the list of open file names in a project""" if (self.current_active_project and self.is_valid_project( self.current_active_project.root_path)): self.current_active_project.set_recent_files(rece...
Set the list of open file names in a project
Below is the the instruction that describes the task: ### Input: Set the list of open file names in a project ### Response: def set_project_filenames(self, recent_files): """Set the list of open file names in a project""" if (self.current_active_project and self.is_valid_project(...
def revoke(self): """ * flag certificate as revoked * fill in revoked_at DateTimeField """ now = timezone.now() self.revoked = True self.revoked_at = now self.save()
* flag certificate as revoked * fill in revoked_at DateTimeField
Below is the the instruction that describes the task: ### Input: * flag certificate as revoked * fill in revoked_at DateTimeField ### Response: def revoke(self): """ * flag certificate as revoked * fill in revoked_at DateTimeField """ now = timezone.now() sel...
def calcu0(self,E,Lz): """ NAME: calcu0 PURPOSE: calculate the minimum of the u potential INPUT: E - energy Lz - angular momentum OUTPUT: u0 HISTORY: 2012-11-29 - Written - Bovy (IAS) """ ...
NAME: calcu0 PURPOSE: calculate the minimum of the u potential INPUT: E - energy Lz - angular momentum OUTPUT: u0 HISTORY: 2012-11-29 - Written - Bovy (IAS)
Below is the the instruction that describes the task: ### Input: NAME: calcu0 PURPOSE: calculate the minimum of the u potential INPUT: E - energy Lz - angular momentum OUTPUT: u0 HISTORY: 2012-11-29 - Written - Bovy (I...
def open_state_machine(path=None, recent_opened_notification=False): """ Open a state machine from respective file system path :param str path: file system path to the state machine :param bool recent_opened_notification: flags that indicates that this call also should update recently open :rtype rafc...
Open a state machine from respective file system path :param str path: file system path to the state machine :param bool recent_opened_notification: flags that indicates that this call also should update recently open :rtype rafcon.core.state_machine.StateMachine :return: opened state machine
Below is the the instruction that describes the task: ### Input: Open a state machine from respective file system path :param str path: file system path to the state machine :param bool recent_opened_notification: flags that indicates that this call also should update recently open :rtype rafcon.core....
def render_js_code(self, id_, *args, **kwargs): """Render html container for Select2 widget with options.""" if id_: options = self.render_select2_options_code( dict(self.get_options()), id_) return mark_safe(self.html.format(id=id_, options=options)) ...
Render html container for Select2 widget with options.
Below is the the instruction that describes the task: ### Input: Render html container for Select2 widget with options. ### Response: def render_js_code(self, id_, *args, **kwargs): """Render html container for Select2 widget with options.""" if id_: options = self.render_select2_option...
def _ensure_counter(self): """Ensure the sync counter is a valid non-dummy object.""" if not isinstance(self.sync_counter, self._SynchronizationManager): self.sync_counter = self._SynchronizationManager()
Ensure the sync counter is a valid non-dummy object.
Below is the the instruction that describes the task: ### Input: Ensure the sync counter is a valid non-dummy object. ### Response: def _ensure_counter(self): """Ensure the sync counter is a valid non-dummy object.""" if not isinstance(self.sync_counter, self._SynchronizationManager): s...
def throttle(self, key, amount=1, rate=None, capacity=None, exc_class=Throttled, **kwargs): """Consume an amount for a given key, or raise a Throttled exception.""" if not self.consume(key, amount, rate, capacity, **kwargs): raise exc_class("Request of %d unit for %s exceeds cap...
Consume an amount for a given key, or raise a Throttled exception.
Below is the the instruction that describes the task: ### Input: Consume an amount for a given key, or raise a Throttled exception. ### Response: def throttle(self, key, amount=1, rate=None, capacity=None, exc_class=Throttled, **kwargs): """Consume an amount for a given key, or raise a Throttle...
def dump_tables_to_tskit(pop): """ Converts fwdpy11.TableCollection to an tskit.TreeSequence """ node_view = np.array(pop.tables.nodes, copy=True) node_view['time'] -= node_view['time'].max() node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0 edge_view = np.array(pop.tables...
Converts fwdpy11.TableCollection to an tskit.TreeSequence
Below is the the instruction that describes the task: ### Input: Converts fwdpy11.TableCollection to an tskit.TreeSequence ### Response: def dump_tables_to_tskit(pop): """ Converts fwdpy11.TableCollection to an tskit.TreeSequence """ node_view = np.array(pop.tables.nodes, copy=True) nod...
def uncompress_files(original, destination): """ Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path """ with zipfile.ZipFile(original) as zips: ...
Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path
Below is the the instruction that describes the task: ### Input: Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path ### Response: def uncompress_files(original,...
def connect(self): "Connects to the Redis server if not already connected" if self._sock: return try: sock = self._connect() except socket.timeout: raise TimeoutError("Timeout connecting to server") except socket.error: e = sys.exc_...
Connects to the Redis server if not already connected
Below is the the instruction that describes the task: ### Input: Connects to the Redis server if not already connected ### Response: def connect(self): "Connects to the Redis server if not already connected" if self._sock: return try: sock = self._connect() e...
def can_cast_to(v: Literal, dt: str) -> bool: """ 5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v per XPath Functions 3.1 section 19 Casting[xpath-functions]." """ # TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257...
5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v per XPath Functions 3.1 section 19 Casting[xpath-functions]."
Below is the the instruction that describes the task: ### Input: 5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v per XPath Functions 3.1 section 19 Casting[xpath-functions]." ### Response: def can_cast_to(v: Literal, dt: str) -> bool: """...
def tag(self, alt='', use_size=None, **attrs): """ Return a standard XHTML ``<img ... />`` tag for this field. :param alt: The ``alt=""`` text for the tag. Defaults to ``''``. :param use_size: Whether to get the size of the thumbnail image for use in the tag attributes. If ...
Return a standard XHTML ``<img ... />`` tag for this field. :param alt: The ``alt=""`` text for the tag. Defaults to ``''``. :param use_size: Whether to get the size of the thumbnail image for use in the tag attributes. If ``None`` (default), the size will only be used it if wo...
Below is the the instruction that describes the task: ### Input: Return a standard XHTML ``<img ... />`` tag for this field. :param alt: The ``alt=""`` text for the tag. Defaults to ``''``. :param use_size: Whether to get the size of the thumbnail image for use in the tag attributes. I...
def exit_on_error(self, message, exit_code=1): # pylint: disable=no-self-use """Log generic message when getting an error and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :t...
Log generic message when getting an error and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None
Below is the the instruction that describes the task: ### Input: Log generic message when getting an error and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :r...
def assemble_cx(): """Assemble INDRA Statements and return CX network json.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ca = CxAssembler...
Assemble INDRA Statements and return CX network json.
Below is the the instruction that describes the task: ### Input: Assemble INDRA Statements and return CX network json. ### Response: def assemble_cx(): """Assemble INDRA Statements and return CX network json.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('ut...
def get_nodes(self, request): """ This method is used to build the menu tree. """ nodes = [] for shiny_app in ShinyApp.objects.all(): node = NavigationNode( shiny_app.name, reverse('cms_shiny:shiny_detail', args=(shiny_app.slug,)), ...
This method is used to build the menu tree.
Below is the the instruction that describes the task: ### Input: This method is used to build the menu tree. ### Response: def get_nodes(self, request): """ This method is used to build the menu tree. """ nodes = [] for shiny_app in ShinyApp.objects.all(): node =...
def reset( self ): """ Resets the user interface buttons for this widget. """ # clear previous widgets for btn in self.findChildren(QToolButton): btn.close() btn.setParent(None) btn.deleteLater() # determine coloring options ...
Resets the user interface buttons for this widget.
Below is the the instruction that describes the task: ### Input: Resets the user interface buttons for this widget. ### Response: def reset( self ): """ Resets the user interface buttons for this widget. """ # clear previous widgets for btn in self.findChildren(QToolButton):...
def multiget_slice(self, keys, column_parent, predicate, consistency_level): """ Performs a get_slice for column_parent and predicate for the given keys in parallel. Parameters: - keys - column_parent - predicate - consistency_level """ self._seqid += 1 d = self._reqs[self._...
Performs a get_slice for column_parent and predicate for the given keys in parallel. Parameters: - keys - column_parent - predicate - consistency_level
Below is the the instruction that describes the task: ### Input: Performs a get_slice for column_parent and predicate for the given keys in parallel. Parameters: - keys - column_parent - predicate - consistency_level ### Response: def multiget_slice(self, keys, column_parent, predicate, co...
def options(self, parser, env=None): """ Sphinx config file that can optionally take the following python template string arguments: ``database_name`` ``database_password`` ``database_username`` ``database_host`` ``database_port`` ``sphinx_search_...
Sphinx config file that can optionally take the following python template string arguments: ``database_name`` ``database_password`` ``database_username`` ``database_host`` ``database_port`` ``sphinx_search_data_dir`` ``searchd_log_dir``
Below is the the instruction that describes the task: ### Input: Sphinx config file that can optionally take the following python template string arguments: ``database_name`` ``database_password`` ``database_username`` ``database_host`` ``database_port`` ``sp...
def lock(self, lock_name, timeout=900): """ Attempt to use lock and unlock, which will work if the Cache is Redis, but fall back to a memcached-compliant add/delete approach. If the Jobtastic Cache isn't Redis or Memcache, or another product with a compatible lock or add/delete ...
Attempt to use lock and unlock, which will work if the Cache is Redis, but fall back to a memcached-compliant add/delete approach. If the Jobtastic Cache isn't Redis or Memcache, or another product with a compatible lock or add/delete API, then a custom locking function will be required...
Below is the the instruction that describes the task: ### Input: Attempt to use lock and unlock, which will work if the Cache is Redis, but fall back to a memcached-compliant add/delete approach. If the Jobtastic Cache isn't Redis or Memcache, or another product with a compatible lock or ad...
def from_api_repr(cls, resource, client): """Factory: construct a job given its API representation .. note: This method assumes that the project found in the resource matches the client's project. :type resource: dict :param resource: dataset job representation ...
Factory: construct a job given its API representation .. note: This method assumes that the project found in the resource matches the client's project. :type resource: dict :param resource: dataset job representation returned from the API :type client: :class:`...
Below is the the instruction that describes the task: ### Input: Factory: construct a job given its API representation .. note: This method assumes that the project found in the resource matches the client's project. :type resource: dict :param resource: dataset job...
def get_plugins_by_feature(features): """ Returns a list of plugin names where the plugins implement at least one of the *features*. *features* must a list of Plugin methods, e.g. [Plugin.postprocess_testrun, Plugin.postprocess_testjob] """ if not features: return get_all_plugins() p...
Returns a list of plugin names where the plugins implement at least one of the *features*. *features* must a list of Plugin methods, e.g. [Plugin.postprocess_testrun, Plugin.postprocess_testjob]
Below is the the instruction that describes the task: ### Input: Returns a list of plugin names where the plugins implement at least one of the *features*. *features* must a list of Plugin methods, e.g. [Plugin.postprocess_testrun, Plugin.postprocess_testjob] ### Response: def get_plugins_by_feature(featur...
def unit_conversion(current, desired): """ Calculate the conversion from one set of units to another. Parameters --------- current : str Unit system values are in now (eg 'millimeters') desired : str Unit system we'd like values in (eg 'inches') Returns --------- co...
Calculate the conversion from one set of units to another. Parameters --------- current : str Unit system values are in now (eg 'millimeters') desired : str Unit system we'd like values in (eg 'inches') Returns --------- conversion : float Number to multiply by to p...
Below is the the instruction that describes the task: ### Input: Calculate the conversion from one set of units to another. Parameters --------- current : str Unit system values are in now (eg 'millimeters') desired : str Unit system we'd like values in (eg 'inches') Returns ...
def factorize(self): """Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint beta >=0, sum(beta)=1, H >=0, sum(H)=1 """ # compute new coefficients for reconstructing data points self.update_w() # for CHNMF it is sometimes useful to only ...
Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint beta >=0, sum(beta)=1, H >=0, sum(H)=1
Below is the the instruction that describes the task: ### Input: Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint beta >=0, sum(beta)=1, H >=0, sum(H)=1 ### Response: def factorize(self): """Do factorization s.t. data = dot(dot(data,beta),H), under the convexit...
def main(sleep_length=0.1): """Log to stdout using python logging in a while loop""" log = logging.getLogger('sip.examples.log_spammer') log.info('Starting to spam log messages every %fs', sleep_length) counter = 0 try: while True: log.info('Hello %06i (log_spammer: %s, sip logg...
Log to stdout using python logging in a while loop
Below is the the instruction that describes the task: ### Input: Log to stdout using python logging in a while loop ### Response: def main(sleep_length=0.1): """Log to stdout using python logging in a while loop""" log = logging.getLogger('sip.examples.log_spammer') log.info('Starting to spam log mess...
def build_groups(self, tokens): """Build dict of groups from list of tokens""" groups = {} for token in tokens: match_type = MatchType.start if token.group_end else MatchType.single groups[token.group_start] = (token, match_type) if token.group_end: ...
Build dict of groups from list of tokens
Below is the the instruction that describes the task: ### Input: Build dict of groups from list of tokens ### Response: def build_groups(self, tokens): """Build dict of groups from list of tokens""" groups = {} for token in tokens: match_type = MatchType.start if token.group_end...
def keywords(text, cloud=None, batch=False, api_key=None, version=2, batch_size=None, **kwargs): """ Given input text, returns series of keywords and associated scores Example usage: .. code-block:: python >>> import indicoio >>> import numpy as np >>> text = 'Monday: Delightful ...
Given input text, returns series of keywords and associated scores Example usage: .. code-block:: python >>> import indicoio >>> import numpy as np >>> text = 'Monday: Delightful with mostly sunny skies. Highs in the low 70s.' >>> keywords = indicoio.keywords(text, top_n=3) ...
Below is the the instruction that describes the task: ### Input: Given input text, returns series of keywords and associated scores Example usage: .. code-block:: python >>> import indicoio >>> import numpy as np >>> text = 'Monday: Delightful with mostly sunny skies. Highs in the lo...
def extract_name_from_job_arn(arn): """Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job. """ slash_pos = arn.find('/') if slash_pos == -1: raise ValueError("Cannot parse invalid ARN: %s" % arn) return arn[(slash_pos + 1):]
Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job.
Below is the the instruction that describes the task: ### Input: Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job. ### Response: def extract_name_from_job_arn(arn): """Returns the name used in the API given a full ARN for a training job or hyperparameter...
def libvlc_audio_set_mute(p_mi, status): '''Set mute status. @param p_mi: media player. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/P...
Set mute status. @param p_mi: media player. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/PDIF, HDMI...) is in use, muting may be unapplica...
Below is the the instruction that describes the task: ### Input: Set mute status. @param p_mi: media player. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digi...