code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def build_options(payload, options, maxsize = 576, overload = OVERLOAD_FILE | OVERLOAD_SNAME, allowpartial = True): ''' Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field ov...
Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field overloading is used. :param options: a list of `dhcp_option` :param maxsize: Limit the maximum DHCP message ...
Below is the the instruction that describes the task: ### Input: Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field overloading is used. :param options: a list of `...
def ini_dump_hook(cfg, text: bool=False): """ Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned. """ data = cfg.config.dump() # Load data back into the goddamned ini file. ndict = {} for ke...
Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned.
Below is the the instruction that describes the task: ### Input: Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned. ### Response: def ini_dump_hook(cfg, text: bool=False): """ Dumps all the data into a INI...
def main(): """ Runs Godot. """ application = GodotApplication( id="godot", plugins=[CorePlugin(), PuddlePlugin(), WorkbenchPlugin(), ResourcePlugin(), GodotPlugin()] ) application.run()
Runs Godot.
Below is the the instruction that describes the task: ### Input: Runs Godot. ### Response: def main(): """ Runs Godot. """ application = GodotApplication( id="godot", plugins=[CorePlugin(), PuddlePlugin(), WorkbenchPlugin(), ResourcePlugin(), ...
def replace_cluster_role(self, name, body, **kwargs): """ replace the specified ClusterRole This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_cluster_role(name, body, async_req=True) ...
replace the specified ClusterRole This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_cluster_role(name, body, async_req=True) >>> result = thread.get() :param async_req bool :...
Below is the the instruction that describes the task: ### Input: replace the specified ClusterRole This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_cluster_role(name, body, async_req=True) ...
def supports_coordinate_type(self, coordinate_type=None): """Tests if the given coordinate type is supported. arg: coordinate_type (osid.type.Type): a coordinate Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syn...
Tests if the given coordinate type is supported. arg: coordinate_type (osid.type.Type): a coordinate Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``COORDINATE`` raise: NullArgument - ``coordina...
Below is the the instruction that describes the task: ### Input: Tests if the given coordinate type is supported. arg: coordinate_type (osid.type.Type): a coordinate Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syn...
def reply(self): """ Reply to the selected item. This is a utility method and should not be bound to a key directly. Item type: Submission - add a top level comment Comment - add a comment reply Message - reply to a private message """ ...
Reply to the selected item. This is a utility method and should not be bound to a key directly. Item type: Submission - add a top level comment Comment - add a comment reply Message - reply to a private message
Below is the the instruction that describes the task: ### Input: Reply to the selected item. This is a utility method and should not be bound to a key directly. Item type: Submission - add a top level comment Comment - add a comment reply Message - reply to a pri...
def _node(self, tax_id): """ Returns parent_id, rank FIXME: expand return rank to include custom 'below' ranks built when get_lineage is caled """ s = select([self.nodes.c.parent_id, self.nodes.c.rank], self.nodes.c.tax_id == tax_id) res...
Returns parent_id, rank FIXME: expand return rank to include custom 'below' ranks built when get_lineage is caled
Below is the the instruction that describes the task: ### Input: Returns parent_id, rank FIXME: expand return rank to include custom 'below' ranks built when get_lineage is caled ### Response: def _node(self, tax_id): """ Returns parent_id, rank FIXME: expand return...
def close(self): """Force close all Channels and cancel all Operations """ if self._Q is not None: for T in self._T: self._Q.interrupt() for n, T in enumerate(self._T): _log.debug('Join Context worker %d', n) T.join() ...
Force close all Channels and cancel all Operations
Below is the the instruction that describes the task: ### Input: Force close all Channels and cancel all Operations ### Response: def close(self): """Force close all Channels and cancel all Operations """ if self._Q is not None: for T in self._T: self._Q.interrup...
def create_tomodir(self, directory): """Create a tomodir subdirectory structure in the given directory """ pwd = os.getcwd() if not os.path.isdir(directory): os.makedirs(directory) os.chdir(directory) directories = ( 'config', 'exe', ...
Create a tomodir subdirectory structure in the given directory
Below is the the instruction that describes the task: ### Input: Create a tomodir subdirectory structure in the given directory ### Response: def create_tomodir(self, directory): """Create a tomodir subdirectory structure in the given directory """ pwd = os.getcwd() if not os.path.i...
def delete(self, reason=''): """Deletes the event chatroom and if necessary the chatroom, too. :param reason: reason for the deletion :return: True if the associated chatroom was also deleted, otherwise False """ db.session.delete(self) db.session.flush(...
Deletes the event chatroom and if necessary the chatroom, too. :param reason: reason for the deletion :return: True if the associated chatroom was also deleted, otherwise False
Below is the the instruction that describes the task: ### Input: Deletes the event chatroom and if necessary the chatroom, too. :param reason: reason for the deletion :return: True if the associated chatroom was also deleted, otherwise False ### Response: def delete(self, reason='...
def rsdl_rn(self, AX, Y): """Compute primal residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden. """ # Avoid computing the norm of the value returned by cnst_c(...
Compute primal residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
Below is the the instruction that describes the task: ### Input: Compute primal residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden. ### Response: def rsdl_rn(self, AX, Y): ...
def set_display_columns(self, set_true=[], set_false=[]): """Add or remove columns from the output.""" for i in range(len(self.fields)): if self.fields[i].name in set_true: self.fields[i].display = True elif self.fields[i].name in set_false: self.f...
Add or remove columns from the output.
Below is the the instruction that describes the task: ### Input: Add or remove columns from the output. ### Response: def set_display_columns(self, set_true=[], set_false=[]): """Add or remove columns from the output.""" for i in range(len(self.fields)): if self.fields[i].name in set_tr...
def __get_oauth_url(self, url, method, **kwargs): """ Generate oAuth1.0a URL """ oauth = OAuth( url=url, consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, version=self.version, method=method, oauth_timestamp=kwar...
Generate oAuth1.0a URL
Below is the the instruction that describes the task: ### Input: Generate oAuth1.0a URL ### Response: def __get_oauth_url(self, url, method, **kwargs): """ Generate oAuth1.0a URL """ oauth = OAuth( url=url, consumer_key=self.consumer_key, consumer_secret=self.con...
def _zip_from_file_patterns(root, includes, excludes, follow_symlinks): """Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in...
Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching t...
Below is the the instruction that describes the task: ### Input: Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the resul...
def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False): """Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_...
Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_on_graph_call_error: A boolean indicate whether an error should be raised if the underlying ...
Below is the the instruction that describes the task: ### Input: Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_on_graph_call_error: A boolean ...
def next_frame_savp(): """SAVP model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.add_hparam("z_dim", 8) hparams.add_hparam("num_discriminator_filters", 32) hparams.add_hparam("use_vae", True) hparams.add_hparam("use_gan", False) hparams.add_hparam("use_spectral_norm", True) hparams.add_h...
SAVP model hparams.
Below is the the instruction that describes the task: ### Input: SAVP model hparams. ### Response: def next_frame_savp(): """SAVP model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.add_hparam("z_dim", 8) hparams.add_hparam("num_discriminator_filters", 32) hparams.add_hparam("use_vae", True...
def remove_empty_keys(values, remove=({}, None, [], 'null')): """Recursively remove key/value pairs where the value is in ``remove``. This is targeted at comparing json-e rebuilt task definitions, since json-e drops key/value pairs with empty values. Args: values (dict/list): the dict or list ...
Recursively remove key/value pairs where the value is in ``remove``. This is targeted at comparing json-e rebuilt task definitions, since json-e drops key/value pairs with empty values. Args: values (dict/list): the dict or list to remove empty keys from. Returns: values (dict/list): ...
Below is the the instruction that describes the task: ### Input: Recursively remove key/value pairs where the value is in ``remove``. This is targeted at comparing json-e rebuilt task definitions, since json-e drops key/value pairs with empty values. Args: values (dict/list): the dict or list ...
def links(self): """ Return the URLs of all the links on a page together with information about their "rel" attribute, for determining which ones to treat as downloads and which ones to queue for further scraping. """ def clean(url): "Tidy up an URL." ...
Return the URLs of all the links on a page together with information about their "rel" attribute, for determining which ones to treat as downloads and which ones to queue for further scraping.
Below is the the instruction that describes the task: ### Input: Return the URLs of all the links on a page together with information about their "rel" attribute, for determining which ones to treat as downloads and which ones to queue for further scraping. ### Response: def links(self): ""...
def main(context, no_color): """ Ipa provides a Python API and command line utility for testing images. It can be used to test images in the Public Cloud (AWS, Azure, GCE, etc.). """ if context.obj is None: context.obj = {} context.obj['no_color'] = no_color
Ipa provides a Python API and command line utility for testing images. It can be used to test images in the Public Cloud (AWS, Azure, GCE, etc.).
Below is the the instruction that describes the task: ### Input: Ipa provides a Python API and command line utility for testing images. It can be used to test images in the Public Cloud (AWS, Azure, GCE, etc.). ### Response: def main(context, no_color): """ Ipa provides a Python API and command line u...
def connect_lv_generators(network, allow_multiple_genos_per_load=True): """Connect LV generators to existing grids. This function searches for unconnected generators in all LV grids and connects them. It connects * generators of voltage level 6 * to MV-LV station * genera...
Connect LV generators to existing grids. This function searches for unconnected generators in all LV grids and connects them. It connects * generators of voltage level 6 * to MV-LV station * generators of voltage level 7 * with a nom. capacity of <=30 kW to LV loa...
Below is the the instruction that describes the task: ### Input: Connect LV generators to existing grids. This function searches for unconnected generators in all LV grids and connects them. It connects * generators of voltage level 6 * to MV-LV station * generators of vo...
def parse_table_properties(doc, table, prop): "Parse table properties." if not table: return style = prop.find(_name('{{{w}}}tblStyle')) if style is not None: table.style_id = style.attrib[_name('{{{w}}}val')] doc.add_style_as_used(table.style_id)
Parse table properties.
Below is the the instruction that describes the task: ### Input: Parse table properties. ### Response: def parse_table_properties(doc, table, prop): "Parse table properties." if not table: return style = prop.find(_name('{{{w}}}tblStyle')) if style is not None: table.style_id = s...
def parse_unique_urlencoded(content): """Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated. """ urlenco...
Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated.
Below is the the instruction that describes the task: ### Input: Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repea...
def merge(self, keys): """ Merges the join on pseudo keys of two or more reference data sets. :param list[tuple[str,str]] keys: For each data set the keys of the start and end date. """ deletes = [] for pseudo_key, rows in self._rows.items(): self._additional...
Merges the join on pseudo keys of two or more reference data sets. :param list[tuple[str,str]] keys: For each data set the keys of the start and end date.
Below is the the instruction that describes the task: ### Input: Merges the join on pseudo keys of two or more reference data sets. :param list[tuple[str,str]] keys: For each data set the keys of the start and end date. ### Response: def merge(self, keys): """ Merges the join on pseudo key...
def create_snmp_manager(self, manager, host, **kwargs): """Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide o...
Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on th...
Below is the the instruction that describes the task: ### Input: Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide...
def dumps(self): """Return a dictionnary of current tables""" return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES}
Return a dictionnary of current tables
Below is the the instruction that describes the task: ### Input: Return a dictionnary of current tables ### Response: def dumps(self): """Return a dictionnary of current tables""" return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES}
def _compute_unitary_oracle_matrix(bitstring_map: Dict[str, str]) -> Tuple[np.ndarray, Dict[str, str]]: """ Computes the unitary matrix that encodes the oracle function used in the Bernstein-Vazirani algorithm. It ge...
Computes the unitary matrix that encodes the oracle function used in the Bernstein-Vazirani algorithm. It generates a dense matrix for a function :math:`f` .. math:: f:\\{0,1\\}^n\\rightarrow \\{0,1\\} \\mathbf{x}\\rightarrow \\mathbf{a}\\cdot\\mathbf{x}+b\\pmod{2} ...
Below is the the instruction that describes the task: ### Input: Computes the unitary matrix that encodes the oracle function used in the Bernstein-Vazirani algorithm. It generates a dense matrix for a function :math:`f` .. math:: f:\\{0,1\\}^n\\rightarrow \\{0,1\\} \\mathb...
def hash(self): ''' :rtype: int :return: hash of the field ''' hashed = super(String, self).hash() return khash(hashed, self._max_size)
:rtype: int :return: hash of the field
Below is the the instruction that describes the task: ### Input: :rtype: int :return: hash of the field ### Response: def hash(self): ''' :rtype: int :return: hash of the field ''' hashed = super(String, self).hash() return khash(hashed, self._max_size)
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [it...
Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
Below is the the instruction that describes the task: ### Input: Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python ### Response: def ...
def _add_layer_clicked(self): """Add layer clicked.""" layer = self.tree.selectedItems()[0] origin = layer.data(0, LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: parent = layer.data(0, LAYER_PARENT_ANALYSIS_ROLE) key = layer.data(0, LAYER_PURPOSE_KEY_OR_ID_...
Add layer clicked.
Below is the the instruction that describes the task: ### Input: Add layer clicked. ### Response: def _add_layer_clicked(self): """Add layer clicked.""" layer = self.tree.selectedItems()[0] origin = layer.data(0, LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: pare...
def event_params(segments, params, band=None, n_fft=None, slopes=None, prep=None, parent=None): """Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool...
Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool, or str 'dur', 'minamp', 'maxamp', 'ptp', 'rms', 'power', 'peakf', 'energy', 'peakef'. If 'all', a dict...
Below is the the instruction that describes the task: ### Input: Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool, or str 'dur', 'minamp', 'maxamp', 'ptp', '...
def verify(verified_entity, verification_key): """ Метод должен райзить ошибки :param verified_entity: сущность :param verification_key: ключ :return: """ verification = get_object_or_none(Verification, verified_entity=verified_entity) if verification is ...
Метод должен райзить ошибки :param verified_entity: сущность :param verification_key: ключ :return:
Below is the the instruction that describes the task: ### Input: Метод должен райзить ошибки :param verified_entity: сущность :param verification_key: ключ :return: ### Response: def verify(verified_entity, verification_key): """ Метод должен райзить ошибки :param ve...
def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains
Utility method to list all the domains in the jar.
Below is the the instruction that describes the task: ### Input: Utility method to list all the domains in the jar. ### Response: def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domai...
def teletex_search_function(name): """ Search function for teletex codec that is passed to codecs.register() """ if name != 'teletex': return None return codecs.CodecInfo( name='teletex', encode=TeletexCodec().encode, decode=TeletexCodec().decode, incrementa...
Search function for teletex codec that is passed to codecs.register()
Below is the the instruction that describes the task: ### Input: Search function for teletex codec that is passed to codecs.register() ### Response: def teletex_search_function(name): """ Search function for teletex codec that is passed to codecs.register() """ if name != 'teletex': return...
def null_space(M, k, k_skip=1, eigen_solver='arpack', random_state=None, solver_kwds=None): """ Find the null space of a matrix M: eigenvectors associated with 0 eigenvalues Parameters ---------- M : {array, matrix, sparse matrix, LinearOperator} Input covariance matrix: shou...
Find the null space of a matrix M: eigenvectors associated with 0 eigenvalues Parameters ---------- M : {array, matrix, sparse matrix, LinearOperator} Input covariance matrix: should be symmetric positive semi-definite k : integer Number of eigenvalues/vectors to return k_skip : int...
Below is the the instruction that describes the task: ### Input: Find the null space of a matrix M: eigenvectors associated with 0 eigenvalues Parameters ---------- M : {array, matrix, sparse matrix, LinearOperator} Input covariance matrix: should be symmetric positive semi-definite k : int...
def register_job_definition(self, json_fpath): """Register a job definition with AWS Batch, using a JSON""" with open(json_fpath) as f: job_def = json.load(f) response = self._client.register_job_definition(**job_def) status_code = response['ResponseMetadata']['HTTPStatusCode...
Register a job definition with AWS Batch, using a JSON
Below is the the instruction that describes the task: ### Input: Register a job definition with AWS Batch, using a JSON ### Response: def register_job_definition(self, json_fpath): """Register a job definition with AWS Batch, using a JSON""" with open(json_fpath) as f: job_def = json.lo...
def prox_min(X, step, thresh=0): """Projection onto numbers above `thresh` """ thresh_ = _step_gamma(step, thresh) below = X - thresh_ < 0 X[below] = thresh_ return X
Projection onto numbers above `thresh`
Below is the the instruction that describes the task: ### Input: Projection onto numbers above `thresh` ### Response: def prox_min(X, step, thresh=0): """Projection onto numbers above `thresh` """ thresh_ = _step_gamma(step, thresh) below = X - thresh_ < 0 X[below] = thresh_ return X
def _se_all(self): """Standard errors (SE) for all parameters, including the intercept.""" err = np.expand_dims(self._ms_err, axis=1) t1 = np.diagonal( np.linalg.inv(np.matmul(self.xwins.swapaxes(1, 2), self.xwins)), axis1=1, axis2=2, ) ...
Standard errors (SE) for all parameters, including the intercept.
Below is the the instruction that describes the task: ### Input: Standard errors (SE) for all parameters, including the intercept. ### Response: def _se_all(self): """Standard errors (SE) for all parameters, including the intercept.""" err = np.expand_dims(self._ms_err, axis=1) t1 = np.d...
def unit_key_from_name(name): """Return a legal python name for the given name for use as a unit key.""" result = name for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS): result = result.replace(old, new) # Collapse redundant underscores and convert to uppercase. result = re.sub(r'_+', '_', result.upp...
Return a legal python name for the given name for use as a unit key.
Below is the the instruction that describes the task: ### Input: Return a legal python name for the given name for use as a unit key. ### Response: def unit_key_from_name(name): """Return a legal python name for the given name for use as a unit key.""" result = name for old, new in six.iteritems(UNIT_KEY_RE...
def recover(self, key, value): """Get the deserialized value for a given key, and the serialized version.""" if key not in self._dtypes: self.read_types() if key not in self._dtypes: raise ValueError("Unknown datatype for {} and {}".format(key, value)) return self...
Get the deserialized value for a given key, and the serialized version.
Below is the the instruction that describes the task: ### Input: Get the deserialized value for a given key, and the serialized version. ### Response: def recover(self, key, value): """Get the deserialized value for a given key, and the serialized version.""" if key not in self._dtypes: ...
def step(step_name=None): """ Decorates functions that will be called by the `run` function. Decorator version of `add_step`. step name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to...
Decorates functions that will be called by the `run` function. Decorator version of `add_step`. step name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argumen...
Below is the the instruction that describes the task: ### Input: Decorates functions that will be called by the `run` function. Decorator version of `add_step`. step name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables...
def cli(env, billing_id, datacenter): """Adds a load balancer given the id returned from create-options.""" mgr = SoftLayer.LoadBalancerManager(env.client) if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAb...
Adds a load balancer given the id returned from create-options.
Below is the the instruction that describes the task: ### Input: Adds a load balancer given the id returned from create-options. ### Response: def cli(env, billing_id, datacenter): """Adds a load balancer given the id returned from create-options.""" mgr = SoftLayer.LoadBalancerManager(env.client) if ...
def get_assets_metadata(self): """Gets the metadata for the assets. return: (osid.Metadata) - metadata for the assets *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template ...
Gets the metadata for the assets. return: (osid.Metadata) - metadata for the assets *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the metadata for the assets. return: (osid.Metadata) - metadata for the assets *compliance: mandatory -- This method must be implemented.* ### Response: def get_assets_metadata(self): """Gets the metadata for the assets....
def MakeRanges(codes): """Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]""" ranges = [] last = -100 for c in codes: if c == last+1: ranges[-1][1] = c else: ranges.append([c, c]) last = c return ranges
Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]
Below is the the instruction that describes the task: ### Input: Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]] ### Response: def MakeRanges(codes): """Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]""" ranges = [] last = -100 for c in codes: if c == last+1: range...
def include_file_cb(include_path, line_ranges, symbol): """ Banana banana """ lang = '' if include_path.endswith((".md", ".markdown")): lang = 'markdown' else: split = os.path.splitext(include_path) if len(split) == 2: e...
Banana banana
Below is the the instruction that describes the task: ### Input: Banana banana ### Response: def include_file_cb(include_path, line_ranges, symbol): """ Banana banana """ lang = '' if include_path.endswith((".md", ".markdown")): lang = 'markdown' else: ...
def _diff(self, cursor, tokenizer, output_fh): """Returns output_fh with diff results that have been reduced. Uses a temporary file to store the results from `cursor` before being reduced, in order to not have the results stored in memory twice. :param cursor: database cursor c...
Returns output_fh with diff results that have been reduced. Uses a temporary file to store the results from `cursor` before being reduced, in order to not have the results stored in memory twice. :param cursor: database cursor containing raw diff data :type cursor: `sqlite3.Cur...
Below is the the instruction that describes the task: ### Input: Returns output_fh with diff results that have been reduced. Uses a temporary file to store the results from `cursor` before being reduced, in order to not have the results stored in memory twice. :param cursor: databa...
def delete_loadbalancer(self, datacenter_id, loadbalancer_id): """ Removes the load balancer from the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. ...
Removes the load balancer from the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type loadbalancer_id: ``str``
Below is the the instruction that describes the task: ### Input: Removes the load balancer from the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type ...
def get_rml(self, rml_name): """ returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve """ try: return getattr(self, rml_name) except AttributeError: return self.load_rml(rml_name)
returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve
Below is the the instruction that describes the task: ### Input: returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve ### Response: def get_rml(self, rml_name): """ returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve ...
def classes_can_admin(self): """Return all the classes (sorted) that this user can admin.""" if self.is_admin: return sorted(Session.query(Class).all()) else: return sorted(self.admin_for)
Return all the classes (sorted) that this user can admin.
Below is the the instruction that describes the task: ### Input: Return all the classes (sorted) that this user can admin. ### Response: def classes_can_admin(self): """Return all the classes (sorted) that this user can admin.""" if self.is_admin: return sorted(Session.query(Class).all(...
def get(self, buffer_type, offset): """Get a reading from the buffer at offset. Offset is specified relative to the start of the data buffer. This means that if the buffer rolls over, the offset for a given item will appear to change. Anyone holding an offset outside of this en...
Get a reading from the buffer at offset. Offset is specified relative to the start of the data buffer. This means that if the buffer rolls over, the offset for a given item will appear to change. Anyone holding an offset outside of this engine object will need to be notified when rollo...
Below is the the instruction that describes the task: ### Input: Get a reading from the buffer at offset. Offset is specified relative to the start of the data buffer. This means that if the buffer rolls over, the offset for a given item will appear to change. Anyone holding an offset outs...
def get(self, key, index=None): """Retrieves a value associated with a key from the database Args: key (str): The key to retrieve """ records = self.get_multi([key], index=index) try: return records[0][1] # return the value from the key/value tuple ...
Retrieves a value associated with a key from the database Args: key (str): The key to retrieve
Below is the the instruction that describes the task: ### Input: Retrieves a value associated with a key from the database Args: key (str): The key to retrieve ### Response: def get(self, key, index=None): """Retrieves a value associated with a key from the database Args: ...
def t_SEMICOLON(self, t): r';' t.endlexpos = t.lexpos + len(t.value) return t
r';
Below is the the instruction that describes the task: ### Input: r'; ### Response: def t_SEMICOLON(self, t): r';' t.endlexpos = t.lexpos + len(t.value) return t
def _parse_attribute_details_file(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ # Parse content from remote file URL, which may be stored in one of two places: # Starting at: contentInfo/MD_FeatureCatalogueDescription/featu...
Concatenates a list of Attribute Details data structures parsed from a remote file
Below is the the instruction that describes the task: ### Input: Concatenates a list of Attribute Details data structures parsed from a remote file ### Response: def _parse_attribute_details_file(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file ...
def volume_present(name, provider=None, **kwargs): ''' Check that a block volume exists. ''' ret = _check_name(name) if not ret['result']: return ret volumes = __salt__['cloud.volume_list'](provider=provider) if name in volumes: ret['comment'] = 'Volume exists: {0}'.format(...
Check that a block volume exists.
Below is the the instruction that describes the task: ### Input: Check that a block volume exists. ### Response: def volume_present(name, provider=None, **kwargs): ''' Check that a block volume exists. ''' ret = _check_name(name) if not ret['result']: return ret volumes = __salt__[...
def instruction_BMI(self, opcode, ea): """ Tests the state of the N (negative) bit and causes a branch if set. That is, branch if the sign of the twos complement result is negative. When used after an operation on signed binary values, this instruction will branch if the result ...
Tests the state of the N (negative) bit and causes a branch if set. That is, branch if the sign of the twos complement result is negative. When used after an operation on signed binary values, this instruction will branch if the result is minus. It is generally preferred to use the LBLT...
Below is the the instruction that describes the task: ### Input: Tests the state of the N (negative) bit and causes a branch if set. That is, branch if the sign of the twos complement result is negative. When used after an operation on signed binary values, this instruction will branch if t...
def get_priority_rules(db) -> Iterable[PriorityRule]: """Get file priority rules.""" cur = db.cursor() cur.execute('SELECT id, regexp, priority FROM file_priority') for row in cur: yield PriorityRule(*row)
Get file priority rules.
Below is the the instruction that describes the task: ### Input: Get file priority rules. ### Response: def get_priority_rules(db) -> Iterable[PriorityRule]: """Get file priority rules.""" cur = db.cursor() cur.execute('SELECT id, regexp, priority FROM file_priority') for row in cur: yield ...
def _serve_individual_image(self, request): """Serves an individual image.""" run = request.args.get('run') tag = request.args.get('tag') index = int(request.args.get('index')) sample = int(request.args.get('sample', 0)) data = self._get_individual_image(run, tag, index, sample) image_type =...
Serves an individual image.
Below is the the instruction that describes the task: ### Input: Serves an individual image. ### Response: def _serve_individual_image(self, request): """Serves an individual image.""" run = request.args.get('run') tag = request.args.get('tag') index = int(request.args.get('index')) sample = in...
def format_survival_rate(): """cr-rate Usage: cr-rate <session-file> Calculate the survival rate of a session. """ arguments = docopt.docopt( format_survival_rate.__doc__, version='cr-rate 1.0') with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db: rate = survival_r...
cr-rate Usage: cr-rate <session-file> Calculate the survival rate of a session.
Below is the the instruction that describes the task: ### Input: cr-rate Usage: cr-rate <session-file> Calculate the survival rate of a session. ### Response: def format_survival_rate(): """cr-rate Usage: cr-rate <session-file> Calculate the survival rate of a session. """ arguments...
def _check_query(self, query, style_cols=None): """Checks if query from Layer or QueryLayer is valid""" try: self.sql_client.send( utils.minify_sql(( 'EXPLAIN', 'SELECT', ' {style_cols}{comma}', ...
Checks if query from Layer or QueryLayer is valid
Below is the the instruction that describes the task: ### Input: Checks if query from Layer or QueryLayer is valid ### Response: def _check_query(self, query, style_cols=None): """Checks if query from Layer or QueryLayer is valid""" try: self.sql_client.send( utils.minif...
def randomize(length=6, choices=None): """Returns a random string of the given length.""" if type(choices) == str: choices = list(choices) choices = choices or ascii_lowercase return "".join(choice(choices) for _ in range(length))
Returns a random string of the given length.
Below is the the instruction that describes the task: ### Input: Returns a random string of the given length. ### Response: def randomize(length=6, choices=None): """Returns a random string of the given length.""" if type(choices) == str: choices = list(choices) choices = choices or ascii_lower...
def linkify_h_by_hd(self, hosts): """Add dependency in host objects :param hosts: hosts list :type hosts: alignak.objects.host.Hosts :return: None """ for hostdep in self: # Only used for debugging purpose when loops are detected setattr(hostdep, ...
Add dependency in host objects :param hosts: hosts list :type hosts: alignak.objects.host.Hosts :return: None
Below is the the instruction that describes the task: ### Input: Add dependency in host objects :param hosts: hosts list :type hosts: alignak.objects.host.Hosts :return: None ### Response: def linkify_h_by_hd(self, hosts): """Add dependency in host objects :param hosts: hos...
def timezone_name(dt, version=LATEST_VER): """ Determine an appropriate timezone for the given date/time object """ tz_rmap = get_tz_rmap(version=version) if dt.tzinfo is None: raise ValueError('%r has no timezone' % dt) # Easy case: pytz timezone. try: tz_name = dt.tzinfo.z...
Determine an appropriate timezone for the given date/time object
Below is the the instruction that describes the task: ### Input: Determine an appropriate timezone for the given date/time object ### Response: def timezone_name(dt, version=LATEST_VER): """ Determine an appropriate timezone for the given date/time object """ tz_rmap = get_tz_rmap(version=version) ...
def new(self, br, ino, sector_count, load_seg, media_name, system_type, platform_id, bootable): # type: (headervd.BootRecord, inode.Inode, int, int, str, int, int, bool) -> None ''' A method to create a new El Torito Boot Catalog. Parameters: br - The boot record th...
A method to create a new El Torito Boot Catalog. Parameters: br - The boot record that this El Torito Boot Catalog is associated with. ino - The Inode to associate with the initial entry. sector_count - The number of sectors for the initial entry. load_seg - The load segment...
Below is the the instruction that describes the task: ### Input: A method to create a new El Torito Boot Catalog. Parameters: br - The boot record that this El Torito Boot Catalog is associated with. ino - The Inode to associate with the initial entry. sector_count - The number o...
def generateHeader(self, sObjectType): ''' Generate a SOAP header as defined in: http://www.salesforce.com/us/developer/docs/api/Content/soap_headers.htm ''' try: return self._sforce.factory.create(sObjectType) except: print 'There is not a SOAP header of type %s' % sObjectType
Generate a SOAP header as defined in: http://www.salesforce.com/us/developer/docs/api/Content/soap_headers.htm
Below is the the instruction that describes the task: ### Input: Generate a SOAP header as defined in: http://www.salesforce.com/us/developer/docs/api/Content/soap_headers.htm ### Response: def generateHeader(self, sObjectType): ''' Generate a SOAP header as defined in: http://www.salesforce.com/us...
def assert_condition_md5(self): """If the ``Content-MD5`` request header is present in the request it's verified against the MD5 hash of the request body. If they don't match, a 400 HTTP response is returned. :raises: :class:`webob.exceptions.ResponseException` of status 400 if ...
If the ``Content-MD5`` request header is present in the request it's verified against the MD5 hash of the request body. If they don't match, a 400 HTTP response is returned. :raises: :class:`webob.exceptions.ResponseException` of status 400 if the MD5 hash does not match the bo...
Below is the the instruction that describes the task: ### Input: If the ``Content-MD5`` request header is present in the request it's verified against the MD5 hash of the request body. If they don't match, a 400 HTTP response is returned. :raises: :class:`webob.exceptions.ResponseException`...
def tiles_exist(self, process_tile=None, output_tile=None): """ Check whether output tiles of a tile (either process or output) exists. Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid`` output_tile : ``BufferedTil...
Check whether output tiles of a tile (either process or output) exists. Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid`` output_tile : ``BufferedTile`` must be member of output ``TilePyramid`` Returns ...
Below is the the instruction that describes the task: ### Input: Check whether output tiles of a tile (either process or output) exists. Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid`` output_tile : ``BufferedTile`` ...
def parameterized_send(self, request, parameter_list): """Send batched requests for a list of parameters Args: request (str): Request to send, like "%s.*?\n" parameter_list (list): parameters to format with, like ["TTLIN", "TTLOUT"] Returns: ...
Send batched requests for a list of parameters Args: request (str): Request to send, like "%s.*?\n" parameter_list (list): parameters to format with, like ["TTLIN", "TTLOUT"] Returns: dict: {parameter: response_queue}
Below is the the instruction that describes the task: ### Input: Send batched requests for a list of parameters Args: request (str): Request to send, like "%s.*?\n" parameter_list (list): parameters to format with, like ["TTLIN", "TTLOUT"] Returns: ...
def _apply_dvs_infrastructure_traffic_resources(infra_traffic_resources, resource_dicts): ''' Applies the values of the resource dictionaries to infra traffic resources, creating the infra traffic resource if required (vim.DistributedVirtualSwitchProductSp...
Applies the values of the resource dictionaries to infra traffic resources, creating the infra traffic resource if required (vim.DistributedVirtualSwitchProductSpec)
Below is the the instruction that describes the task: ### Input: Applies the values of the resource dictionaries to infra traffic resources, creating the infra traffic resource if required (vim.DistributedVirtualSwitchProductSpec) ### Response: def _apply_dvs_infrastructure_traffic_resources(infra_traffic_...
def _download_images(data, img_cols): """Download images given image columns.""" images = collections.defaultdict(list) for d in data: for img_col in img_cols: if d.get(img_col, None): if isinstance(d[img_col], Image.Image): # If it is already an Image, just copy and continue. ...
Download images given image columns.
Below is the the instruction that describes the task: ### Input: Download images given image columns. ### Response: def _download_images(data, img_cols): """Download images given image columns.""" images = collections.defaultdict(list) for d in data: for img_col in img_cols: if d.get(img_col, None...
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump=False, serialize=True): """Transform matplotlib.contourf to geojson with overlapp...
Transform matplotlib.contourf to geojson with overlapping filled contours.
Below is the the instruction that describes the task: ### Input: Transform matplotlib.contourf to geojson with overlapping filled contours. ### Response: def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opa...
def main(): """For testing purpose""" tcp_adapter = TcpAdapter("192.168.1.3", name="HASS", activate_source=False) hdmi_network = HDMINetwork(tcp_adapter) hdmi_network.start() while True: for d in hdmi_network.devices: _LOGGER.info("Device: %s", d) time.sleep(7)
For testing purpose
Below is the the instruction that describes the task: ### Input: For testing purpose ### Response: def main(): """For testing purpose""" tcp_adapter = TcpAdapter("192.168.1.3", name="HASS", activate_source=False) hdmi_network = HDMINetwork(tcp_adapter) hdmi_network.start() while True: f...
def run(self, evals, feed_dict=None, breakpoints=None, break_immediately=False): """ starts the debug session """ if not isinstance(evals,list): evals=[evals] if feed_dict is None: feed_dict={} if breakpoints is None: breakpoints=[] self.state=RUNNING self._original_evals=evals self._origina...
starts the debug session
Below is the the instruction that describes the task: ### Input: starts the debug session ### Response: def run(self, evals, feed_dict=None, breakpoints=None, break_immediately=False): """ starts the debug session """ if not isinstance(evals,list): evals=[evals] if feed_dict is None: feed_dict={} ...
def CreateRunner(self, **kw): """Make a new runner.""" self.runner = HuntRunner(self, token=self.token, **kw) return self.runner
Make a new runner.
Below is the the instruction that describes the task: ### Input: Make a new runner. ### Response: def CreateRunner(self, **kw): """Make a new runner.""" self.runner = HuntRunner(self, token=self.token, **kw) return self.runner
def search_tree(self, name): # noqa: D302 r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :raises: RuntimeError (Argument \`name\` is not valid) For example: >>> from __future__ import...
r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :raises: RuntimeError (Argument \`name\` is not valid) For example: >>> from __future__ import print_function >>> import pprint, ptri...
Below is the the instruction that describes the task: ### Input: r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :raises: RuntimeError (Argument \`name\` is not valid) For example: >>> from...
def div_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta informati...
Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information
Below is the the instruction that describes the task: ### Input: Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information ### Response: d...
def compute_residuals(self): """Compute residuals and stopping thresholds.""" if self.opt['AutoRho', 'StdResiduals']: r = np.linalg.norm(self.rsdl_r(self.AXnr, self.Y)) s = np.linalg.norm(self.rsdl_s(self.Yprev, self.Y)) epri = np.sqrt(self.Nc) * self.opt['AbsStopTol...
Compute residuals and stopping thresholds.
Below is the the instruction that describes the task: ### Input: Compute residuals and stopping thresholds. ### Response: def compute_residuals(self): """Compute residuals and stopping thresholds.""" if self.opt['AutoRho', 'StdResiduals']: r = np.linalg.norm(self.rsdl_r(self.AXnr, self...
def pad(lines, delim): """ Right Pads text split by their delim. :param lines: :param delim: :return: """ """ Populates text into chunks. If the delim was & then ['12 & 344', '344 & 8', '8 & 88'] would be stored in chunks as [['12', '344', '8'], ['344', '8', '88']] """ chunks = [] for i in range(len(lin...
Right Pads text split by their delim. :param lines: :param delim: :return:
Below is the the instruction that describes the task: ### Input: Right Pads text split by their delim. :param lines: :param delim: :return: ### Response: def pad(lines, delim): """ Right Pads text split by their delim. :param lines: :param delim: :return: """ """ Populates text into chunks. If the ...
def _prepare_for_training(self, job_name=None): """Set any values in the estimator that need to be set before training. Args: * job_name (str): Name of the training job to be created. If not specified, one is generated, using the base name given to the constructor if applica...
Set any values in the estimator that need to be set before training. Args: * job_name (str): Name of the training job to be created. If not specified, one is generated, using the base name given to the constructor if applicable.
Below is the the instruction that describes the task: ### Input: Set any values in the estimator that need to be set before training. Args: * job_name (str): Name of the training job to be created. If not specified, one is generated, using the base name given to the constructor ...
def recursively_save_dict_contents_to_group(h5file, path, dic): """ Parameters ---------- h5file: h5py file to be written to path: path within h5py file to saved dictionary dic: python dictionary to be converted to hdf5 format """ for key, item in dic.items(): ...
Parameters ---------- h5file: h5py file to be written to path: path within h5py file to saved dictionary dic: python dictionary to be converted to hdf5 format
Below is the the instruction that describes the task: ### Input: Parameters ---------- h5file: h5py file to be written to path: path within h5py file to saved dictionary dic: python dictionary to be converted to hdf5 format ### Response: def recursively_save_dict_contents_to...
def hidden(self): """return list of hidden members""" members = [self.member_info(item["_id"]) for item in self.members()] result = [] for member in members: if member['rsInfo'].get('hidden'): server_id = member['server_id'] result.append({ ...
return list of hidden members
Below is the the instruction that describes the task: ### Input: return list of hidden members ### Response: def hidden(self): """return list of hidden members""" members = [self.member_info(item["_id"]) for item in self.members()] result = [] for member in members: if m...
def render_to_string(self, template_file, context): """Render given template to string and add object to context""" context = context if context else {} if self.object: context['object'] = self.object context[self.object.__class__.__name__.lower()] = self.object r...
Render given template to string and add object to context
Below is the the instruction that describes the task: ### Input: Render given template to string and add object to context ### Response: def render_to_string(self, template_file, context): """Render given template to string and add object to context""" context = context if context else {} i...
def tag_secondary_structure(self, force=False): """Tags each `Residue` of the `Polypeptide` with secondary structure. Notes ----- DSSP must be available to call. Check by running `isambard.external_programs.dssp.test_dssp`. If DSSP is not available, please follow instruc...
Tags each `Residue` of the `Polypeptide` with secondary structure. Notes ----- DSSP must be available to call. Check by running `isambard.external_programs.dssp.test_dssp`. If DSSP is not available, please follow instruction here to add it: https://github.com/woolfson-gr...
Below is the the instruction that describes the task: ### Input: Tags each `Residue` of the `Polypeptide` with secondary structure. Notes ----- DSSP must be available to call. Check by running `isambard.external_programs.dssp.test_dssp`. If DSSP is not available, please foll...
def _init_qualifier(qualifier, qual_repo): """ Initialize the flavors of a qualifier from the qualifier repo and initialize propagated. """ qual_dict_entry = qual_repo[qualifier.name] qualifier.propagated = False if qualifier.tosubclass is None: if qua...
Initialize the flavors of a qualifier from the qualifier repo and initialize propagated.
Below is the the instruction that describes the task: ### Input: Initialize the flavors of a qualifier from the qualifier repo and initialize propagated. ### Response: def _init_qualifier(qualifier, qual_repo): """ Initialize the flavors of a qualifier from the qualifier repo and in...
def from_xuid(cls, xuid): ''' Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ''' url = 'https://profile.xboxlive....
Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance
Below is the the instruction that describes the task: ### Input: Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ### Response: def from_xuid(c...
def segment(args): """ %prog segment loss.ids bedfile Merge adjacent gene loss into segmental loss. Then based on the segmental loss, estimate amount of DNA loss in base pairs. Two estimates can be given: - conservative: just within the start and end of a single gene - aggressive: extend t...
%prog segment loss.ids bedfile Merge adjacent gene loss into segmental loss. Then based on the segmental loss, estimate amount of DNA loss in base pairs. Two estimates can be given: - conservative: just within the start and end of a single gene - aggressive: extend the deletion track to the next g...
Below is the the instruction that describes the task: ### Input: %prog segment loss.ids bedfile Merge adjacent gene loss into segmental loss. Then based on the segmental loss, estimate amount of DNA loss in base pairs. Two estimates can be given: - conservative: just within the start and end of a ...
def _get_Berger_data(verbose=True): '''Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray ''' # The first column of the data file is used as the row index, and represents kyr from present orbit91_pd, path = load_data_source(local_path = local_path, r...
Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray
Below is the the instruction that describes the task: ### Input: Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray ### Response: def _get_Berger_data(verbose=True): '''Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray ''' # The first...
def _unzip_file(self, src_path, dest_path, filename): """unzips file located at src_path into destination_path""" self.logger.info("unzipping file...") # construct full path (including file name) for unzipping unzip_path = os.path.join(dest_path, filename) utils.ensure_directory...
unzips file located at src_path into destination_path
Below is the the instruction that describes the task: ### Input: unzips file located at src_path into destination_path ### Response: def _unzip_file(self, src_path, dest_path, filename): """unzips file located at src_path into destination_path""" self.logger.info("unzipping file...") # con...
def get_user(self, user_id): """ Return user object. :param user_id: primary key of user object :return: user object """ user_model = get_user_model() try: return user_model.objects.get(id=user_id) except user_model.DoesNotExist: re...
Return user object. :param user_id: primary key of user object :return: user object
Below is the the instruction that describes the task: ### Input: Return user object. :param user_id: primary key of user object :return: user object ### Response: def get_user(self, user_id): """ Return user object. :param user_id: primary key of user object :return:...
def iterative_stratification(node_label_matrix, training_set_size, number_of_categories, random_seed=0): """ Iterative data fold stratification/balancing for two folds. Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011). On the stratification of multi-label data. In Ma...
Iterative data fold stratification/balancing for two folds. Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011). On the stratification of multi-label data. In Machine Learning and Knowledge Discovery in Databases (pp. 145-158). Springer Berlin Heidelberg. Inp...
Below is the the instruction that describes the task: ### Input: Iterative data fold stratification/balancing for two folds. Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011). On the stratification of multi-label data. In Machine Learning and Knowledge Discovery in Databa...
def _overwrite_special_dates(midnight_utcs, opens_or_closes, special_opens_or_closes): """ Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment. """ # Short circuit when noth...
Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment.
Below is the the instruction that describes the task: ### Input: Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment. ### Response: def _overwrite_special_dates(midnight_utcs, opens_or_closes, ...
def _handle_command(self, buffer): " When text is accepted in the command line. " text = buffer.text # First leave command mode. We want to make sure that the working # pane is focused again before executing the command handers. self.pymux.leave_command_mode(append_to_history=Tr...
When text is accepted in the command line.
Below is the the instruction that describes the task: ### Input: When text is accepted in the command line. ### Response: def _handle_command(self, buffer): " When text is accepted in the command line. " text = buffer.text # First leave command mode. We want to make sure that the working ...
def reject_entry(request, entry_id): """ Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix. """ return_url = request.GET.get('next', reverse('dashboard')) try: entry = Entry.no_join.get(pk=entry_id) ex...
Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix.
Below is the the instruction that describes the task: ### Input: Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix. ### Response: def reject_entry(request, entry_id): """ Admins can reject an entry that has been verified...
def _write_cpr(self, f, cType, parameter) -> int: ''' Write compression info to the end of the file in a CPR. ''' f.seek(0, 2) byte_loc = f.tell() block_size = CDF.CPR_BASE_SIZE64 + 4 section_type = CDF.CPR_ rfuA = 0 pCount = 1 cpr = bytea...
Write compression info to the end of the file in a CPR.
Below is the the instruction that describes the task: ### Input: Write compression info to the end of the file in a CPR. ### Response: def _write_cpr(self, f, cType, parameter) -> int: ''' Write compression info to the end of the file in a CPR. ''' f.seek(0, 2) byte_loc = f....
def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, act...
Return a script that'll work in a relocatable environment.
Below is the the instruction that describes the task: ### Input: Return a script that'll work in a relocatable environment. ### Response: def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpa...
def getScreenBounds(self, screenId): """ Returns the screen size of the specified monitor (0 being the main monitor). """ screen_details = self.getScreenDetails() if not isinstance(screenId, int) or screenId < -1 or screenId >= len(screen_details): raise ValueError("Invalid screen ID...
Returns the screen size of the specified monitor (0 being the main monitor).
Below is the the instruction that describes the task: ### Input: Returns the screen size of the specified monitor (0 being the main monitor). ### Response: def getScreenBounds(self, screenId): """ Returns the screen size of the specified monitor (0 being the main monitor). """ screen_details = self...
def _bar(s, align, colors, width=100, vmin=None, vmax=None): """ Draw bar chart in dataframe cells. """ # Get input value range. smin = s.min() if vmin is None else vmin if isinstance(smin, ABCSeries): smin = smin.min() smax = s.max() if vmax is None e...
Draw bar chart in dataframe cells.
Below is the the instruction that describes the task: ### Input: Draw bar chart in dataframe cells. ### Response: def _bar(s, align, colors, width=100, vmin=None, vmax=None): """ Draw bar chart in dataframe cells. """ # Get input value range. smin = s.min() if vmin is None e...
def refreshRecords( self ): """ Refreshes the records being loaded by this browser. """ table_type = self.tableType() if ( not table_type ): self._records = RecordSet() return False search = nativestring(self.uiSearchTXT.text()) ...
Refreshes the records being loaded by this browser.
Below is the the instruction that describes the task: ### Input: Refreshes the records being loaded by this browser. ### Response: def refreshRecords( self ): """ Refreshes the records being loaded by this browser. """ table_type = self.tableType() if ( not table_type )...
def dframe(self, dimensions=None, multi_index=False): """Convert dimension values to DataFrame. Returns a pandas dataframe of columns along each dimension, either completely flat or indexed by key dimensions. Args: dimensions: Dimensions to return as columns mul...
Convert dimension values to DataFrame. Returns a pandas dataframe of columns along each dimension, either completely flat or indexed by key dimensions. Args: dimensions: Dimensions to return as columns multi_index: Convert key dimensions to (multi-)index Return...
Below is the the instruction that describes the task: ### Input: Convert dimension values to DataFrame. Returns a pandas dataframe of columns along each dimension, either completely flat or indexed by key dimensions. Args: dimensions: Dimensions to return as columns ...
def _add_junction(item): ''' Adds a junction to the _current_statement. ''' type_, channels = _expand_one_key_dictionary(item) junction = UnnamedStatement(type='junction') for item in channels: type_, value = _expand_one_key_dictionary(item) channel = UnnamedStatement(type='chann...
Adds a junction to the _current_statement.
Below is the the instruction that describes the task: ### Input: Adds a junction to the _current_statement. ### Response: def _add_junction(item): ''' Adds a junction to the _current_statement. ''' type_, channels = _expand_one_key_dictionary(item) junction = UnnamedStatement(type='junction') ...
def to_dict(self): """ Get a dictionary representation of :class:`InstanceResource` """ self_dict = {} for key, value in six.iteritems(self.__dict__): if self.allowed_params and key in self.allowed_params: self_dict[key] = value return self_dic...
Get a dictionary representation of :class:`InstanceResource`
Below is the the instruction that describes the task: ### Input: Get a dictionary representation of :class:`InstanceResource` ### Response: def to_dict(self): """ Get a dictionary representation of :class:`InstanceResource` """ self_dict = {} for key, value in six.iteritems(...
def normalize_name(decl): """ Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name """ if decl.cache.normalized_name is None: decl.cache.normalized_name = normalize(decl.name) return decl.cache.normalized_...
Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name
Below is the the instruction that describes the task: ### Input: Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name ### Response: def normalize_name(decl): """ Cached variant of normalize Args: decl (decla...