code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage='cp1252', **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and d...
Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): ...
Below is the the instruction that describes the task: ### Input: Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key th...
def nlmsg_flags(self, value): """Message flags setter.""" self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0))
Message flags setter.
Below is the the instruction that describes the task: ### Input: Message flags setter. ### Response: def nlmsg_flags(self, value): """Message flags setter.""" self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0))
def handle_profile_save(self, sender, instance, **kwargs): """ Custom handler for user profile save """ self.handle_save(instance.user.__class__, instance.user)
Custom handler for user profile save
Below is the the instruction that describes the task: ### Input: Custom handler for user profile save ### Response: def handle_profile_save(self, sender, instance, **kwargs): """ Custom handler for user profile save """ self.handle_save(instance.user.__class__, instance.user)
def create_manager(self, instance, superclass): """ Dynamically create a RelatedManager to handle the back side of the (G)FK """ rel_model = self.rating_model rated_model = self.rated_model class RelatedManager(superclass): def get_query_set(self): ...
Dynamically create a RelatedManager to handle the back side of the (G)FK
Below is the the instruction that describes the task: ### Input: Dynamically create a RelatedManager to handle the back side of the (G)FK ### Response: def create_manager(self, instance, superclass): """ Dynamically create a RelatedManager to handle the back side of the (G)FK """ re...
def is_static(*p): """ A static value (does not change at runtime) which is known at compile time """ return all(is_CONST(x) or is_number(x) or is_const(x) for x in p)
A static value (does not change at runtime) which is known at compile time
Below is the the instruction that describes the task: ### Input: A static value (does not change at runtime) which is known at compile time ### Response: def is_static(*p): """ A static value (does not change at runtime) which is known at compile time """ return all(is_CONST(x) or ...
def get_env_args(env): """Yield options to inject into the slcli command from the environment.""" for arg, val in env.vars.get('global_args', {}).items(): if val is True: yield '--%s' % arg elif isinstance(val, int): for _ in range(val): yield '--%s' % arg...
Yield options to inject into the slcli command from the environment.
Below is the the instruction that describes the task: ### Input: Yield options to inject into the slcli command from the environment. ### Response: def get_env_args(env): """Yield options to inject into the slcli command from the environment.""" for arg, val in env.vars.get('global_args', {}).items(): ...
def collect(cls, sources): """ :param sources: dictionaries with a key 'tectonicRegion' :returns: an ordered list of SourceGroup instances """ source_stats_dict = {} for src in sources: trt = src['tectonicRegion'] if trt not in source_stats_dict: ...
:param sources: dictionaries with a key 'tectonicRegion' :returns: an ordered list of SourceGroup instances
Below is the the instruction that describes the task: ### Input: :param sources: dictionaries with a key 'tectonicRegion' :returns: an ordered list of SourceGroup instances ### Response: def collect(cls, sources): """ :param sources: dictionaries with a key 'tectonicRegion' :returns...
def set_mac_addr_adv_interval(self, name, vrid, value=None, disable=False, default=False, run=True): """Set the mac_addr_adv_interval property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the v...
Set the mac_addr_adv_interval property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (integer): mac-address advertisement-interval value to assign to the vrrp. disabl...
Below is the the instruction that describes the task: ### Input: Set the mac_addr_adv_interval property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (integer): mac-address advertisement-int...
def get_backends(): """ Get backends info so that we can find the correct one. We just look in the directory structure to find modules. """ IGNORE_DIRS = ["core", "tools", "utils"] global backends if backends is None: backends = {} i3pystatus_dir = os.path.dirname(i3pystatus...
Get backends info so that we can find the correct one. We just look in the directory structure to find modules.
Below is the the instruction that describes the task: ### Input: Get backends info so that we can find the correct one. We just look in the directory structure to find modules. ### Response: def get_backends(): """ Get backends info so that we can find the correct one. We just look in the directory...
def execute(self, command, *args, encoding=_NOTSET): """Executes redis command and returns Future waiting for the answer. Raises: * TypeError if any of args can not be encoded as bytes. * ReplyError on redis '-ERR' responses. * ProtocolError when response can not be decoded mean...
Executes redis command and returns Future waiting for the answer. Raises: * TypeError if any of args can not be encoded as bytes. * ReplyError on redis '-ERR' responses. * ProtocolError when response can not be decoded meaning connection is broken. * ConnectionClosedEr...
Below is the the instruction that describes the task: ### Input: Executes redis command and returns Future waiting for the answer. Raises: * TypeError if any of args can not be encoded as bytes. * ReplyError on redis '-ERR' responses. * ProtocolError when response can not be decoded...
def with_stmt__26(self, with_loc, context, with_var, colon_loc, body): """(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite""" if with_var: as_loc, optional_vars = with_var item = ast.withitem(context_expr=context, optional_vars=optional_vars, ...
(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite
Below is the the instruction that describes the task: ### Input: (2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite ### Response: def with_stmt__26(self, with_loc, context, with_var, colon_loc, body): """(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite""" if with_var: as_l...
def scope_groups(self): """ Return a new raw REST interface to scope_group resources :rtype: :py:class:`ns1.rest.ipam.Scopegroups` """ import ns1.rest.ipam return ns1.rest.ipam.Scopegroups(self.config)
Return a new raw REST interface to scope_group resources :rtype: :py:class:`ns1.rest.ipam.Scopegroups`
Below is the the instruction that describes the task: ### Input: Return a new raw REST interface to scope_group resources :rtype: :py:class:`ns1.rest.ipam.Scopegroups` ### Response: def scope_groups(self): """ Return a new raw REST interface to scope_group resources :rtype: :py:cl...
def run(self, *args): """Withdraw a unique identity from an organization.""" params = self.parser.parse_args(args) uuid = params.uuid organization = params.organization try: from_date = utils.str_to_datetime(params.from_date) to_date = utils.str_to_date...
Withdraw a unique identity from an organization.
Below is the the instruction that describes the task: ### Input: Withdraw a unique identity from an organization. ### Response: def run(self, *args): """Withdraw a unique identity from an organization.""" params = self.parser.parse_args(args) uuid = params.uuid organization = para...
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = ...
Perform update of param_arrays from grad_arrays on kvstore.
Below is the the instruction that describes the task: ### Input: Perform update of param_arrays from grad_arrays on kvstore. ### Response: def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enu...
def parse_docopt_string(docopt_string): """returns a 2-tuple (usage, options)""" from re import match, DOTALL only_usage_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+""" usage_and_options_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+Options:\s+(?P<options>.*)\s+""" usage, options = '', '' if match(usa...
returns a 2-tuple (usage, options)
Below is the the instruction that describes the task: ### Input: returns a 2-tuple (usage, options) ### Response: def parse_docopt_string(docopt_string): """returns a 2-tuple (usage, options)""" from re import match, DOTALL only_usage_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+""" usage_and_options_...
def qteAddMiniApplet(self, appletObj: QtmacsApplet): """ Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this ...
Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this method does nothing if a custom mini applet is already active. Us...
Below is the the instruction that describes the task: ### Input: Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this meth...
def init(opts): ''' This function gets called when the proxy starts up. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this proxy.') return False if 'username' not in opts['proxy']: log.critical('No \'username\' key found in pillar for t...
This function gets called when the proxy starts up.
Below is the the instruction that describes the task: ### Input: This function gets called when the proxy starts up. ### Response: def init(opts): ''' This function gets called when the proxy starts up. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for th...
def write_segment(buff, segment, ver, ver_range, eci=False): """\ Writes a segment. :param buff: The byte buffer. :param _Segment segment: The segment to serialize. :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a Micro QR Code is written. :param ver_rang...
\ Writes a segment. :param buff: The byte buffer. :param _Segment segment: The segment to serialize. :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a Micro QR Code is written. :param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written, ...
Below is the the instruction that describes the task: ### Input: \ Writes a segment. :param buff: The byte buffer. :param _Segment segment: The segment to serialize. :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a Micro QR Code is written. :param ver_ran...
def _get_jenks_config(): """ retrieve the jenks configuration object """ config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, 'w').close() with open(config_file, 'r') as fh: ...
retrieve the jenks configuration object
Below is the the instruction that describes the task: ### Input: retrieve the jenks configuration object ### Response: def _get_jenks_config(): """ retrieve the jenks configuration object """ config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME...
def find_actions(namespace, action_prefix): """Find all the actions in the namespace.""" actions = {} for key, value in iteritems(namespace): if key.startswith(action_prefix): actions[key[len(action_prefix):]] = analyse_action(value) return actions
Find all the actions in the namespace.
Below is the the instruction that describes the task: ### Input: Find all the actions in the namespace. ### Response: def find_actions(namespace, action_prefix): """Find all the actions in the namespace.""" actions = {} for key, value in iteritems(namespace): if key.startswith(action_prefix): ...
def render_customizations(self): """ Customize template for site user specified customizations """ disable_plugins = self.pt.customize_conf.get('disable_plugins', []) if not disable_plugins: logger.debug('No site-user specified plugins to disable') else: ...
Customize template for site user specified customizations
Below is the the instruction that describes the task: ### Input: Customize template for site user specified customizations ### Response: def render_customizations(self): """ Customize template for site user specified customizations """ disable_plugins = self.pt.customize_conf.get('d...
def close_connection (self): """Release the open connection from the connection pool.""" if self.url_connection is not None: try: self.url_connection.quit() except Exception: pass self.url_connection = None
Release the open connection from the connection pool.
Below is the the instruction that describes the task: ### Input: Release the open connection from the connection pool. ### Response: def close_connection (self): """Release the open connection from the connection pool.""" if self.url_connection is not None: try: self.url...
def compute_transformed(context): """Compute transformed key for opening database""" key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) kdf_parameters = context._.header.value.dynamic_header.kdf_parameters.data.dict if context._._.tr...
Compute transformed key for opening database
Below is the the instruction that describes the task: ### Input: Compute transformed key for opening database ### Response: def compute_transformed(context): """Compute transformed key for opening database""" key_composite = compute_key_composite( password=context._._.password, keyfile=con...
def send_command(self, command, args=None): """ Send a command to VNDB and then get the result. :param command: What command are we sending :param args: What are the json args for this command :return: Servers Response :rtype: Dictionary (See D11 docs on VNDB) ""...
Send a command to VNDB and then get the result. :param command: What command are we sending :param args: What are the json args for this command :return: Servers Response :rtype: Dictionary (See D11 docs on VNDB)
Below is the the instruction that describes the task: ### Input: Send a command to VNDB and then get the result. :param command: What command are we sending :param args: What are the json args for this command :return: Servers Response :rtype: Dictionary (See D11 docs on VNDB) ### R...
def open_resource(self, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE, resource_pyclass=None, **kwargs): """Return an instrument for the resource name. :param reso...
Return an instrument for the resource name. :param resource_name: name or alias of the resource to open. :param access_mode: access mode. :type access_mode: :class:`pyvisa.constants.AccessModes` :param open_timeout: time out to open. :param resource_pyclass: resource python clas...
Below is the the instruction that describes the task: ### Input: Return an instrument for the resource name. :param resource_name: name or alias of the resource to open. :param access_mode: access mode. :type access_mode: :class:`pyvisa.constants.AccessModes` :param open_timeout: ti...
def add_matplotlib_cmaps(fail_on_import_error=True): """Add all matplotlib colormaps.""" try: from matplotlib import cm as _cm from matplotlib.cbook import mplDeprecation except ImportError: if fail_on_import_error: raise # silently fail return for na...
Add all matplotlib colormaps.
Below is the the instruction that describes the task: ### Input: Add all matplotlib colormaps. ### Response: def add_matplotlib_cmaps(fail_on_import_error=True): """Add all matplotlib colormaps.""" try: from matplotlib import cm as _cm from matplotlib.cbook import mplDeprecation except ...
def times_called(self, n): """Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>>...
Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (m...
Below is the the instruction that describes the task: ### Input: Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >...
def city_center_distance(self): """ This method gets the distance to city center, in km. :return: """ try: infos = self._ad_page_content.find_all( 'div', {"class": "map_info_box"}) for info in infos: if 'Distance to City Cen...
This method gets the distance to city center, in km. :return:
Below is the the instruction that describes the task: ### Input: This method gets the distance to city center, in km. :return: ### Response: def city_center_distance(self): """ This method gets the distance to city center, in km. :return: """ try: infos =...
def load_combo_catalog(): """Load a union of the user and global catalogs for convenience""" user_dir = user_data_dir() global_dir = global_data_dir() desc = 'Generated from data packages found on your intake search path' cat_dirs = [] if os.path.isdir(user_dir): cat_dirs.append(user_dir...
Load a union of the user and global catalogs for convenience
Below is the the instruction that describes the task: ### Input: Load a union of the user and global catalogs for convenience ### Response: def load_combo_catalog(): """Load a union of the user and global catalogs for convenience""" user_dir = user_data_dir() global_dir = global_data_dir() desc = '...
def query( self, *, # Forces keyword args. time: Timestamp, duration: Union[Duration, timedelta] = Duration(), qubits: Iterable[Qid] = None, include_query_end_time=False, include_op_end_times=False) -> List[ScheduledOperation]: ...
Finds operations by time and qubit. Args: time: Operations must end after this time to be returned. duration: Operations must start by time+duration to be returned. qubits: If specified, only operations touching one of the included qubits will...
Below is the the instruction that describes the task: ### Input: Finds operations by time and qubit. Args: time: Operations must end after this time to be returned. duration: Operations must start by time+duration to be returned. qubits: If specified, onl...
def _download_chunk(self, chunk_offset, chunk_size): """Reads or downloads the received blob from the system.""" range_id = 'bytes={0}-{1}'.format( chunk_offset, chunk_offset + chunk_size - 1) return self._blob_service.get_blob( container_name=self._container_name, ...
Reads or downloads the received blob from the system.
Below is the the instruction that describes the task: ### Input: Reads or downloads the received blob from the system. ### Response: def _download_chunk(self, chunk_offset, chunk_size): """Reads or downloads the received blob from the system.""" range_id = 'bytes={0}-{1}'.format( chunk_...
def process_response(self, request, response, spider): """Handle the a Scrapy response""" if not self.is_cloudflare_challenge(response): return response logger = logging.getLogger('cloudflaremiddleware') logger.debug( 'Cloudflare protection detected on %s, tryi...
Handle the a Scrapy response
Below is the the instruction that describes the task: ### Input: Handle the a Scrapy response ### Response: def process_response(self, request, response, spider): """Handle the a Scrapy response""" if not self.is_cloudflare_challenge(response): return response logger = logging...
def verify(self): '''Check that the database accurately describes the state of the repository''' c = self.database.cursor() non_exist = set() no_db_entry = set(os.listdir(self.cache_dir)) try: no_db_entry.remove('file_database.db') no_db_entry.remove('fi...
Check that the database accurately describes the state of the repository
Below is the the instruction that describes the task: ### Input: Check that the database accurately describes the state of the repository ### Response: def verify(self): '''Check that the database accurately describes the state of the repository''' c = self.database.cursor() non_exist = se...
def channel_history(current): """ Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'channel_key': key, 'timestamp': datetime, # timestamp data of o...
Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'channel_key': key, 'timestamp': datetime, # timestamp data of oldest shown message } ...
Below is the the instruction that describes the task: ### Input: Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'channel_key': key, 'timestamp': datetime...
def resource_moved(self, resource, new_resource): """It is called when a resource is moved""" if self.moved is not None: self.moved(resource, new_resource)
It is called when a resource is moved
Below is the the instruction that describes the task: ### Input: It is called when a resource is moved ### Response: def resource_moved(self, resource, new_resource): """It is called when a resource is moved""" if self.moved is not None: self.moved(resource, new_resource)
def cvtToMag(rh, size): """ Convert a size value to a number with a magnitude appended. Input: Request Handle Size bytes Output: Converted value with a magnitude """ rh.printSysLog("Enter generalUtils.cvtToMag") mSize = '' size = size / (1024 * 1024) if size...
Convert a size value to a number with a magnitude appended. Input: Request Handle Size bytes Output: Converted value with a magnitude
Below is the the instruction that describes the task: ### Input: Convert a size value to a number with a magnitude appended. Input: Request Handle Size bytes Output: Converted value with a magnitude ### Response: def cvtToMag(rh, size): """ Convert a size value to a number wi...
def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data r...
Return minions that match via glob
Below is the the instruction that describes the task: ### Input: Return minions that match via glob ### Response: def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): ...
def importSite(self, location): """ This operation imports the portal site configuration to a location you specify. """ params = { "location" : location, "f" : "json" } url = self._url + "/importSite" return self._post(url=url, para...
This operation imports the portal site configuration to a location you specify.
Below is the the instruction that describes the task: ### Input: This operation imports the portal site configuration to a location you specify. ### Response: def importSite(self, location): """ This operation imports the portal site configuration to a location you specify. ...
def create(self, data, **kwargs): """Create a new object. Args: data (dict): Parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo or 'ref_name', 'stage', 'name', 'all') ...
Create a new object. Args: data (dict): Parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo or 'ref_name', 'stage', 'name', 'all') Raises: GitlabAuthenticatio...
Below is the the instruction that describes the task: ### Input: Create a new object. Args: data (dict): Parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo or 'ref_name', 'st...
def setup_logging(): """ Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all loggers that are given in the law config. """ global console_handler # make sure ...
Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all loggers that are given in the law config.
Below is the the instruction that describes the task: ### Input: Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all loggers that are given in the law config. ### Response: d...
def spherical_matrix(theta, phi, axes='sxyz'): """ Give a spherical coordinate vector, find the rotation that will transform a [0,0,1] vector to those coordinates Parameters ----------- theta: float, rotation angle in radians phi: float, rotation angle in radians Returns --------...
Give a spherical coordinate vector, find the rotation that will transform a [0,0,1] vector to those coordinates Parameters ----------- theta: float, rotation angle in radians phi: float, rotation angle in radians Returns ---------- matrix: (4,4) rotation matrix where the following wi...
Below is the the instruction that describes the task: ### Input: Give a spherical coordinate vector, find the rotation that will transform a [0,0,1] vector to those coordinates Parameters ----------- theta: float, rotation angle in radians phi: float, rotation angle in radians Returns ...
def delete_tags(self, arg): """Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string """ if len(arg) > 0: raw = html.fromstring(arg) return raw.text_content().strip() ...
Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string
Below is the the instruction that describes the task: ### Input: Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string ### Response: def delete_tags(self, arg): """Removes html-tags from extracted data. ...
def shell(commands, splitlines=False, ignore_errors=False): ''' Subprocess based implementation of pyinfra/api/ssh.py's ``run_shell_command``. Args: commands (string, list): command or list of commands to execute spltlines (bool): optionally have the output split by lines ignore_err...
Subprocess based implementation of pyinfra/api/ssh.py's ``run_shell_command``. Args: commands (string, list): command or list of commands to execute spltlines (bool): optionally have the output split by lines ignore_errors (bool): ignore errors when executing these commands
Below is the the instruction that describes the task: ### Input: Subprocess based implementation of pyinfra/api/ssh.py's ``run_shell_command``. Args: commands (string, list): command or list of commands to execute spltlines (bool): optionally have the output split by lines ignore_errors...
def run_profilers(run_object, prof_config, verbose=False): """Runs profilers on run_object. Args: run_object: An object (string or tuple) for profiling. prof_config: A string with profilers configuration. verbose: True if info about running profilers should be shown. Returns: ...
Runs profilers on run_object. Args: run_object: An object (string or tuple) for profiling. prof_config: A string with profilers configuration. verbose: True if info about running profilers should be shown. Returns: An ordered dictionary with collected stats. Raises: ...
Below is the the instruction that describes the task: ### Input: Runs profilers on run_object. Args: run_object: An object (string or tuple) for profiling. prof_config: A string with profilers configuration. verbose: True if info about running profilers should be shown. Returns: ...
def _CreateNewShowDir(self, showName): """ Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autog...
Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autogenerated value is accepted by default. Par...
Below is the the instruction that describes the task: ### Input: Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable...
def prepare_destruction(self): """Prepares the model for destruction Un-registers itself as observer from the state machine and the root state """ try: self.relieve_model(self.state_machine_model) assert self.__buffered_root_state_model is self.state_machine_mode...
Prepares the model for destruction Un-registers itself as observer from the state machine and the root state
Below is the the instruction that describes the task: ### Input: Prepares the model for destruction Un-registers itself as observer from the state machine and the root state ### Response: def prepare_destruction(self): """Prepares the model for destruction Un-registers itself as observer ...
def open(url, wait=10): """ Returns a connection to a url which you can read(). When the wait amount is exceeded, raises a URLTimeout. When an error occurs, raises a URLError. 404 errors specifically return a HTTP404NotFound. """ # If the url is a URLParser, get any POST parameters. post...
Returns a connection to a url which you can read(). When the wait amount is exceeded, raises a URLTimeout. When an error occurs, raises a URLError. 404 errors specifically return a HTTP404NotFound.
Below is the the instruction that describes the task: ### Input: Returns a connection to a url which you can read(). When the wait amount is exceeded, raises a URLTimeout. When an error occurs, raises a URLError. 404 errors specifically return a HTTP404NotFound. ### Response: def open(url, wait=10): ...
def present(name, service_name, auth=None, **kwargs): ''' Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to cont...
Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to control if endpoint is enabled
Below is the the instruction that describes the task: ### Input: Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to c...
def get_trial_info(current_trial): """Get job information for current trial.""" if current_trial.end_time and ("_" in current_trial.end_time): # end time is parsed from result.json and the format # is like: yyyy-mm-dd_hh-MM-ss, which will be converted # to yyyy-mm-dd hh:MM:ss here ...
Get job information for current trial.
Below is the the instruction that describes the task: ### Input: Get job information for current trial. ### Response: def get_trial_info(current_trial): """Get job information for current trial.""" if current_trial.end_time and ("_" in current_trial.end_time): # end time is parsed from result.json ...
def _argtop(y_score, k=None): """ Returns the indexes of the top k scores (not necessarily sorted) """ # avoid sorting when just want the top all if k is None: return slice(0, len(y_score)) else: return _argsort(y_score, k)
Returns the indexes of the top k scores (not necessarily sorted)
Below is the the instruction that describes the task: ### Input: Returns the indexes of the top k scores (not necessarily sorted) ### Response: def _argtop(y_score, k=None): """ Returns the indexes of the top k scores (not necessarily sorted) """ # avoid sorting when just want the top all if k ...
def create_node(vm_): ''' Build and submit the XML to create a node ''' # Start the tree content = ET.Element('ve') # Name of the instance name = ET.SubElement(content, 'name') name.text = vm_['name'] # Description, defaults to name desc = ET.SubElement(content, 'description') ...
Build and submit the XML to create a node
Below is the the instruction that describes the task: ### Input: Build and submit the XML to create a node ### Response: def create_node(vm_): ''' Build and submit the XML to create a node ''' # Start the tree content = ET.Element('ve') # Name of the instance name = ET.SubElement(conte...
def get_or_add_image_part(self, image_file): """ Return an ``(image_part, rId)`` 2-tuple corresponding to an |ImagePart| object containing the image in *image_file*, and related to this slide with the key *rId*. If either the image part or relationship already exists, they are re...
Return an ``(image_part, rId)`` 2-tuple corresponding to an |ImagePart| object containing the image in *image_file*, and related to this slide with the key *rId*. If either the image part or relationship already exists, they are reused, otherwise they are newly created.
Below is the the instruction that describes the task: ### Input: Return an ``(image_part, rId)`` 2-tuple corresponding to an |ImagePart| object containing the image in *image_file*, and related to this slide with the key *rId*. If either the image part or relationship already exists, they ar...
def save(self, *args, **kwargs): """ Saves the topic instance. """ # It is vital to track the changes of the forum associated with a topic in order to # maintain counters up-to-date. old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk...
Saves the topic instance.
Below is the the instruction that describes the task: ### Input: Saves the topic instance. ### Response: def save(self, *args, **kwargs): """ Saves the topic instance. """ # It is vital to track the changes of the forum associated with a topic in order to # maintain counters up-to-date. ...
def Lazarek_Black(m, D, mul, kl, Hvap, q=None, Te=None): r'''Calculates heat transfer coefficient for film boiling of saturated fluid in vertical tubes for either upward or downward flow. Correlation is as shown in [1]_, and also reviewed in [2]_ and [3]_. Either the heat flux or excess temperature...
r'''Calculates heat transfer coefficient for film boiling of saturated fluid in vertical tubes for either upward or downward flow. Correlation is as shown in [1]_, and also reviewed in [2]_ and [3]_. Either the heat flux or excess temperature is required for the calculation of heat transfer coeffic...
Below is the the instruction that describes the task: ### Input: r'''Calculates heat transfer coefficient for film boiling of saturated fluid in vertical tubes for either upward or downward flow. Correlation is as shown in [1]_, and also reviewed in [2]_ and [3]_. Either the heat flux or excess tem...
def gnomonicImageToSphere(x, y): """ Inverse gnomonic projection (deg). """ # Convert angle to [-180, 180] interval x = x - 360.*(x>180) x = np.asarray(x) y = np.asarray(y) lon = np.degrees(np.arctan2(y, x)) r_theta = np.sqrt(x**2 + y**2) lat = np.degrees(np.arctan(180. / (np.pi ...
Inverse gnomonic projection (deg).
Below is the the instruction that describes the task: ### Input: Inverse gnomonic projection (deg). ### Response: def gnomonicImageToSphere(x, y): """ Inverse gnomonic projection (deg). """ # Convert angle to [-180, 180] interval x = x - 360.*(x>180) x = np.asarray(x) y = np.asarray(y) ...
def get_element_id(self, complete_name): """Get the TocElement element id-number of the element with the supplied name.""" [group, name] = complete_name.split('.') element = self.get_element(group, name) if element: return element.ident else: logge...
Get the TocElement element id-number of the element with the supplied name.
Below is the the instruction that describes the task: ### Input: Get the TocElement element id-number of the element with the supplied name. ### Response: def get_element_id(self, complete_name): """Get the TocElement element id-number of the element with the supplied name.""" [grou...
def lookup_entry( self, linked_resource=None, sql_resource=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Get an entry by target resource name. This method allows clients to u...
Get an entry by target resource name. This method allows clients to use the resource name from the source Google Cloud Platform service to get the Cloud Data Catalog Entry. Example: >>> from google.cloud import datacatalog_v1beta1 >>> >>> client = datacatalog...
Below is the the instruction that describes the task: ### Input: Get an entry by target resource name. This method allows clients to use the resource name from the source Google Cloud Platform service to get the Cloud Data Catalog Entry. Example: >>> from google.cloud import dat...
def save(func): """@decorator: Saves data after executing :func:. Also performs modifications set as permanent options. """ def aux(self, *args, **kwargs): out = func(self, *args, **kwargs) path = (hasattr(self, 'path') and self.path or os.path.join(os.getcwd(), '.td'))...
@decorator: Saves data after executing :func:. Also performs modifications set as permanent options.
Below is the the instruction that describes the task: ### Input: @decorator: Saves data after executing :func:. Also performs modifications set as permanent options. ### Response: def save(func): """@decorator: Saves data after executing :func:. Also performs modifications set as permanent options. ...
def from_text(self, line, line_index, column, is_escaped): """Return the new state of the comment parser.""" begin = self._begin end = self._end single = self._single single_len = len(single) start_len = len(begin) if _token_at_col_in_line(line, column, single, ...
Return the new state of the comment parser.
Below is the the instruction that describes the task: ### Input: Return the new state of the comment parser. ### Response: def from_text(self, line, line_index, column, is_escaped): """Return the new state of the comment parser.""" begin = self._begin end = self._end single = self._...
def _area_settings(area, setting, value, validate_value): """Will validate area settings and values, returns data packet.""" if validate_value: # Exit delay has some specific limitations apparently if (setting == CONST.SETTING_EXIT_DELAY_AWAY and value not in ...
Will validate area settings and values, returns data packet.
Below is the the instruction that describes the task: ### Input: Will validate area settings and values, returns data packet. ### Response: def _area_settings(area, setting, value, validate_value): """Will validate area settings and values, returns data packet.""" if validate_value: # E...
def proxyval(self, visited): ''' Support for new-style classes. Currently we just locate the dictionary using a transliteration to python of _PyObject_GetDictPtr, ignoring descriptors ''' # Guard against infinite loops: if self.as_address() in visited: ...
Support for new-style classes. Currently we just locate the dictionary using a transliteration to python of _PyObject_GetDictPtr, ignoring descriptors
Below is the the instruction that describes the task: ### Input: Support for new-style classes. Currently we just locate the dictionary using a transliteration to python of _PyObject_GetDictPtr, ignoring descriptors ### Response: def proxyval(self, visited): ''' Support for new-sty...
def get_desc2nts_fnc(self, hdrgo_prt=True, section_prt=None, top_n=None, use_sections=True): """Return grouped, sorted namedtuples in either format: flat, sections.""" # RETURN: flat list of namedtuples nts_flat = self.get_nts_flat(hdrgo_prt, use_sections) if nts...
Return grouped, sorted namedtuples in either format: flat, sections.
Below is the the instruction that describes the task: ### Input: Return grouped, sorted namedtuples in either format: flat, sections. ### Response: def get_desc2nts_fnc(self, hdrgo_prt=True, section_prt=None, top_n=None, use_sections=True): """Return grouped, sorted namedtuples in ...
def _init_metadata(self): """stub""" self._objective_bank_id_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'objective_bank_id'), 'element_label': 'Objective Bank Id...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def _init_metadata(self): """stub""" self._objective_bank_id_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, ...
def from_coordinates(cls, coordinates): """Creates a `Primitive` from a list of coordinates.""" prim = cls() for coord in coordinates: pm = PseudoMonomer(ampal_parent=prim) pa = PseudoAtom(coord, ampal_parent=pm) pm.atoms = OrderedDict([('CA', pa)]) ...
Creates a `Primitive` from a list of coordinates.
Below is the the instruction that describes the task: ### Input: Creates a `Primitive` from a list of coordinates. ### Response: def from_coordinates(cls, coordinates): """Creates a `Primitive` from a list of coordinates.""" prim = cls() for coord in coordinates: pm = PseudoMono...
def ListHashes(age=aff4.NEWEST_TIME): """Yields all the hashes in the file store. Args: age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in microseconds since Jan 1st, 1970. If just a m...
Yields all the hashes in the file store. Args: age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in microseconds since Jan 1st, 1970. If just a microseconds value is given it's treat...
Below is the the instruction that describes the task: ### Input: Yields all the hashes in the file store. Args: age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in microseconds since Ja...
def get_row(self, row): '''Format a single row (if necessary)''' if isinstance(self.fields, dict): return dict([ (key, text_type(value).format(**row) if RE_FORMATTED.match(value) else row[value]) for key, value in self.fields.items() ]) el...
Format a single row (if necessary)
Below is the the instruction that describes the task: ### Input: Format a single row (if necessary) ### Response: def get_row(self, row): '''Format a single row (if necessary)''' if isinstance(self.fields, dict): return dict([ (key, text_type(value).format(**row) if RE_...
def error(transaction, code): # pragma: no cover """ Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction """ transact...
Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
Below is the the instruction that describes the task: ### Input: Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction ### Response: def error(tran...
def shift_image(im, shift, borderValue=0): """shift the image Parameters ---------- im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ------...
shift the image Parameters ---------- im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ------- im: 2d array The shifted image ...
Below is the the instruction that describes the task: ### Input: shift the image Parameters ---------- im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The value for the pixels outside the border (default 0) ...
def delete(self): """Delete the customer payment profile remotely and locally""" response = delete_payment_profile(self.customer_profile.profile_id, self.payment_profile_id) response.raise_if_error() return super(CustomerPaymentProfile, self).del...
Delete the customer payment profile remotely and locally
Below is the the instruction that describes the task: ### Input: Delete the customer payment profile remotely and locally ### Response: def delete(self): """Delete the customer payment profile remotely and locally""" response = delete_payment_profile(self.customer_profile.profile_id, ...
def write_to_manifest(self): """ Overwrites the section of the manifest with the featureconfig's value """ self.manifest.remove_section(self.feature_name) self.manifest.add_section(self.feature_name) for k, v in self.raw_dict.items(): self.manifest.set(self.feature_name, k, v...
Overwrites the section of the manifest with the featureconfig's value
Below is the the instruction that describes the task: ### Input: Overwrites the section of the manifest with the featureconfig's value ### Response: def write_to_manifest(self): """ Overwrites the section of the manifest with the featureconfig's value """ self.manifest.remove_section(self.feature_n...
def entropy_score(var,bins, w=None, decimate=True): '''Compute entropy scores, given a variance and # of bins ''' if w is None: n = len(var) w = np.arange(0,n,n//bins) / float(n) if decimate: n = len(var) var = var[0:n:n//bins] score = w * np.log(var * w * np.sqr...
Compute entropy scores, given a variance and # of bins
Below is the the instruction that describes the task: ### Input: Compute entropy scores, given a variance and # of bins ### Response: def entropy_score(var,bins, w=None, decimate=True): '''Compute entropy scores, given a variance and # of bins ''' if w is None: n = len(var) w = np....
def save(fname, data): """Saves a list of arrays or a dict of str->array to file. Examples of filenames: - ``/path/to/file`` - ``s3://my-bucket/path/to/file`` (if compiled with AWS S3 supports) - ``hdfs://path/to/file`` (if compiled with HDFS supports) Parameters ---------- fname : st...
Saves a list of arrays or a dict of str->array to file. Examples of filenames: - ``/path/to/file`` - ``s3://my-bucket/path/to/file`` (if compiled with AWS S3 supports) - ``hdfs://path/to/file`` (if compiled with HDFS supports) Parameters ---------- fname : str The filename. da...
Below is the the instruction that describes the task: ### Input: Saves a list of arrays or a dict of str->array to file. Examples of filenames: - ``/path/to/file`` - ``s3://my-bucket/path/to/file`` (if compiled with AWS S3 supports) - ``hdfs://path/to/file`` (if compiled with HDFS supports) P...
def get_devices(self): """ Return the devices linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_device(dev) for dev in result] return Command('get', [ROOT_DEVICES], process_result=process_result)
Return the devices linked to the gateway. Returns a Command.
Below is the the instruction that describes the task: ### Input: Return the devices linked to the gateway. Returns a Command. ### Response: def get_devices(self): """ Return the devices linked to the gateway. Returns a Command. """ def process_result(result): ...
def perform_action(self, action): """ Perform actions in the api from the CLI """ form = ToolForm s_action = form_action = action.split('_')[0] form_name = s_action.title() + ' tools' cores = False a_type = 'containers' forms = [action.upper() + 'TOOLS'] f...
Perform actions in the api from the CLI
Below is the the instruction that describes the task: ### Input: Perform actions in the api from the CLI ### Response: def perform_action(self, action): """ Perform actions in the api from the CLI """ form = ToolForm s_action = form_action = action.split('_')[0] form_name = s_action...
def best_prefix(bytes, system=NIST): """Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` ...
Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` keyword. Choices for ``system`` are ``bitmat...
Below is the the instruction that describes the task: ### Input: Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by s...
def download(self, source_file, source_len=0, info_cb=DEFAULT_MESSAGE_CALLBACK, progress_callback=None): """Downloads a file to the device. Args: source_file: A filename or file-like object to download to the device. source_len: Optional length of source_file. If source_file is a fil...
Downloads a file to the device. Args: source_file: A filename or file-like object to download to the device. source_len: Optional length of source_file. If source_file is a file-like object and source_len is not provided, source_file is read into memory. info_cb: Optional call...
Below is the the instruction that describes the task: ### Input: Downloads a file to the device. Args: source_file: A filename or file-like object to download to the device. source_len: Optional length of source_file. If source_file is a file-like object and source_len is not provided, so...
def dispatch_request(self): """ Handle redirect back from provider """ if current_user.is_authenticated: return redirect(self.next) # clear previous! if 'social_data' in session: del session['social_data'] res = self.app.authorized_response() if ...
Handle redirect back from provider
Below is the the instruction that describes the task: ### Input: Handle redirect back from provider ### Response: def dispatch_request(self): """ Handle redirect back from provider """ if current_user.is_authenticated: return redirect(self.next) # clear previous! if 'so...
def getLoadAvg(self): """Return system Load Average. @return: List of 1 min, 5 min and 15 min Load Average figures. """ try: fp = open(loadavgFile, 'r') line = fp.readline() fp.close() except: raise IOError('Failed...
Return system Load Average. @return: List of 1 min, 5 min and 15 min Load Average figures.
Below is the the instruction that describes the task: ### Input: Return system Load Average. @return: List of 1 min, 5 min and 15 min Load Average figures. ### Response: def getLoadAvg(self): """Return system Load Average. @return: List of 1 min, 5 min and 15 min Load Aver...
def asset_url_for(self, asset): """ Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found ""...
Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found
Below is the the instruction that describes the task: ### Input: Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not...
def init(self, force_deploy=False, client=None): """Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be red...
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
Below is the the instruction that describes the task: ### Input: Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment mu...
def setup_seasonal(self): """ Check if there's some seasonal holiday going on, setup appropriate Shibe picture and load holiday words. Note: if there are two or more holidays defined for a certain date, the first one takes precedence. """ # If we've specified a...
Check if there's some seasonal holiday going on, setup appropriate Shibe picture and load holiday words. Note: if there are two or more holidays defined for a certain date, the first one takes precedence.
Below is the the instruction that describes the task: ### Input: Check if there's some seasonal holiday going on, setup appropriate Shibe picture and load holiday words. Note: if there are two or more holidays defined for a certain date, the first one takes precedence. ### Response: def se...
def unsubscribe(request, message_id, dispatch_id, hashed, redirect_to=None): """Handles unsubscribe request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return: """ return _generic_view( 'handle_unsubscri...
Handles unsubscribe request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return:
Below is the the instruction that describes the task: ### Input: Handles unsubscribe request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return: ### Response: def unsubscribe(request, message_id, dispatch_id, hashed, r...
def _request(self, method, *relative_path_parts, **kwargs): """Sends an HTTP request to the REST API and receives the requested data. Additionally sets up pagination cursors. :param str method: HTTP method name :param relative_path_parts: the relative paths for the request URI :param kwargs: argume...
Sends an HTTP request to the REST API and receives the requested data. Additionally sets up pagination cursors. :param str method: HTTP method name :param relative_path_parts: the relative paths for the request URI :param kwargs: argument keywords :returns: requested data :raises APIError: for ...
Below is the the instruction that describes the task: ### Input: Sends an HTTP request to the REST API and receives the requested data. Additionally sets up pagination cursors. :param str method: HTTP method name :param relative_path_parts: the relative paths for the request URI :param kwargs: argu...
def add_leverage(self): """ Adds leverage term to the model Returns ---------- None (changes instance attributes) """ if self.leverage is True: pass else: self.leverage = True self.z_no += 1 self.laten...
Adds leverage term to the model Returns ---------- None (changes instance attributes)
Below is the the instruction that describes the task: ### Input: Adds leverage term to the model Returns ---------- None (changes instance attributes) ### Response: def add_leverage(self): """ Adds leverage term to the model Returns ---------- None (changes...
def handle_command_line(options): """ act upon command options """ options = merge(options, constants.DEFAULT_OPTIONS) engine = plugins.ENGINES.get_engine( options[constants.LABEL_TEMPLATE_TYPE], options[constants.LABEL_TMPL_DIRS], options[constants.LABEL_CONFIG_DIR], ) ...
act upon command options
Below is the the instruction that describes the task: ### Input: act upon command options ### Response: def handle_command_line(options): """ act upon command options """ options = merge(options, constants.DEFAULT_OPTIONS) engine = plugins.ENGINES.get_engine( options[constants.LABEL_TEM...
def GetLayerFromFeatureService(self, fs, layerName="", returnURLOnly=False): """Obtains a layer from a feature service by feature service reference. Args: fs (FeatureService): The feature service from which to obtain the layer. layerName (str): The name of the layer. Defaults to...
Obtains a layer from a feature service by feature service reference. Args: fs (FeatureService): The feature service from which to obtain the layer. layerName (str): The name of the layer. Defaults to ``""``. returnURLOnly (bool): A boolean value to return the URL of the laye...
Below is the the instruction that describes the task: ### Input: Obtains a layer from a feature service by feature service reference. Args: fs (FeatureService): The feature service from which to obtain the layer. layerName (str): The name of the layer. Defaults to ``""``. ...
def get_model_creation_kwargs(model_obj): """ Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the ...
Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are nee...
Below is the the instruction that describes the task: ### Input: Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. ...
def clean_expired_user_attempts(attempt_time: datetime = None) -> int: """ Clean expired user attempts from the database. """ if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured') return 0 thr...
Clean expired user attempts from the database.
Below is the the instruction that describes the task: ### Input: Clean expired user attempts from the database. ### Response: def clean_expired_user_attempts(attempt_time: datetime = None) -> int: """ Clean expired user attempts from the database. """ if settings.AXES_COOLOFF_TIME is None: ...
def clean_username(self): """ Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. """ try: user = get_user_model().objects.get(username=self.cleaned_data["username"]) except get_user_model().DoesNot...
Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list.
Below is the the instruction that describes the task: ### Input: Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. ### Response: def clean_username(self): """ Validate that the username is unique and not listed in ``defaults.ACC...
def local_time_to_online(dt=None): """Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in...
Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000) Examples...
Below is the the instruction that describes the task: ### Input: Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as ...
def psetex(self, name, time_ms, value): """ Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object """ if isinstance(time_ms, datetime.timedelta): time_ms =...
Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object
Below is the the instruction that describes the task: ### Input: Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object ### Response: def psetex(self, name, time_ms, value): """ S...
def configure(self, name=None, rules=None, query=None, **options): """Configure the alert.""" self.name = name if not name: raise AssertionError("Alert's name should be defined and not empty.") if not rules: raise AssertionError("%s: Alert's rules is invalid" % n...
Configure the alert.
Below is the the instruction that describes the task: ### Input: Configure the alert. ### Response: def configure(self, name=None, rules=None, query=None, **options): """Configure the alert.""" self.name = name if not name: raise AssertionError("Alert's name should be defined an...
def set_secure_boot_mode(self, secure_boot_enable): """Enable/Disable secure boot on the server. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, i...
Enable/Disable secure boot on the server. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
Below is the the instruction that describes the task: ### Input: Enable/Disable secure boot on the server. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedEr...
def build(client, repository_tag, docker_file, tag=None, use_cache=False): """ Build a docker image """ if not isinstance(client, docker.Client): raise TypeError("client needs to be of type docker.Client.") if not isinstance(docker_file, six.string_types) or not os.p...
Build a docker image
Below is the the instruction that describes the task: ### Input: Build a docker image ### Response: def build(client, repository_tag, docker_file, tag=None, use_cache=False): """ Build a docker image """ if not isinstance(client, docker.Client): raise TypeError("client n...
def callJavaFunc(func, *args): """ Call Java Function """ gateway = _get_gateway() args = [_py2java(gateway, a) for a in args] result = func(*args) return _java2py(gateway, result)
Call Java Function
Below is the the instruction that describes the task: ### Input: Call Java Function ### Response: def callJavaFunc(func, *args): """ Call Java Function """ gateway = _get_gateway() args = [_py2java(gateway, a) for a in args] result = func(*args) return _java2py(gateway, result)
def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """ ls1, ls2 = len(str1), len(str2) if str1.isdigit(): # 10 SM if str2 in ['SM', '0SM']: return True # 12 /10 if ls2 > 2 and str2[0] ...
Return True if a space shouldn't exist between two items
Below is the the instruction that describes the task: ### Input: Return True if a space shouldn't exist between two items ### Response: def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """ ls1, ls2 = len(str1), len(str2) ...
def entity(self, entity_type, identifier=None): """Factory method for creating an Entity. If an entity with the same type and identifier already exists, this will return a reference to that entity. If not, it will create a new one and add it to the list of known entities for th...
Factory method for creating an Entity. If an entity with the same type and identifier already exists, this will return a reference to that entity. If not, it will create a new one and add it to the list of known entities for this ACL. :type entity_type: str :param enti...
Below is the the instruction that describes the task: ### Input: Factory method for creating an Entity. If an entity with the same type and identifier already exists, this will return a reference to that entity. If not, it will create a new one and add it to the list of known entities for ...
def since(self, ts): """ Query the oplog for items since ts and then return """ spec = {'ts': {'$gt': ts}} cursor = self.query(spec) while True: # todo: trap InvalidDocument errors: # except bson.errors.InvalidDocument as e: # logging....
Query the oplog for items since ts and then return
Below is the the instruction that describes the task: ### Input: Query the oplog for items since ts and then return ### Response: def since(self, ts): """ Query the oplog for items since ts and then return """ spec = {'ts': {'$gt': ts}} cursor = self.query(spec) whil...
def _matcher(self, other): """ QueryContainer < MoleculeContainer QueryContainer < QueryContainer[more general] QueryContainer < QueryCGRContainer[more general] """ if isinstance(other, MoleculeContainer): return GraphMatcher(other, self, lambda x, y: y == x, ...
QueryContainer < MoleculeContainer QueryContainer < QueryContainer[more general] QueryContainer < QueryCGRContainer[more general]
Below is the the instruction that describes the task: ### Input: QueryContainer < MoleculeContainer QueryContainer < QueryContainer[more general] QueryContainer < QueryCGRContainer[more general] ### Response: def _matcher(self, other): """ QueryContainer < MoleculeContainer ...
def new(path='.', template=None): """Creates a new project """ path = abspath(path.rstrip(sep)) template = template or DEFAULT_TEMPLATE_URL render_skeleton( template, path, include_this=['.gitignore'], filter_this=[ '~*', '*.py[co]', '__pycache__', '__...
Creates a new project
Below is the the instruction that describes the task: ### Input: Creates a new project ### Response: def new(path='.', template=None): """Creates a new project """ path = abspath(path.rstrip(sep)) template = template or DEFAULT_TEMPLATE_URL render_skeleton( template, path, inclu...