code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def kvectors(self, norm=False, form='broadcast', real=False, shift=False): """ Return the kvectors associated with this tile, given the standard form of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to `Tile.coords`. Parameters ----------- r...
Return the kvectors associated with this tile, given the standard form of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to `Tile.coords`. Parameters ----------- real : boolean whether to return kvectors associated with the real fft instead
Below is the the instruction that describes the task: ### Input: Return the kvectors associated with this tile, given the standard form of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to `Tile.coords`. Parameters ----------- real : boolean ...
def new(self): # type: () -> None ''' A method to create a new UDF Anchor Volume Structure. Parameters: None. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF Anchor Volume Structure alread...
A method to create a new UDF Anchor Volume Structure. Parameters: None. Returns: Nothing.
Below is the the instruction that describes the task: ### Input: A method to create a new UDF Anchor Volume Structure. Parameters: None. Returns: Nothing. ### Response: def new(self): # type: () -> None ''' A method to create a new UDF Anchor Volume Struct...
def _load_ssh_files(self): """ Trigger loading of configured SSH config file paths. Expects that ``base_ssh_config`` has already been set to an `~paramiko.config.SSHConfig` object. :returns: ``None``. """ # TODO: does this want to more closely ape the behavior o...
Trigger loading of configured SSH config file paths. Expects that ``base_ssh_config`` has already been set to an `~paramiko.config.SSHConfig` object. :returns: ``None``.
Below is the the instruction that describes the task: ### Input: Trigger loading of configured SSH config file paths. Expects that ``base_ssh_config`` has already been set to an `~paramiko.config.SSHConfig` object. :returns: ``None``. ### Response: def _load_ssh_files(self): """ ...
def get_vmpolicy_macaddr_output_vmpolicy_macaddr_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr") config = get_vmpolicy_macaddr output = ET.SubElement(get_vmpolicy_macaddr, "output") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_vmpolicy_macaddr_output_vmpolicy_macaddr_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr"...
def prune_loop_for_kic(self, loops_segments, search_radius, expected_min_loop_length = None, expected_max_loop_length = None, generate_pymol_session = False): '''A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method.''' return s...
A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method.
Below is the the instruction that describes the task: ### Input: A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method. ### Response: def prune_loop_for_kic(self, loops_segments, search_radius, expected_min_loop_length = None, expected_max...
def _validate_config(self, config): """ Validates that all necessary config parameters are specified. :type config: dict[str, dict[str, Any] | str] :param config: the module config """ if config is None: raise ValueError("OIDCFrontend conf can't be 'None'.") ...
Validates that all necessary config parameters are specified. :type config: dict[str, dict[str, Any] | str] :param config: the module config
Below is the the instruction that describes the task: ### Input: Validates that all necessary config parameters are specified. :type config: dict[str, dict[str, Any] | str] :param config: the module config ### Response: def _validate_config(self, config): """ Validates that all nece...
def get(self, **params): """ Return a list of commands that where affected by a recent change (following a poll() return for the controlling file descriptor). Each list element is a tuple: (name, command_path, module_list) The event queue will be read multiple time...
Return a list of commands that where affected by a recent change (following a poll() return for the controlling file descriptor). Each list element is a tuple: (name, command_path, module_list) The event queue will be read multiple times and reads continue until a timeout ...
Below is the the instruction that describes the task: ### Input: Return a list of commands that where affected by a recent change (following a poll() return for the controlling file descriptor). Each list element is a tuple: (name, command_path, module_list) The event queue wi...
def help_center_user_segment_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/user_segments#create-user-segment" api_path = "/api/v2/help_center/user_segments.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/user_segments#create-user-segment
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/help_center/user_segments#create-user-segment ### Response: def help_center_user_segment_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/user_segments#create-u...
def numericise(value, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty...
Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input string, empty or not, otherwise. Executable examples: >>> ...
Below is the the instruction that describes the task: ### Input: Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input...
def on_zijd_mark(self, event): """ Get mouse position on double right click find the interpretation in range of mouse position then mark that interpretation bad or good Parameters ---------- event : the wx Mouseevent for that click Alters ------ ...
Get mouse position on double right click find the interpretation in range of mouse position then mark that interpretation bad or good Parameters ---------- event : the wx Mouseevent for that click Alters ------ current_fit
Below is the the instruction that describes the task: ### Input: Get mouse position on double right click find the interpretation in range of mouse position then mark that interpretation bad or good Parameters ---------- event : the wx Mouseevent for that click Alte...
def word_frequency(word, lang, wordlist='best', minimum=0.): """ Get the frequency of `word` in the language with code `lang`, from the specified `wordlist`. These wordlists can be specified: - 'large': a wordlist built from at least 5 sources, containing word frequencies of 10^-8 and higher...
Get the frequency of `word` in the language with code `lang`, from the specified `wordlist`. These wordlists can be specified: - 'large': a wordlist built from at least 5 sources, containing word frequencies of 10^-8 and higher - 'small': a wordlist built from at least 3 sources, containing word...
Below is the the instruction that describes the task: ### Input: Get the frequency of `word` in the language with code `lang`, from the specified `wordlist`. These wordlists can be specified: - 'large': a wordlist built from at least 5 sources, containing word frequencies of 10^-8 and higher ...
def load_objects(self, addr, num_bytes, ret_on_segv=False): """ Load memory objects from paged memory. :param addr: Address to start loading. :param num_bytes: Number of bytes to load. :param bool ret_on_segv: True if you want load_bytes to return directly when a SIGSEV is trigg...
Load memory objects from paged memory. :param addr: Address to start loading. :param num_bytes: Number of bytes to load. :param bool ret_on_segv: True if you want load_bytes to return directly when a SIGSEV is triggered, otherwise a SimSegfaultError will be rais...
Below is the the instruction that describes the task: ### Input: Load memory objects from paged memory. :param addr: Address to start loading. :param num_bytes: Number of bytes to load. :param bool ret_on_segv: True if you want load_bytes to return directly when a SIGSEV is triggered, other...
def fromJSON(jsonValue): """returns a featureset from a JSON string""" jd = json.loads(jsonValue) features = [] if 'fields' in jd: fields = jd['fields'] else: fields = {'fields':[]} if 'features' in jd: for feat in jd['features']: ...
returns a featureset from a JSON string
Below is the the instruction that describes the task: ### Input: returns a featureset from a JSON string ### Response: def fromJSON(jsonValue): """returns a featureset from a JSON string""" jd = json.loads(jsonValue) features = [] if 'fields' in jd: fields = jd['fields']...
def _get_ln_a_n_max(self, C, n_sites, idx, rup): """ Defines the rock site amplification defined in equations 10a and 10b """ ln_a_n_max = C["lnSC1AM"] * np.ones(n_sites) for i in [2, 3, 4]: if np.any(idx[i]): ln_a_n_max[idx[i]] += C["S{:g}".format(i)]...
Defines the rock site amplification defined in equations 10a and 10b
Below is the the instruction that describes the task: ### Input: Defines the rock site amplification defined in equations 10a and 10b ### Response: def _get_ln_a_n_max(self, C, n_sites, idx, rup): """ Defines the rock site amplification defined in equations 10a and 10b """ ln_a_n_ma...
def calc_contours(data, num_contours): """Get sets of contour points for numpy array `data`. `num_contours` specifies the number (int) of contours to make. Returns a list of numpy arrays of points--each array makes a polygon if plotted as such. """ mn = np.nanmean(data) top = np.nanmax(data)...
Get sets of contour points for numpy array `data`. `num_contours` specifies the number (int) of contours to make. Returns a list of numpy arrays of points--each array makes a polygon if plotted as such.
Below is the the instruction that describes the task: ### Input: Get sets of contour points for numpy array `data`. `num_contours` specifies the number (int) of contours to make. Returns a list of numpy arrays of points--each array makes a polygon if plotted as such. ### Response: def calc_contours(dat...
def acquire_direct(self, address): """ Acquire a connection to a given address from the pool. The address supplied should always be an IP address, not a host name. This method is thread safe. """ if self.closed(): raise ServiceUnavailable("Connection pool clo...
Acquire a connection to a given address from the pool. The address supplied should always be an IP address, not a host name. This method is thread safe.
Below is the the instruction that describes the task: ### Input: Acquire a connection to a given address from the pool. The address supplied should always be an IP address, not a host name. This method is thread safe. ### Response: def acquire_direct(self, address): """ Acquire a c...
def sync_client(self): """Synchronous OAuth 2.0 Bearer client""" if not self._sync_client: self._sync_client = AlfSyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=se...
Synchronous OAuth 2.0 Bearer client
Below is the the instruction that describes the task: ### Input: Synchronous OAuth 2.0 Bearer client ### Response: def sync_client(self): """Synchronous OAuth 2.0 Bearer client""" if not self._sync_client: self._sync_client = AlfSyncClient( token_endpoint=self.config.get...
def TimeFromTicks(ticks, tz=None): """Construct a DB-API time value from the given ticks value. :type ticks: float :param ticks: a number of seconds since the epoch; see the documentation of the standard Python time module for details. :type tz: :class:`datetime.tzinfo` :param tz: ...
Construct a DB-API time value from the given ticks value. :type ticks: float :param ticks: a number of seconds since the epoch; see the documentation of the standard Python time module for details. :type tz: :class:`datetime.tzinfo` :param tz: (Optional) time zone to use for conversion...
Below is the the instruction that describes the task: ### Input: Construct a DB-API time value from the given ticks value. :type ticks: float :param ticks: a number of seconds since the epoch; see the documentation of the standard Python time module for details. :type tz: :class:`datet...
def open_file(self, store=current_store, use_seek=False): """The shorthand of :meth:`~Image.open_file()` for the :attr:`original`. :param store: the storage which contains the image files :data:`~sqlalchemy_imageattach.context.current_store` by defaul...
The shorthand of :meth:`~Image.open_file()` for the :attr:`original`. :param store: the storage which contains the image files :data:`~sqlalchemy_imageattach.context.current_store` by default :type store: :class:`~sqlalchemy_imageattach.store.Store` ...
Below is the the instruction that describes the task: ### Input: The shorthand of :meth:`~Image.open_file()` for the :attr:`original`. :param store: the storage which contains the image files :data:`~sqlalchemy_imageattach.context.current_store` by defaul...
def unpack_rsp(cls, rsp_pb): """Convert from PLS response to user response""" if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None order_id = str(rsp_pb.s2c.orderID) modify_order_list = [{ 'trd_env': TRADE.REV_TRD_ENV_MAP[rsp_pb.s2c.header.trdEnv], ...
Convert from PLS response to user response
Below is the the instruction that describes the task: ### Input: Convert from PLS response to user response ### Response: def unpack_rsp(cls, rsp_pb): """Convert from PLS response to user response""" if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None order_id = ...
def com_google_fonts_check_name_trailing_spaces(ttFont): """Name table records must not have trailing spaces.""" failed = False for name_record in ttFont['name'].names: name_string = name_record.toUnicode() if name_string != name_string.strip(): failed = True name_key = tuple([name_record.plat...
Name table records must not have trailing spaces.
Below is the the instruction that describes the task: ### Input: Name table records must not have trailing spaces. ### Response: def com_google_fonts_check_name_trailing_spaces(ttFont): """Name table records must not have trailing spaces.""" failed = False for name_record in ttFont['name'].names: name_st...
def DbGetClassPropertyList(self, argin): """ Get property list for a given Tango class with a specified filter :param argin: The filter :type: tango.DevString :return: Property name list :rtype: tango.DevVarStringArray """ self._log.debug("In DbGetClassPropertyList()") ...
Get property list for a given Tango class with a specified filter :param argin: The filter :type: tango.DevString :return: Property name list :rtype: tango.DevVarStringArray
Below is the the instruction that describes the task: ### Input: Get property list for a given Tango class with a specified filter :param argin: The filter :type: tango.DevString :return: Property name list :rtype: tango.DevVarStringArray ### Response: def DbGetClassPropertyList(se...
def _to_string(self): """Implemented a function for __str__ and __repr__ to use, but which prevents infinite recursion when migrating to Python 3""" if self.sections: start = "/" if self.bound_start else "**/" sections = "/**/".join(str(section) for section in self.sectio...
Implemented a function for __str__ and __repr__ to use, but which prevents infinite recursion when migrating to Python 3
Below is the the instruction that describes the task: ### Input: Implemented a function for __str__ and __repr__ to use, but which prevents infinite recursion when migrating to Python 3 ### Response: def _to_string(self): """Implemented a function for __str__ and __repr__ to use, but which ...
def _remove_string_from_commastring(self, field, string): # type: (str, str) -> bool """Remove a string from a comma separated list of strings Args: field (str): Field containing comma separated list string (str): String to remove Returns: bool: True...
Remove a string from a comma separated list of strings Args: field (str): Field containing comma separated list string (str): String to remove Returns: bool: True if string removed or False if not
Below is the the instruction that describes the task: ### Input: Remove a string from a comma separated list of strings Args: field (str): Field containing comma separated list string (str): String to remove Returns: bool: True if string removed or False if not ...
def _retstr(ins): """ Returns from a procedure / function a string pointer (16bits) value """ tmp, output = _str_oper(ins.quad[1], no_exaf=True) if not tmp: output.append('call __LOADSTR') REQUIRES.add('loadstr.asm') output.append('#pragma opt require hl') output.append('jp %s'...
Returns from a procedure / function a string pointer (16bits) value
Below is the the instruction that describes the task: ### Input: Returns from a procedure / function a string pointer (16bits) value ### Response: def _retstr(ins): """ Returns from a procedure / function a string pointer (16bits) value """ tmp, output = _str_oper(ins.quad[1], no_exaf=True) if not...
def _write(self, session, openFile, replaceParamFile): """ Storm Pipe Network File Write to File Method """ # Retrieve Connection objects and write to file connections = self.connections self._writeConnections(connections=connections, fileOb...
Storm Pipe Network File Write to File Method
Below is the the instruction that describes the task: ### Input: Storm Pipe Network File Write to File Method ### Response: def _write(self, session, openFile, replaceParamFile): """ Storm Pipe Network File Write to File Method """ # Retrieve Connection objects and write to file ...
def _create_pipe(self): """ Creates a new pipe and returns the child end of the connection. To request an account from the pipe, use:: pipe = queue._create_pipe() # Let the account manager choose an account. pipe.send(('acquire-account-for-host', host)) ...
Creates a new pipe and returns the child end of the connection. To request an account from the pipe, use:: pipe = queue._create_pipe() # Let the account manager choose an account. pipe.send(('acquire-account-for-host', host)) account = pipe.recv() .....
Below is the the instruction that describes the task: ### Input: Creates a new pipe and returns the child end of the connection. To request an account from the pipe, use:: pipe = queue._create_pipe() # Let the account manager choose an account. pipe.send(('acquire-accou...
def compute_samples(self): """ Sample from a Normal distribution with inferred mu and std """ eps = tf.random_normal([self.batch_size, self.eq_samples, self.iw_samples, self.num_latent]) z = tf.reshape(eps * self.std + self.mu, [-1, self.num_latent]) return z
Sample from a Normal distribution with inferred mu and std
Below is the the instruction that describes the task: ### Input: Sample from a Normal distribution with inferred mu and std ### Response: def compute_samples(self): """ Sample from a Normal distribution with inferred mu and std """ eps = tf.random_normal([self.batch_size, self.eq_samples, self.iw_s...
def oauth_token_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#show-token" api_path = "/api/v2/oauth/tokens/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#show-token
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#show-token ### Response: def oauth_token_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#show-token" api_path = "/api/v2/oauth/toke...
def _authenticate_ssh(org): """Try authenticating via ssh, if succesful yields a User, otherwise raises Error.""" # Try to get username from git config username = os.environ.get(f"{org.upper()}_USERNAME") # Require ssh-agent child = pexpect.spawn("ssh -T git@github.com", encoding="utf8") # GitHu...
Try authenticating via ssh, if succesful yields a User, otherwise raises Error.
Below is the the instruction that describes the task: ### Input: Try authenticating via ssh, if succesful yields a User, otherwise raises Error. ### Response: def _authenticate_ssh(org): """Try authenticating via ssh, if succesful yields a User, otherwise raises Error.""" # Try to get username from git con...
def d(msg, *args, **kwargs): ''' log a message at debug level; ''' return logging.log(DEBUG, msg, *args, **kwargs)
log a message at debug level;
Below is the the instruction that describes the task: ### Input: log a message at debug level; ### Response: def d(msg, *args, **kwargs): ''' log a message at debug level; ''' return logging.log(DEBUG, msg, *args, **kwargs)
def appdata_roaming_dir(): """Returns the roaming AppData directory for the installed ArcGIS Desktop.""" install = arcpy.GetInstallInfo('desktop') app_data = arcpy.GetSystemEnvironment("APPDATA") product_dir = ''.join((install['ProductName'], major_version())) return os.path.join(app_data, 'ESRI', p...
Returns the roaming AppData directory for the installed ArcGIS Desktop.
Below is the the instruction that describes the task: ### Input: Returns the roaming AppData directory for the installed ArcGIS Desktop. ### Response: def appdata_roaming_dir(): """Returns the roaming AppData directory for the installed ArcGIS Desktop.""" install = arcpy.GetInstallInfo('desktop') app_d...
def terminate(self): """Terminate the child process. It is not an error to call this method when the child has already exited. """ try: self.send_signal(signal.SIGTERM) except pyuv.error.ProcessError as e: if e.args[0] != pyuv.errno.UV_ESRCH: ...
Terminate the child process. It is not an error to call this method when the child has already exited.
Below is the the instruction that describes the task: ### Input: Terminate the child process. It is not an error to call this method when the child has already exited. ### Response: def terminate(self): """Terminate the child process. It is not an error to call this method when the child ...
def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats...
Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status
Below is the the instruction that describes the task: ### Input: Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ### Response: def all_status(): ''' Return a composite of all st...
def get_file_list(file_dir, regex=''): """ Creates a list of files that match the search_regex within file_dir. The list of files will have file_dir as path prefix. Parameters ---------- @param file_dir: @param search_regex: Returns: -------- List of paths to files that match ...
Creates a list of files that match the search_regex within file_dir. The list of files will have file_dir as path prefix. Parameters ---------- @param file_dir: @param search_regex: Returns: -------- List of paths to files that match the search_regex
Below is the the instruction that describes the task: ### Input: Creates a list of files that match the search_regex within file_dir. The list of files will have file_dir as path prefix. Parameters ---------- @param file_dir: @param search_regex: Returns: -------- List of paths to...
def drop(self, filter_func=None, stash='active'): """ Drops states from a stash. This is an alias for move(), with defaults for the stashes. :param filter_func: Drop states that match this filter. Should be a function that takes a state and returns True or False. (de...
Drops states from a stash. This is an alias for move(), with defaults for the stashes. :param filter_func: Drop states that match this filter. Should be a function that takes a state and returns True or False. (default: drop all states) :param stash: Drop matching stat...
Below is the the instruction that describes the task: ### Input: Drops states from a stash. This is an alias for move(), with defaults for the stashes. :param filter_func: Drop states that match this filter. Should be a function that takes a state and returns True or False. (def...
def plot_data(): '''Plot sample data up with the fancy colormaps. ''' var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM'] # colorbar limits for each property lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2]...
Plot sample data up with the fancy colormaps.
Below is the the instruction that describes the task: ### Input: Plot sample data up with the fancy colormaps. ### Response: def plot_data(): '''Plot sample data up with the fancy colormaps. ''' var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM...
def matrix_chain_mult(M): """Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications """ opt, arg = matrix_mult_opt_order(M) return _apply_order(M, arg, 0, len(M)-1)
Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications
Below is the the instruction that describes the task: ### Input: Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications ### Response: def matrix_chain_mult(M): """Matrix chain multip...
def delete(self, item, dry_run=None): """Deletes item in file.""" logger.debug('Deleting item. Item: {item} Table: {namespace}'.format( item=item, namespace=self.namespace )) if not dry_run: self.table.delete_item(Key={'id': item['id']}) retu...
Deletes item in file.
Below is the the instruction that describes the task: ### Input: Deletes item in file. ### Response: def delete(self, item, dry_run=None): """Deletes item in file.""" logger.debug('Deleting item. Item: {item} Table: {namespace}'.format( item=item, namespace=self.namespace ...
def get(self, section, name, default=None, **kw): """Replacement for :func:`boto.pyami.config.Config.get()`.""" try: return self.unbound_method(self.instance, section, name, **kw) except Exception: return default
Replacement for :func:`boto.pyami.config.Config.get()`.
Below is the the instruction that describes the task: ### Input: Replacement for :func:`boto.pyami.config.Config.get()`. ### Response: def get(self, section, name, default=None, **kw): """Replacement for :func:`boto.pyami.config.Config.get()`.""" try: return self.unbound_method(self.ins...
def permission_required(perm, queryset_or_model=None, login_url=None, raise_exception=False): """ Permission check decorator for classbased/functional generic view This decorator works as class, method or function decorator without any modification. DO NOT use ``method_decor...
Permission check decorator for classbased/functional generic view This decorator works as class, method or function decorator without any modification. DO NOT use ``method_decorator`` or whatever while this decorator will use ``self`` argument for method of classbased generic view. Parameters ...
Below is the the instruction that describes the task: ### Input: Permission check decorator for classbased/functional generic view This decorator works as class, method or function decorator without any modification. DO NOT use ``method_decorator`` or whatever while this decorator will use ``self``...
def serialize_message(self, message: SegmentSequence) -> bytes: """Serialize a message (as SegmentSequence, list of FinTS3Segment, or FinTS3Segment) into a byte array""" if isinstance(message, FinTS3Segment): message = SegmentSequence([message]) if isinstance(message, (list, tuple, I...
Serialize a message (as SegmentSequence, list of FinTS3Segment, or FinTS3Segment) into a byte array
Below is the the instruction that describes the task: ### Input: Serialize a message (as SegmentSequence, list of FinTS3Segment, or FinTS3Segment) into a byte array ### Response: def serialize_message(self, message: SegmentSequence) -> bytes: """Serialize a message (as SegmentSequence, list of FinTS3Segmen...
def mkdir(self, astr_dirSpec): """ Given an <astr_dirSpec> in form '/a/b/c/d/.../f', create that path in the internal stree, creating all intermediate nodes as necessary :param astr_dirSpec: :return: """ if astr_dirSpec != ...
Given an <astr_dirSpec> in form '/a/b/c/d/.../f', create that path in the internal stree, creating all intermediate nodes as necessary :param astr_dirSpec: :return:
Below is the the instruction that describes the task: ### Input: Given an <astr_dirSpec> in form '/a/b/c/d/.../f', create that path in the internal stree, creating all intermediate nodes as necessary :param astr_dirSpec: :return: ### Response: def mkdir(self, astr_d...
def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be computed from stored dependencies """ if self.store and self._stored(_id, persistence): return True if self.is_root: return False ...
Return true if this feature stored, or is unstored, but can be computed from stored dependencies
Below is the the instruction that describes the task: ### Input: Return true if this feature stored, or is unstored, but can be computed from stored dependencies ### Response: def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be comput...
def load_plugin(self, name): """This automatically loads a plugin by the given name from the current source and returns the module. This is a convenient alternative to the import statement and saves you from invoking ``__import__`` or a similar function yourself. :param name: t...
This automatically loads a plugin by the given name from the current source and returns the module. This is a convenient alternative to the import statement and saves you from invoking ``__import__`` or a similar function yourself. :param name: the name of the plugin to load.
Below is the the instruction that describes the task: ### Input: This automatically loads a plugin by the given name from the current source and returns the module. This is a convenient alternative to the import statement and saves you from invoking ``__import__`` or a similar function your...
def generate_phase_1(dim = 40): """ The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution. """ phase_1 = numpy.random.normal(0, 1, dim) for i in range(dim - 4, dim): pha...
The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution.
Below is the the instruction that describes the task: ### Input: The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution. ### Response: def generate_phase_1(dim = 40): """ The ...
def plane_xz(size=(10, 10), resolution=(10, 10)) -> VAO: """ Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included. Args: size: (x, y) tuple resolution: (x, y) tuple Returns: A :py:class:`demosys.opengl.vao.VAO...
Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included. Args: size: (x, y) tuple resolution: (x, y) tuple Returns: A :py:class:`demosys.opengl.vao.VAO` instance
Below is the the instruction that describes the task: ### Input: Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included. Args: size: (x, y) tuple resolution: (x, y) tuple Returns: A :py:class:`demosys.opengl.vao.VAO...
def outspiral_loop(N): """ Return a list of points that will loop outwards in a 2D lattice in terms of distance from a central point. So if N=2 this will be [0,0], [0,1], [0,-1],[1,0],[-1,0],[1,1] .... This is useful when you want to loop over a number of bins, but want to start in the center and wo...
Return a list of points that will loop outwards in a 2D lattice in terms of distance from a central point. So if N=2 this will be [0,0], [0,1], [0,-1],[1,0],[-1,0],[1,1] .... This is useful when you want to loop over a number of bins, but want to start in the center and work outwards.
Below is the the instruction that describes the task: ### Input: Return a list of points that will loop outwards in a 2D lattice in terms of distance from a central point. So if N=2 this will be [0,0], [0,1], [0,-1],[1,0],[-1,0],[1,1] .... This is useful when you want to loop over a number of bins, but ...
def sample_given_context(self, c, c_dims): ''' Sample the region with max progress among regions that have the same context c: context value on c_dims dimensions c_dims: w.r.t sensory space dimensions ''' index = self.discrete_progress.sample_given_context(c, c_di...
Sample the region with max progress among regions that have the same context c: context value on c_dims dimensions c_dims: w.r.t sensory space dimensions
Below is the the instruction that describes the task: ### Input: Sample the region with max progress among regions that have the same context c: context value on c_dims dimensions c_dims: w.r.t sensory space dimensions ### Response: def sample_given_context(self, c, c_dims): ''' ...
def iterdays(self, d1, d2): """ Date iterator returning dates in d1 <= x < d2 """ curr = datetime.datetime.combine(d1, datetime.time()) end = datetime.datetime.combine(d2, datetime.time()) if d1.date() == d2.date(): yield curr return while ...
Date iterator returning dates in d1 <= x < d2
Below is the the instruction that describes the task: ### Input: Date iterator returning dates in d1 <= x < d2 ### Response: def iterdays(self, d1, d2): """ Date iterator returning dates in d1 <= x < d2 """ curr = datetime.datetime.combine(d1, datetime.time()) end = datetime...
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1) start, end = int(a), int(b) except ValueError: log.error('Ig...
Given a 'N-P,X-Y' description of port ranges, return a set of ints.
Below is the the instruction that describes the task: ### Input: Given a 'N-P,X-Y' description of port ranges, return a set of ints. ### Response: def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(',...
def reverse_shortlex(end, other, excludeend=False): """Yield all intersections of end with other in reverse shortlex order. >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])] ['111', '011', '101', '110', '001', '010', '100', '000'] >>> ', '.join(''.join(sorted(s)) ......
Yield all intersections of end with other in reverse shortlex order. >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])] ['111', '011', '101', '110', '001', '010', '100', '000'] >>> ', '.join(''.join(sorted(s)) ... for s in reverse_shortlex({'a', 'b', 'c', 'd'}, ... [{...
Below is the the instruction that describes the task: ### Input: Yield all intersections of end with other in reverse shortlex order. >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])] ['111', '011', '101', '110', '001', '010', '100', '000'] >>> ', '.join(''.join(sorted(s...
def resolve_interpreter(exe): """ If the executable given isn't an absolute path, search $PATH for the interpreter """ if os.path.abspath(exe) != exe: paths = os.environ.get('PATH', '').split(os.pathsep) for path in paths: if os.path.exists(os.path.join(path, exe)): ...
If the executable given isn't an absolute path, search $PATH for the interpreter
Below is the the instruction that describes the task: ### Input: If the executable given isn't an absolute path, search $PATH for the interpreter ### Response: def resolve_interpreter(exe): """ If the executable given isn't an absolute path, search $PATH for the interpreter """ if os.path.abspath(e...
def context(self): """Get the xpathContext from an xpathParserContext """ ret = libxml2mod.xmlXPathParserGetContext(self._o) if ret is None:raise xpathError('xmlXPathParserGetContext() failed') __tmp = xpathContext(_obj=ret) return __tmp
Get the xpathContext from an xpathParserContext
Below is the the instruction that describes the task: ### Input: Get the xpathContext from an xpathParserContext ### Response: def context(self): """Get the xpathContext from an xpathParserContext """ ret = libxml2mod.xmlXPathParserGetContext(self._o) if ret is None:raise xpathError('xmlXPa...
def session(self): """ Get session object to benefit from connection pooling. http://docs.python-requests.org/en/master/user/advanced/#session-objects :rtype: requests.Session """ if self._session is None: self._session = requests.Session() self....
Get session object to benefit from connection pooling. http://docs.python-requests.org/en/master/user/advanced/#session-objects :rtype: requests.Session
Below is the the instruction that describes the task: ### Input: Get session object to benefit from connection pooling. http://docs.python-requests.org/en/master/user/advanced/#session-objects :rtype: requests.Session ### Response: def session(self): """ Get session object to bene...
def searchNamesIndex(self, nameIndex, nameData, searchString, category="", math=False, game=False, extension="", searchFiles=False): """Search the names index for a string and returns the namedata""" nameData = {} try: nameFile = open(nameIndex, 'rt') except IOError: self.repo.printd("Error: Unable to rea...
Search the names index for a string and returns the namedata
Below is the the instruction that describes the task: ### Input: Search the names index for a string and returns the namedata ### Response: def searchNamesIndex(self, nameIndex, nameData, searchString, category="", math=False, game=False, extension="", searchFiles=False): """Search the names index for a string a...
def fetch_github_token(self): """ Fetch GitHub token. First try to use variable provided by --token option, otherwise try to fetch it from git config and last CHANGELOG_GITHUB_TOKEN env variable. :returns: Nothing """ if not self.options.token: try: ...
Fetch GitHub token. First try to use variable provided by --token option, otherwise try to fetch it from git config and last CHANGELOG_GITHUB_TOKEN env variable. :returns: Nothing
Below is the the instruction that describes the task: ### Input: Fetch GitHub token. First try to use variable provided by --token option, otherwise try to fetch it from git config and last CHANGELOG_GITHUB_TOKEN env variable. :returns: Nothing ### Response: def fetch_github_token(self): ...
def get_below_right_key_rect(self): """Returns tuple key rect of below right cell""" key_below_right = self.row + 1, self.col + 1, self.tab border_width_right = \ float(self.cell_attributes[self.key]["borderwidth_right"]) / 2.0 border_width_bottom = \ float(self...
Returns tuple key rect of below right cell
Below is the the instruction that describes the task: ### Input: Returns tuple key rect of below right cell ### Response: def get_below_right_key_rect(self): """Returns tuple key rect of below right cell""" key_below_right = self.row + 1, self.col + 1, self.tab border_width_right = \ ...
def getObject(ID, jd, lat, lon): """ Returns an object for a specific date and location. """ if ID == const.SOUTH_NODE: obj = swe.sweObject(const.NORTH_NODE, jd) obj.update({ 'id': const.SOUTH_NODE, 'lon': angle.norm(obj['lon'] + 180) }) elif ID ...
Returns an object for a specific date and location.
Below is the the instruction that describes the task: ### Input: Returns an object for a specific date and location. ### Response: def getObject(ID, jd, lat, lon): """ Returns an object for a specific date and location. """ if ID == const.SOUTH_NODE: obj = swe.sweObject(const.NOR...
def cmd(send, msg, args): """'Inspects a bot attribute. Syntax: {command} <attr> """ if not hasattr(args['handler'], msg): send("That attribute was not found in the handler.") return send(str(getattr(args['handler'], msg)))
Inspects a bot attribute. Syntax: {command} <attr>
Below is the the instruction that describes the task: ### Input: Inspects a bot attribute. Syntax: {command} <attr> ### Response: def cmd(send, msg, args): """'Inspects a bot attribute. Syntax: {command} <attr> """ if not hasattr(args['handler'], msg): send("That attribute was not fo...
def single_valued(self, e): """ Returns True whether `e` is a concrete value or is a value set with only 1 possible value. This differs from `unique` in that this *does* not query the constraint solver. """ if self.state.mode == 'static': if type(e) in (int, b...
Returns True whether `e` is a concrete value or is a value set with only 1 possible value. This differs from `unique` in that this *does* not query the constraint solver.
Below is the the instruction that describes the task: ### Input: Returns True whether `e` is a concrete value or is a value set with only 1 possible value. This differs from `unique` in that this *does* not query the constraint solver. ### Response: def single_valued(self, e): """ R...
def process_kwargs(obj, kwargs): ''' Convenience wrapper around binwalk.core.module.Modules.kwargs. @obj - The class object (an instance of a sub-class of binwalk.core.module.Module). @kwargs - The kwargs provided to the object's __init__ method. Returns None. ''' with Modules() as m: ...
Convenience wrapper around binwalk.core.module.Modules.kwargs. @obj - The class object (an instance of a sub-class of binwalk.core.module.Module). @kwargs - The kwargs provided to the object's __init__ method. Returns None.
Below is the the instruction that describes the task: ### Input: Convenience wrapper around binwalk.core.module.Modules.kwargs. @obj - The class object (an instance of a sub-class of binwalk.core.module.Module). @kwargs - The kwargs provided to the object's __init__ method. Returns None. ### Respon...
def update_vm(vm_ref, vm_config_spec): ''' Updates the virtual machine configuration with the given object vm_ref Virtual machine managed object reference vm_config_spec Virtual machine config spec object to update ''' vm_name = get_managed_object_name(vm_ref) log.trace('Up...
Updates the virtual machine configuration with the given object vm_ref Virtual machine managed object reference vm_config_spec Virtual machine config spec object to update
Below is the the instruction that describes the task: ### Input: Updates the virtual machine configuration with the given object vm_ref Virtual machine managed object reference vm_config_spec Virtual machine config spec object to update ### Response: def update_vm(vm_ref, vm_config_spec):...
def connect_delete_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): """ connect DELETE requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api...
connect DELETE requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_delete_namespaced_service_proxy_with_path(name, namespace, path, async_req=True) >>> result = thr...
Below is the the instruction that describes the task: ### Input: connect DELETE requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_delete_namespaced_service_proxy_with...
def from_series(cls, series, offset=0): """ Creates and return a Series from a Series :param series: raccoon Series :param offset: offset value must be provided as there is no equivalent for a DataFrame :return: Series """ return cls(data=series.data, index=serie...
Creates and return a Series from a Series :param series: raccoon Series :param offset: offset value must be provided as there is no equivalent for a DataFrame :return: Series
Below is the the instruction that describes the task: ### Input: Creates and return a Series from a Series :param series: raccoon Series :param offset: offset value must be provided as there is no equivalent for a DataFrame :return: Series ### Response: def from_series(cls, series, offset=...
def get_loader(config_uri, protocols=None): """ Find a :class:`plaster.ILoader` object capable of handling ``config_uri``. :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param protocols: Zero or more :term:`loader protocol` identifiers that the loader mus...
Find a :class:`plaster.ILoader` object capable of handling ``config_uri``. :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param protocols: Zero or more :term:`loader protocol` identifiers that the loader must implement to match the desired ``config_uri``. :r...
Below is the the instruction that describes the task: ### Input: Find a :class:`plaster.ILoader` object capable of handling ``config_uri``. :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param protocols: Zero or more :term:`loader protocol` identifiers that t...
def keyword_search(rows, **kwargs): """ Takes a list of dictionaries and finds all the dictionaries where the keys and values match those found in the keyword arguments. Keys in the row data have ' ' and '-' replaced with '_', so they can match the keyword argument parsing. For example, the keywor...
Takes a list of dictionaries and finds all the dictionaries where the keys and values match those found in the keyword arguments. Keys in the row data have ' ' and '-' replaced with '_', so they can match the keyword argument parsing. For example, the keyword argument 'fix_up_path' will match a key na...
Below is the the instruction that describes the task: ### Input: Takes a list of dictionaries and finds all the dictionaries where the keys and values match those found in the keyword arguments. Keys in the row data have ' ' and '-' replaced with '_', so they can match the keyword argument parsing. Fo...
def require(self, name): """Return the value of the requested parameter or raise an error.""" value = self.get(name) if value is None: raise TypeError( "{0} requires the parameter '{1}'.".format( self.__class__, name ) )...
Return the value of the requested parameter or raise an error.
Below is the the instruction that describes the task: ### Input: Return the value of the requested parameter or raise an error. ### Response: def require(self, name): """Return the value of the requested parameter or raise an error.""" value = self.get(name) if value is None: ra...
def get_form(self, request, obj=None, **kwargs): """Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself. """ if obj is not None and obj.parent is not None: self.previous_parent = obj.parent previous_parent_id = self.previ...
Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself.
Below is the the instruction that describes the task: ### Input: Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself. ### Response: def get_form(self, request, obj=None, **kwargs): """Returns modified form for TreeItem model. 'Parent' field choices ...
def from_shape_pixel_scale_and_sub_grid_size(cls, shape, pixel_scale, sub_grid_size=2): """Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size. This grid corresponds to a fully unmasked 2D array. Parameters ----------- shape : (int,...
Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size. This grid corresponds to a fully unmasked 2D array. Parameters ----------- shape : (int, int) The 2D shape of the array, where all pixels are used to generate the grid-stack's...
Below is the the instruction that describes the task: ### Input: Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size. This grid corresponds to a fully unmasked 2D array. Parameters ----------- shape : (int, int) The 2D shape...
def script_finished(self): """ waits for the script to emit the script_finshed signal """ script = self.current_script script.updateProgress.disconnect(self.update_status) self.script_thread.started.disconnect() script.finished.disconnect() self.current_s...
waits for the script to emit the script_finshed signal
Below is the the instruction that describes the task: ### Input: waits for the script to emit the script_finshed signal ### Response: def script_finished(self): """ waits for the script to emit the script_finshed signal """ script = self.current_script script.updateProgress....
def delete_gemini_query(self, query_id): """Delete a gemini query Args: name (str) """ query_obj = self.gemini_query(query_id) logger.debug("Delete query: {0}".format(query_obj.name_query)) self.session.delete(query_obj) self.save()
Delete a gemini query Args: name (str)
Below is the the instruction that describes the task: ### Input: Delete a gemini query Args: name (str) ### Response: def delete_gemini_query(self, query_id): """Delete a gemini query Args: name (str) """ query_obj = self.gemini_query(query_id) ...
def get_related_clients(self, client): """ Get all other clients that are connected to the same kernel as `client` """ related_clients = [] for cl in self.get_clients(): if cl.connection_file == client.connection_file and \ cl is not client: ...
Get all other clients that are connected to the same kernel as `client`
Below is the the instruction that describes the task: ### Input: Get all other clients that are connected to the same kernel as `client` ### Response: def get_related_clients(self, client): """ Get all other clients that are connected to the same kernel as `client` """ related_c...
def addSection(self, data, name =".pype32\x00", flags = 0x60000000): """ Adds a new section to the existing L{PE} instance. @type data: str @param data: The data to be added in the new section. @type name: str @param name: (Optional) The name for the new...
Adds a new section to the existing L{PE} instance. @type data: str @param data: The data to be added in the new section. @type name: str @param name: (Optional) The name for the new section. @type flags: int @param flags: (Optional) The attribut...
Below is the the instruction that describes the task: ### Input: Adds a new section to the existing L{PE} instance. @type data: str @param data: The data to be added in the new section. @type name: str @param name: (Optional) The name for the new section. ...
def _get_section(name, source): # type: (str, str) -> Optional[str] """Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the se...
Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the section appears multiple times, each instance will be merged into a singl...
Below is the the instruction that describes the task: ### Input: Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the section appe...
def _set_aws_environment(task: Task = None): """Sets up AWS environment from NCLUSTER environment variables""" current_zone = os.environ.get('NCLUSTER_ZONE', '') current_region = os.environ.get('AWS_DEFAULT_REGION', '') def log(*args): if task: task.log(*args) else: util.log(*args) if cu...
Sets up AWS environment from NCLUSTER environment variables
Below is the the instruction that describes the task: ### Input: Sets up AWS environment from NCLUSTER environment variables ### Response: def _set_aws_environment(task: Task = None): """Sets up AWS environment from NCLUSTER environment variables""" current_zone = os.environ.get('NCLUSTER_ZONE', '') current_...
def finalize_concurrency_state(self, outcome): """ Utility function to finalize the forward execution of the concurrency state. :param outcome: :return: """ final_outcome = outcome self.write_output_data() self.check_output_data_type() self.execution_hist...
Utility function to finalize the forward execution of the concurrency state. :param outcome: :return:
Below is the the instruction that describes the task: ### Input: Utility function to finalize the forward execution of the concurrency state. :param outcome: :return: ### Response: def finalize_concurrency_state(self, outcome): """ Utility function to finalize the forward execution of the ...
def log10(self, floor=None): """Take the log base 10 of the entire dataset. Parameters ---------- floor : number (optional) Clip values below floor after log. Default is None. """ def f(dataset, s, floor): arr = dataset[s] arr = np.lo...
Take the log base 10 of the entire dataset. Parameters ---------- floor : number (optional) Clip values below floor after log. Default is None.
Below is the the instruction that describes the task: ### Input: Take the log base 10 of the entire dataset. Parameters ---------- floor : number (optional) Clip values below floor after log. Default is None. ### Response: def log10(self, floor=None): """Take the log ba...
def add_args(): """Adds commandline arguments and formatted Help""" parser = argparse.ArgumentParser() parser.add_argument('-host', action='store', dest='host', default='127.0.0.1', help='DEFAULT "127.0.0.1"') parser.add_argument('-port', action='store', dest='port', default='2947', help='DEFAULT 2947'...
Adds commandline arguments and formatted Help
Below is the the instruction that describes the task: ### Input: Adds commandline arguments and formatted Help ### Response: def add_args(): """Adds commandline arguments and formatted Help""" parser = argparse.ArgumentParser() parser.add_argument('-host', action='store', dest='host', default='127.0.0...
def get_vulnerability_functions_04(fname): """ Parse the vulnerability model in NRML 0.4 format. :param fname: path of the vulnerability file :returns: a dictionary imt, taxonomy -> vulnerability function + vset """ categories = dict(assetCategory=set(), lossCategory=set(), ...
Parse the vulnerability model in NRML 0.4 format. :param fname: path of the vulnerability file :returns: a dictionary imt, taxonomy -> vulnerability function + vset
Below is the the instruction that describes the task: ### Input: Parse the vulnerability model in NRML 0.4 format. :param fname: path of the vulnerability file :returns: a dictionary imt, taxonomy -> vulnerability function + vset ### Response: def get_vulnerability_functions_04(fname): ...
def handle_join(self, connection, event): """ Store join time for a nickname when it joins. """ nickname = self.get_nickname(event) self.joined[nickname] = datetime.now()
Store join time for a nickname when it joins.
Below is the the instruction that describes the task: ### Input: Store join time for a nickname when it joins. ### Response: def handle_join(self, connection, event): """ Store join time for a nickname when it joins. """ nickname = self.get_nickname(event) self.joined[nickna...
def get_multilevel_rpn_anchor_input(im, boxes, is_crowd): """ Args: im: an image boxes: nx4, floatbox, gt. shoudn't be changed is_crowd: n, Returns: [(fm_labels, fm_boxes)]: Returns a tuple for each FPN level. Each tuple contains the anchor labels and target boxes fo...
Args: im: an image boxes: nx4, floatbox, gt. shoudn't be changed is_crowd: n, Returns: [(fm_labels, fm_boxes)]: Returns a tuple for each FPN level. Each tuple contains the anchor labels and target boxes for each pixel in the featuremap. fm_labels: fHxfWx NUM_ANCHOR_...
Below is the the instruction that describes the task: ### Input: Args: im: an image boxes: nx4, floatbox, gt. shoudn't be changed is_crowd: n, Returns: [(fm_labels, fm_boxes)]: Returns a tuple for each FPN level. Each tuple contains the anchor labels and target boxes for...
def register(cache): ''' Registers a cache. ''' global caches name = cache().name if not caches.has_key(name): caches[name] = cache
Registers a cache.
Below is the the instruction that describes the task: ### Input: Registers a cache. ### Response: def register(cache): ''' Registers a cache. ''' global caches name = cache().name if not caches.has_key(name): caches[name] = cache
def add_group_grant(self, permission, group_id): """ Convenience method that provides a quick way to add a canonical group grant to a key. This method retrieves the current ACL, creates a new grant based on the parameters passed in, adds that grant to the ACL and then PUT's the n...
Convenience method that provides a quick way to add a canonical group grant to a key. This method retrieves the current ACL, creates a new grant based on the parameters passed in, adds that grant to the ACL and then PUT's the new ACL back to GS. :type permission: string :param p...
Below is the the instruction that describes the task: ### Input: Convenience method that provides a quick way to add a canonical group grant to a key. This method retrieves the current ACL, creates a new grant based on the parameters passed in, adds that grant to the ACL and then PUT's the n...
def on_gtk_prefer_dark_theme_toggled(self, chk): """Set the `gtk_prefer_dark_theme' property in dconf """ self.settings.general.set_boolean('gtk-prefer-dark-theme', chk.get_active()) select_gtk_theme(self.settings)
Set the `gtk_prefer_dark_theme' property in dconf
Below is the the instruction that describes the task: ### Input: Set the `gtk_prefer_dark_theme' property in dconf ### Response: def on_gtk_prefer_dark_theme_toggled(self, chk): """Set the `gtk_prefer_dark_theme' property in dconf """ self.settings.general.set_boolean('gtk-prefer-dark-theme...
def all_coplanar(triangles): """ Check to see if a list of triangles are all coplanar Parameters ---------------- triangles: (n, 3, 3) float Vertices of triangles Returns --------------- all_coplanar : bool True if all triangles are coplanar """ triangles = np.asany...
Check to see if a list of triangles are all coplanar Parameters ---------------- triangles: (n, 3, 3) float Vertices of triangles Returns --------------- all_coplanar : bool True if all triangles are coplanar
Below is the the instruction that describes the task: ### Input: Check to see if a list of triangles are all coplanar Parameters ---------------- triangles: (n, 3, 3) float Vertices of triangles Returns --------------- all_coplanar : bool True if all triangles are coplanar ### ...
def _get_crud_params(compiler, stmt, **kw): """ extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect""" compiler.postfetch = [] compiler.insert_prefetch = [] compiler.update_prefetch = [] compiler.re...
extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect
Below is the the instruction that describes the task: ### Input: extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect ### Response: def _get_crud_params(compiler, stmt, **kw): """ extract values from crud parameters ta...
def helioY(self,*args,**kwargs): """ NAME: helioY PURPOSE: return Heliocentric Galactic rectangular y-coordinate (aka "Y") INPUT: t - (optional) time at which to get Y obs=[X,Y,Z] - (optional) position and velocity of observer ...
NAME: helioY PURPOSE: return Heliocentric Galactic rectangular y-coordinate (aka "Y") INPUT: t - (optional) time at which to get Y obs=[X,Y,Z] - (optional) position and velocity of observer (in kpc and km/s) (default=Object-wide defau...
Below is the the instruction that describes the task: ### Input: NAME: helioY PURPOSE: return Heliocentric Galactic rectangular y-coordinate (aka "Y") INPUT: t - (optional) time at which to get Y obs=[X,Y,Z] - (optional) position and velocity of observer ...
def get_bugs_summaries(self, bugids): """ Get multiple bug objects' summaries only (faster). param bugids: ``list`` of ``int``, bug numbers. returns: deferred that when fired returns a list of ``AttrDict``s representing these bugs. """ payload = {'ids': ...
Get multiple bug objects' summaries only (faster). param bugids: ``list`` of ``int``, bug numbers. returns: deferred that when fired returns a list of ``AttrDict``s representing these bugs.
Below is the the instruction that describes the task: ### Input: Get multiple bug objects' summaries only (faster). param bugids: ``list`` of ``int``, bug numbers. returns: deferred that when fired returns a list of ``AttrDict``s representing these bugs. ### Response: def get_bugs...
def replace_rep_after(text: str) -> str: "Replace repetitions at the character level in `text` after the repetition" def _replace_rep(m): c, cc = m.groups() return f"{c}{TK_REP}{len(cc)+1}" re_rep = re.compile(r"(\S)(\1{2,})") return re_rep.sub(_replace_rep, text)
Replace repetitions at the character level in `text` after the repetition
Below is the the instruction that describes the task: ### Input: Replace repetitions at the character level in `text` after the repetition ### Response: def replace_rep_after(text: str) -> str: "Replace repetitions at the character level in `text` after the repetition" def _replace_rep(m): c, cc =...
def new(cls) -> 'Generator': """ Creates and returns random generator point that satisfy BLS algorithm requirements. :return: BLS generator """ logger = logging.getLogger(__name__) logger.debug("Generator::new: >>>") c_instance = c_void_p() do_call(cls.ne...
Creates and returns random generator point that satisfy BLS algorithm requirements. :return: BLS generator
Below is the the instruction that describes the task: ### Input: Creates and returns random generator point that satisfy BLS algorithm requirements. :return: BLS generator ### Response: def new(cls) -> 'Generator': """ Creates and returns random generator point that satisfy BLS algorithm re...
def _udf_cell(args, cell_body): """Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional arguments following '%%bq udf'. ...
Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional arguments following '%%bq udf'. cell_body: the UDF declaration (i...
Below is the the instruction that describes the task: ### Input: Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional ...
def scanAllProcessesForMapping(searchPortion, isExactMatch=False, ignoreCase=False): ''' scanAllProcessesForMapping - Scans all processes on the system for a given search pattern. @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string...
scanAllProcessesForMapping - Scans all processes on the system for a given search pattern. @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings. @param isExactMatch <bool> Default False - If match should be ex...
Below is the the instruction that describes the task: ### Input: scanAllProcessesForMapping - Scans all processes on the system for a given search pattern. @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings. ...
def type_check_cmd(self, args, range=None): """Sets the flag to begin buffering typecheck notes & clears any stale notes before requesting a typecheck from the server""" self.log.debug('type_check_cmd: in') self.start_typechecking() self.type_check("") self.editor.message...
Sets the flag to begin buffering typecheck notes & clears any stale notes before requesting a typecheck from the server
Below is the the instruction that describes the task: ### Input: Sets the flag to begin buffering typecheck notes & clears any stale notes before requesting a typecheck from the server ### Response: def type_check_cmd(self, args, range=None): """Sets the flag to begin buffering typecheck notes & cl...
def _get_constraints(self): """Get neighboring edges for each edge in the edges.""" num_edges = len(self.edges) for k in range(num_edges): for i in range(num_edges): # add to constraints if i shared an edge with k if k != i and self.edges[k].is_adjacen...
Get neighboring edges for each edge in the edges.
Below is the the instruction that describes the task: ### Input: Get neighboring edges for each edge in the edges. ### Response: def _get_constraints(self): """Get neighboring edges for each edge in the edges.""" num_edges = len(self.edges) for k in range(num_edges): for i in ra...
def _publish_deferred_messages(self): """Called when pika is connected and has a channel open to publish any requests buffered. """ global message_stack if not self._rabbitmq_is_closed and message_stack: LOGGER.info('Publishing %i deferred message(s)', len(message_st...
Called when pika is connected and has a channel open to publish any requests buffered.
Below is the the instruction that describes the task: ### Input: Called when pika is connected and has a channel open to publish any requests buffered. ### Response: def _publish_deferred_messages(self): """Called when pika is connected and has a channel open to publish any requests buffere...
def encode(self): '''Compress the associated encodable payload, prepend the header then encode with base64 if requested Returns: the b64 encoded wire encoding of the histogram (as a string) or the compressed payload (as a string, if b64 wrappinb is disabled) ''' ...
Compress the associated encodable payload, prepend the header then encode with base64 if requested Returns: the b64 encoded wire encoding of the histogram (as a string) or the compressed payload (as a string, if b64 wrappinb is disabled)
Below is the the instruction that describes the task: ### Input: Compress the associated encodable payload, prepend the header then encode with base64 if requested Returns: the b64 encoded wire encoding of the histogram (as a string) or the compressed payload (as a string, i...
def declare_queue(self, queue_name): """Declare a queue. Has no effect if a queue with the given name already exists. Parameters: queue_name(str): The name of the new queue. Raises: ConnectionClosed: If the underlying channel or connection has been clos...
Declare a queue. Has no effect if a queue with the given name already exists. Parameters: queue_name(str): The name of the new queue. Raises: ConnectionClosed: If the underlying channel or connection has been closed.
Below is the the instruction that describes the task: ### Input: Declare a queue. Has no effect if a queue with the given name already exists. Parameters: queue_name(str): The name of the new queue. Raises: ConnectionClosed: If the underlying channel or connection ...
def GetAll(cls, attr, value, e=0.000001, sort_by="__name__"): """Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attr...
Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attribute. .. versionadded:: 0.0.5
Below is the the instruction that describes the task: ### Input: Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attribut...
def merge(arg, *rest, **kwargs): """Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use ...
Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use for items within mer...
Below is the the instruction that describes the task: ### Input: Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Opti...