code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_logger(name=None): """ Get virtualchain's logger """ level = logging.CRITICAL if DEBUG: logging.disable(logging.NOTSET) level = logging.DEBUG if name is None: name = "<unknown>" log = logging.getLogger(name=name) log.setLevel( level ) console = logg...
Get virtualchain's logger
Below is the the instruction that describes the task: ### Input: Get virtualchain's logger ### Response: def get_logger(name=None): """ Get virtualchain's logger """ level = logging.CRITICAL if DEBUG: logging.disable(logging.NOTSET) level = logging.DEBUG if name is None: ...
def wait_condition_spec(self): """Spec for a wait_condition block""" from harpoon.option_spec import image_objs formatted_string = formatted(string_spec(), formatter=MergedOptionStringFormatter) return create_spec(image_objs.WaitCondition , harpoon = formatted(overridden("{ha...
Spec for a wait_condition block
Below is the the instruction that describes the task: ### Input: Spec for a wait_condition block ### Response: def wait_condition_spec(self): """Spec for a wait_condition block""" from harpoon.option_spec import image_objs formatted_string = formatted(string_spec(), formatter=MergedOptionSt...
def set_remote_config(experiment_config, port, config_file_name): '''Call setClusterMetadata to pass trial''' #set machine_list request_data = dict() request_data['machine_list'] = experiment_config['machineList'] if request_data['machine_list']: for i in range(len(request_data['machine_list...
Call setClusterMetadata to pass trial
Below is the the instruction that describes the task: ### Input: Call setClusterMetadata to pass trial ### Response: def set_remote_config(experiment_config, port, config_file_name): '''Call setClusterMetadata to pass trial''' #set machine_list request_data = dict() request_data['machine_list'] = e...
def key_values_cache_key_name(cls, *key_fields): """ Key for fetching unique key values from the cache """ key_fields = key_fields or cls.KEY_FIELDS return 'configuration/{}/key_values/{}'.format(cls.__name__, ','.join(key_fields))
Key for fetching unique key values from the cache
Below is the the instruction that describes the task: ### Input: Key for fetching unique key values from the cache ### Response: def key_values_cache_key_name(cls, *key_fields): """ Key for fetching unique key values from the cache """ key_fields = key_fields or cls.KEY_FIELDS return 'confi...
def get_productivity_stats(self): """Return the user's productivity stats. :return: A JSON-encoded representation of the user's productivity stats. :rtype: A JSON-encoded object. >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'passw...
Return the user's productivity stats. :return: A JSON-encoded representation of the user's productivity stats. :rtype: A JSON-encoded object. >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> stats = user.get_productivi...
Below is the the instruction that describes the task: ### Input: Return the user's productivity stats. :return: A JSON-encoded representation of the user's productivity stats. :rtype: A JSON-encoded object. >>> from pytodoist import todoist >>> user = todoist.login('joh...
def execute(self, input_data): ''' Execute method ''' # Spin up the rekall adapter adapter = RekallAdapter() adapter.set_plugin_name(self.plugin_name) rekall_output = adapter.execute(input_data) # Process the output data for line in rekall_output: i...
Execute method
Below is the the instruction that describes the task: ### Input: Execute method ### Response: def execute(self, input_data): ''' Execute method ''' # Spin up the rekall adapter adapter = RekallAdapter() adapter.set_plugin_name(self.plugin_name) rekall_output = adapter.execu...
def p_propertyDeclaration_7(p): """propertyDeclaration_7 : qualifierList dataType propertyName array ';'""" quals = OrderedDict([(x.name, x) for x in p[1]]) p[0] = CIMProperty(p[3], None, type=p[2], qualifiers=quals, is_array=True, array_size=p[4])
propertyDeclaration_7 : qualifierList dataType propertyName array ';
Below is the the instruction that describes the task: ### Input: propertyDeclaration_7 : qualifierList dataType propertyName array '; ### Response: def p_propertyDeclaration_7(p): """propertyDeclaration_7 : qualifierList dataType propertyName array ';'""" quals = OrderedDict([(x.name, x) for x in p[1]]) ...
def _contains(self, hit): '''Returns True iff (the query contig is contained in the reference contig and the query contig is not flagged to be kept)''' return ( hit.qry_name not in self.contigs_to_keep and hit.qry_name != hit.ref_name and (100 * hit.hit_len...
Returns True iff (the query contig is contained in the reference contig and the query contig is not flagged to be kept)
Below is the the instruction that describes the task: ### Input: Returns True iff (the query contig is contained in the reference contig and the query contig is not flagged to be kept) ### Response: def _contains(self, hit): '''Returns True iff (the query contig is contained in the reference con...
def hasApplication(self, app): """Returns True if app is among the loaded modules. @param app: Module name. @return: Boolean """ if self._applications is None: self._initApplicationList() return app in self._applications
Returns True if app is among the loaded modules. @param app: Module name. @return: Boolean
Below is the the instruction that describes the task: ### Input: Returns True if app is among the loaded modules. @param app: Module name. @return: Boolean ### Response: def hasApplication(self, app): """Returns True if app is among the loaded modules. @param ap...
def irip(ip, rc=None, r=None, fl=None, fs=None, ot=None, coe=None, moc=DEFAULT_ITER_MAXOBJECTCOUNT): # pylint: disable=too-many-arguments, redefined-outer-name, invalid-name """ *New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMCo...
*New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMConnection.IterReferenceInstancePaths`. Retrieve the instance paths of the association instances that reference a source instance, using the corresponding pull operations if supported by t...
Below is the the instruction that describes the task: ### Input: *New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMConnection.IterReferenceInstancePaths`. Retrieve the instance paths of the association instances that reference a source in...
def tag_builder(parser, token, cls, flow_type): """Helper function handling flow form tags.""" tokens = token.split_contents() tokens_num = len(tokens) if tokens_num == 1 or (tokens_num == 3 and tokens[1] == 'for'): flow_name = None if tokens_num == 3: flow_name = tokens[2] ...
Helper function handling flow form tags.
Below is the the instruction that describes the task: ### Input: Helper function handling flow form tags. ### Response: def tag_builder(parser, token, cls, flow_type): """Helper function handling flow form tags.""" tokens = token.split_contents() tokens_num = len(tokens) if tokens_num == 1 or (tok...
def run_iterations(cls, the_callable, iterations=1, label=None, schedule='* * * * * *', userdata = None, run_immediately=False, delay_until=None): """Class method to run a callable with a specified number of iterations""" task = task_with_callable(the_callable, label=label, schedule=schedule, userdata=u...
Class method to run a callable with a specified number of iterations
Below is the the instruction that describes the task: ### Input: Class method to run a callable with a specified number of iterations ### Response: def run_iterations(cls, the_callable, iterations=1, label=None, schedule='* * * * * *', userdata = None, run_immediately=False, delay_until=None): """Class met...
def begin_date(self, value): """ A datetime.datetime object of when the certificate becomes valid. """ if not isinstance(value, datetime): raise TypeError(_pretty_message( ''' begin_date must be an instance of datetime.datetime, not %s ...
A datetime.datetime object of when the certificate becomes valid.
Below is the the instruction that describes the task: ### Input: A datetime.datetime object of when the certificate becomes valid. ### Response: def begin_date(self, value): """ A datetime.datetime object of when the certificate becomes valid. """ if not isinstance(value, datetime)...
def pickle_load(name, extension='.pkl'): """Load data with pickle. Parameters ---------- name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. Returns ------- Contents of file path. """ filename = name + extension...
Load data with pickle. Parameters ---------- name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. Returns ------- Contents of file path.
Below is the the instruction that describes the task: ### Input: Load data with pickle. Parameters ---------- name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. Returns ------- Contents of file path. ### Response: def...
def jinja_loader(self): """Search templates in custom app templates dir (default Flask behaviour), fallback on abilian templates.""" loaders = self._jinja_loaders del self._jinja_loaders loaders.append(Flask.jinja_loader.func(self)) loaders.reverse() return jinja2...
Search templates in custom app templates dir (default Flask behaviour), fallback on abilian templates.
Below is the the instruction that describes the task: ### Input: Search templates in custom app templates dir (default Flask behaviour), fallback on abilian templates. ### Response: def jinja_loader(self): """Search templates in custom app templates dir (default Flask behaviour), fallback o...
def ping_pong(connection, command, strexp, timeout=10): ''' Enter a command and wait for something to happen (enter + expect combined) @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str...
Enter a command and wait for something to happen (enter + expect combined) @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param strexp: string to convert to expression (.*string.*) ...
Below is the the instruction that describes the task: ### Input: Enter a command and wait for something to happen (enter + expect combined) @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str ...
def process(self, value, tag=None): """ Process (marshal) the tag with the specified value using the optional type information. @param value: The value (content) of the XML node. @type value: (L{Object}|any) @param tag: The (optional) tag name for the value. The default ...
Process (marshal) the tag with the specified value using the optional type information. @param value: The value (content) of the XML node. @type value: (L{Object}|any) @param tag: The (optional) tag name for the value. The default is value.__class__.__name__ @type ta...
Below is the the instruction that describes the task: ### Input: Process (marshal) the tag with the specified value using the optional type information. @param value: The value (content) of the XML node. @type value: (L{Object}|any) @param tag: The (optional) tag name for the value. ...
def entities(self, subject_id): """ Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param subject_id: The identifier of the subject :return: A possibly empty list of entity identifiers """ try: ...
Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param subject_id: The identifier of the subject :return: A possibly empty list of entity identifiers
Below is the the instruction that describes the task: ### Input: Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param subject_id: The identifier of the subject :return: A possibly empty list of entity identifiers ### Response...
def reset_everything(self, payload): """Kill all processes, delete the queue and clean everything up.""" kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.process_handler.wait_for_finish() self.reset = True answer = {'message': 'Resetting c...
Kill all processes, delete the queue and clean everything up.
Below is the the instruction that describes the task: ### Input: Kill all processes, delete the queue and clean everything up. ### Response: def reset_everything(self, payload): """Kill all processes, delete the queue and clean everything up.""" kill_signal = signals['9'] self.process_handl...
def send_mass_sms(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (message, from_phone, to, flash), sends each message to each recipient list. :returns: the number of SMSs sent. """ from sendsms.message import SmsMessa...
Given a datatuple of (message, from_phone, to, flash), sends each message to each recipient list. :returns: the number of SMSs sent.
Below is the the instruction that describes the task: ### Input: Given a datatuple of (message, from_phone, to, flash), sends each message to each recipient list. :returns: the number of SMSs sent. ### Response: def send_mass_sms(datatuple, fail_silently=False, auth_user=None, auth_password=N...
def _isLastCodeColumn(self, block, column): """Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. """ return column >= self._lastColumn(block) or \ ...
Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment.
Below is the the instruction that describes the task: ### Input: Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. ### Response: def _isLastCodeColumn(self, block, column): ...
def retrieve(self, id) : """ Retrieve a single tag Returns a single tag available to the user according to the unique ID provided If the specified tag does not exist, this query will return an error :calls: ``get /tags/{id}`` :param int id: Unique identifier of a Tag. ...
Retrieve a single tag Returns a single tag available to the user according to the unique ID provided If the specified tag does not exist, this query will return an error :calls: ``get /tags/{id}`` :param int id: Unique identifier of a Tag. :return: Dictionary that support attri...
Below is the the instruction that describes the task: ### Input: Retrieve a single tag Returns a single tag available to the user according to the unique ID provided If the specified tag does not exist, this query will return an error :calls: ``get /tags/{id}`` :param int id: Uniqu...
def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function by sending a transaction. """ trans...
Helper function for interacting with a contract function by sending a transaction.
Below is the the instruction that describes the task: ### Input: Helper function for interacting with a contract function by sending a transaction. ### Response: def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, ...
def get_word_level_vocab(self): """Provides word level vocabulary Returns ------- Vocab Word level vocabulary """ def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'): return list(filter(None, re.split(token_delim + '|' + seq_delim, s...
Provides word level vocabulary Returns ------- Vocab Word level vocabulary
Below is the the instruction that describes the task: ### Input: Provides word level vocabulary Returns ------- Vocab Word level vocabulary ### Response: def get_word_level_vocab(self): """Provides word level vocabulary Returns ------- Vocab ...
def corpus(self): '''Command to add a corpus to the dsrt library''' # Initialize the addcorpus subcommand's argparser description = '''The corpus subcommand has a number of subcommands of its own, including: list\t-\tlists all available corpora in dsrt's library add\t-\t...
Command to add a corpus to the dsrt library
Below is the the instruction that describes the task: ### Input: Command to add a corpus to the dsrt library ### Response: def corpus(self): '''Command to add a corpus to the dsrt library''' # Initialize the addcorpus subcommand's argparser description = '''The corpus subcommand has a numb...
def process_input(self, stream, value, rpc_executor): """Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. Args: stream (DataStream): The stream the input is pa...
Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. Args: stream (DataStream): The stream the input is part of value (IOTileReading): The value to process ...
Below is the the instruction that describes the task: ### Input: Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. Args: stream (DataStream): The stream the input i...
def is_labial(c,lang): """ Is the character a labial """ o=get_offset(c,lang) return (o>=LABIAL_RANGE[0] and o<=LABIAL_RANGE[1])
Is the character a labial
Below is the the instruction that describes the task: ### Input: Is the character a labial ### Response: def is_labial(c,lang): """ Is the character a labial """ o=get_offset(c,lang) return (o>=LABIAL_RANGE[0] and o<=LABIAL_RANGE[1])
def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None): """ Edit a user. Modify an existing user. To modify a user's login, see the documentation for logins....
Edit a user. Modify an existing user. To modify a user's login, see the documentation for logins.
Below is the the instruction that describes the task: ### Input: Edit a user. Modify an existing user. To modify a user's login, see the documentation for logins. ### Response: def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_s...
def upload(self, login, package_name, release, basename, fd, distribution_type, description='', md5=None, size=None, dependencies=None, attrs=None, channels=('main',), callback=None): ''' Upload a new distribution to a package release. :param login: the login of the package owner...
Upload a new distribution to a package release. :param login: the login of the package owner :param package_name: the name of the package :param version: the version string of the release :param basename: the basename of the distribution to download :param fd: a file like object...
Below is the the instruction that describes the task: ### Input: Upload a new distribution to a package release. :param login: the login of the package owner :param package_name: the name of the package :param version: the version string of the release :param basename: the basename ...
def getWindows(input): """Get a source's windows""" with rasterio.open(input) as src: return [[window, ij] for ij, window in src.block_windows()]
Get a source's windows
Below is the the instruction that describes the task: ### Input: Get a source's windows ### Response: def getWindows(input): """Get a source's windows""" with rasterio.open(input) as src: return [[window, ij] for ij, window in src.block_windows()]
def to_numpy(self, dtype=None, copy=False): """ Convert the DataFrame to a NumPy array. .. versionadded:: 0.24.0 By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are ``float16`` and ``fl...
Convert the DataFrame to a NumPy array. .. versionadded:: 0.24.0 By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are ``float16`` and ``float32``, the results dtype will be ``float32``. This may...
Below is the the instruction that describes the task: ### Input: Convert the DataFrame to a NumPy array. .. versionadded:: 0.24.0 By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are ``float16`` and...
def request_view(request, request_pk): ''' The view of a single request. ''' if request.is_ajax(): if not request.user.is_authenticated(): return HttpResponse(json.dumps(dict()), content_type="application/json") try: relevant_reque...
The view of a single request.
Below is the the instruction that describes the task: ### Input: The view of a single request. ### Response: def request_view(request, request_pk): ''' The view of a single request. ''' if request.is_ajax(): if not request.user.is_authenticated(): return HttpResponse(json.dumps(...
def extract(archive_file, path=".", delete_on_success=False, enable_rar=False): """ Automatically detect archive type and extract all files to specified path. .. code:: python import os os.listdir(".") # ['test_structure.zip'] reusables.extract("test_structure...
Automatically detect archive type and extract all files to specified path. .. code:: python import os os.listdir(".") # ['test_structure.zip'] reusables.extract("test_structure.zip") os.listdir(".") # [ 'test_structure', 'test_structure.zip'] :param archive...
Below is the the instruction that describes the task: ### Input: Automatically detect archive type and extract all files to specified path. .. code:: python import os os.listdir(".") # ['test_structure.zip'] reusables.extract("test_structure.zip") os.listdir(".") ...
def publish(self, load): ''' Publish "load" to minions ''' payload = {'enc': 'aes'} crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value) payload['load'] = crypticle.dumps(load) if self.opts['sign_pub_messages']: ...
Publish "load" to minions
Below is the the instruction that describes the task: ### Input: Publish "load" to minions ### Response: def publish(self, load): ''' Publish "load" to minions ''' payload = {'enc': 'aes'} crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secre...
def datetime( self, year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> datetime """ Return a normalized datetime for the current timezone. """ if _HAS_FOLD: return self.convert( datetime(y...
Return a normalized datetime for the current timezone.
Below is the the instruction that describes the task: ### Input: Return a normalized datetime for the current timezone. ### Response: def datetime( self, year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> datetime """ Return a ...
def create_ants_transform(transform_type='AffineTransform', precision='float', dimension=3, matrix=None, offset=None, center=None, translation=None, ...
Create and initialize an ANTsTransform ANTsR function: `createAntsrTransform` Arguments --------- transform_type : string type of transform(s) precision : string numerical precision dimension : integer spatial dimension of transform matrix : ndarra...
Below is the the instruction that describes the task: ### Input: Create and initialize an ANTsTransform ANTsR function: `createAntsrTransform` Arguments --------- transform_type : string type of transform(s) precision : string numerical precision dimension : in...
def acquire(self,blocking=True,timeout=None): """Attempt to acquire this lock. If the optional argument "blocking" is True and "timeout" is None, this methods blocks until is successfully acquires the lock. If "blocking" is False, it returns immediately if the lock could not be...
Attempt to acquire this lock. If the optional argument "blocking" is True and "timeout" is None, this methods blocks until is successfully acquires the lock. If "blocking" is False, it returns immediately if the lock could not be acquired. Otherwise, it blocks for at most "timeout" se...
Below is the the instruction that describes the task: ### Input: Attempt to acquire this lock. If the optional argument "blocking" is True and "timeout" is None, this methods blocks until is successfully acquires the lock. If "blocking" is False, it returns immediately if the lock could no...
def get_data(self): """ Retrieve the relation data for each unit involved in a relation and, if complete, store it in a list under `self[self.name]`. This is automatically called when the RelationContext is instantiated. The units are sorted lexographically first by the service...
Retrieve the relation data for each unit involved in a relation and, if complete, store it in a list under `self[self.name]`. This is automatically called when the RelationContext is instantiated. The units are sorted lexographically first by the service ID, then by the unit ID. Thus,...
Below is the the instruction that describes the task: ### Input: Retrieve the relation data for each unit involved in a relation and, if complete, store it in a list under `self[self.name]`. This is automatically called when the RelationContext is instantiated. The units are sorted lexogra...
def BorueErukhimovich_Powerlaw(q, C, r0, s, t, nu): """Borue-Erukhimovich model ending in a power-law. Inputs: ------- ``q``: independent variable ``C``: scaling factor ``r0``: typical el.stat. screening length ``s``: dimensionless charge concentration ``t``: dimensi...
Borue-Erukhimovich model ending in a power-law. Inputs: ------- ``q``: independent variable ``C``: scaling factor ``r0``: typical el.stat. screening length ``s``: dimensionless charge concentration ``t``: dimensionless temperature ``nu``: excluded volume paramete...
Below is the the instruction that describes the task: ### Input: Borue-Erukhimovich model ending in a power-law. Inputs: ------- ``q``: independent variable ``C``: scaling factor ``r0``: typical el.stat. screening length ``s``: dimensionless charge concentration ``t`...
def dashboard_absent( name, hosts=None, profile='grafana'): ''' Ensure the named grafana dashboard is deleted. name Name of the grafana dashboard. profile A pillar key or dict that contains a list of hosts and an elasticsearch index to use. ''' r...
Ensure the named grafana dashboard is deleted. name Name of the grafana dashboard. profile A pillar key or dict that contains a list of hosts and an elasticsearch index to use.
Below is the the instruction that describes the task: ### Input: Ensure the named grafana dashboard is deleted. name Name of the grafana dashboard. profile A pillar key or dict that contains a list of hosts and an elasticsearch index to use. ### Response: def dashboard_absent( ...
def ReplaceItem(self, document_link, new_document, options=None): """Replaces a document and returns it. :param str document_link: The link to the document. :param dict new_document: :param dict options: The request options for the request. :return: ...
Replaces a document and returns it. :param str document_link: The link to the document. :param dict new_document: :param dict options: The request options for the request. :return: The new Document. :rtype: dict
Below is the the instruction that describes the task: ### Input: Replaces a document and returns it. :param str document_link: The link to the document. :param dict new_document: :param dict options: The request options for the request. :return: ...
def filter(args): """ %prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features """ p = OptionParser(filter.__...
%prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features
Below is the the instruction that describes the task: ### Input: %prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features...
def _ratelimit(self, http_method, url, **kwargs): """ Ensure we do not hit the rate limit. """ def time_since_last_call(): if self.callsafety['lastcalltime'] is not None: return int(time() - self.callsafety['lastcalltime']) else: return None ...
Ensure we do not hit the rate limit.
Below is the the instruction that describes the task: ### Input: Ensure we do not hit the rate limit. ### Response: def _ratelimit(self, http_method, url, **kwargs): """ Ensure we do not hit the rate limit. """ def time_since_last_call(): if self.callsafety['lastcalltime'] is not None:...
def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU.""" padded_shapes = {} def get_filler(specified_max_length): if not specified_max_length: return max_length return min(specified_max_length, max_length) inputs_none_filler = get_filler(hparams.max_inp...
Pads unknown features' dimensions for TPU.
Below is the the instruction that describes the task: ### Input: Pads unknown features' dimensions for TPU. ### Response: def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU.""" padded_shapes = {} def get_filler(specified_max_length): if not specified_max_leng...
def accept_freeware_license(): '''different Eagle versions need differnt TAB count. 6.5 -> 2 6.6 -> 3 7.4 -> 2 ''' ntab = 3 if version().startswith('6.6.') else 2 for _ in range(ntab): EasyProcess('xdotool key KP_Tab').call() time.sleep(0.5) EasyProcess('xdotool key KP...
different Eagle versions need differnt TAB count. 6.5 -> 2 6.6 -> 3 7.4 -> 2
Below is the the instruction that describes the task: ### Input: different Eagle versions need differnt TAB count. 6.5 -> 2 6.6 -> 3 7.4 -> 2 ### Response: def accept_freeware_license(): '''different Eagle versions need differnt TAB count. 6.5 -> 2 6.6 -> 3 7.4 -> 2 ''' nt...
def path(self, *paths, **kwargs): """Create new Path based on self.root and provided paths. :param paths: List of sub paths :param kwargs: required=False :rtype: Path """ return self.__class__(self.__root__, *paths, **kwargs)
Create new Path based on self.root and provided paths. :param paths: List of sub paths :param kwargs: required=False :rtype: Path
Below is the the instruction that describes the task: ### Input: Create new Path based on self.root and provided paths. :param paths: List of sub paths :param kwargs: required=False :rtype: Path ### Response: def path(self, *paths, **kwargs): """Create new Path based on self.root a...
def get_user_group(user_group): """ Formats a user and group in the format ``user:group``, as needed for `chown`. If user_group is a tuple, this is used for the fomatting. If a string or integer is given, it will be formatted as ``user:user``. Otherwise the input is returned - this method does not perfo...
Formats a user and group in the format ``user:group``, as needed for `chown`. If user_group is a tuple, this is used for the fomatting. If a string or integer is given, it will be formatted as ``user:user``. Otherwise the input is returned - this method does not perform any more checks. :param user_group: ...
Below is the the instruction that describes the task: ### Input: Formats a user and group in the format ``user:group``, as needed for `chown`. If user_group is a tuple, this is used for the fomatting. If a string or integer is given, it will be formatted as ``user:user``. Otherwise the input is returned - t...
def capakey_rest_gateway_request(url, headers={}, params={}): ''' Utility function that helps making requests to the CAPAKEY REST service. :param string url: URL to request. :param dict headers: Headers to send with the URL. :param dict params: Parameters to send with the URL. :returns: Result ...
Utility function that helps making requests to the CAPAKEY REST service. :param string url: URL to request. :param dict headers: Headers to send with the URL. :param dict params: Parameters to send with the URL. :returns: Result of the call.
Below is the the instruction that describes the task: ### Input: Utility function that helps making requests to the CAPAKEY REST service. :param string url: URL to request. :param dict headers: Headers to send with the URL. :param dict params: Parameters to send with the URL. :returns: Result of th...
def get_job_image_info(project: 'Project', job: Any) -> Tuple[str, str]: """Return the image name and image tag for a job""" project_name = project.name repo_name = project_name image_name = '{}/{}'.format(conf.get('REGISTRY_URI'), repo_name) try: last_commit = project.repo.last_commit ...
Return the image name and image tag for a job
Below is the the instruction that describes the task: ### Input: Return the image name and image tag for a job ### Response: def get_job_image_info(project: 'Project', job: Any) -> Tuple[str, str]: """Return the image name and image tag for a job""" project_name = project.name repo_name = project_name ...
def process_resource(self, req, resp, resource): """ Process the request after routing. Deserializer selection needs a resource to determine which deserializers are allowed. If a deserializer is required then it will be initialized & added to the request object for further proce...
Process the request after routing. Deserializer selection needs a resource to determine which deserializers are allowed. If a deserializer is required then it will be initialized & added to the request object for further processing.
Below is the the instruction that describes the task: ### Input: Process the request after routing. Deserializer selection needs a resource to determine which deserializers are allowed. If a deserializer is required then it will be initialized & added to the request object for furth...
def _retrieve_and_validate_certificate_chain(self, cert_url): # type: (str) -> Certificate """Retrieve and validate certificate chain. This method validates if the URL is valid and loads and validates the certificate chain, before returning it. :param cert_url: URL for retrievi...
Retrieve and validate certificate chain. This method validates if the URL is valid and loads and validates the certificate chain, before returning it. :param cert_url: URL for retrieving certificate chain :type cert_url: str :return The certificate chain loaded from the URL ...
Below is the the instruction that describes the task: ### Input: Retrieve and validate certificate chain. This method validates if the URL is valid and loads and validates the certificate chain, before returning it. :param cert_url: URL for retrieving certificate chain :type cert_u...
def _get_c_valid_arr(self, x): """ Warning! Interpretation of axes is different for C code. """ orig_shape = x.shape x = np.ascontiguousarray(x.reshape(orig_shape[0], -1).T) return orig_shape, x
Warning! Interpretation of axes is different for C code.
Below is the the instruction that describes the task: ### Input: Warning! Interpretation of axes is different for C code. ### Response: def _get_c_valid_arr(self, x): """ Warning! Interpretation of axes is different for C code. """ orig_shape = x.shape x = np.ascontiguousarr...
def barh(d, plt, title=None): """A convenience function for plotting a horizontal bar plot from a Counter""" labels = sorted(d, key=d.get) index = range(len(labels)) plt.yticks(index, labels) plt.barh(index, [d[v] for v in labels]) if title is not None: plt.title(title)
A convenience function for plotting a horizontal bar plot from a Counter
Below is the the instruction that describes the task: ### Input: A convenience function for plotting a horizontal bar plot from a Counter ### Response: def barh(d, plt, title=None): """A convenience function for plotting a horizontal bar plot from a Counter""" labels = sorted(d, key=d.get) index = rang...
def tracking_event_post(node_id): """Enqueue a TrackingEvent worker for the specified Node. """ details = request_parameter(parameter="details", optional=True) if details: details = loads(details) # check the node exists node = models.Node.query.get(node_id) if node is None: ...
Enqueue a TrackingEvent worker for the specified Node.
Below is the the instruction that describes the task: ### Input: Enqueue a TrackingEvent worker for the specified Node. ### Response: def tracking_event_post(node_id): """Enqueue a TrackingEvent worker for the specified Node. """ details = request_parameter(parameter="details", optional=True) if de...
def _setup_incorporate(self): """Helper to setup incorporate functions :return (transcript sequence, cds start [1-based], cds stop [1-based], cds start index in seq [inc, 0-based], cds end index in seq [excl, 0-based]) :rtype (list, int, int, int, int) """ seq = list(self...
Helper to setup incorporate functions :return (transcript sequence, cds start [1-based], cds stop [1-based], cds start index in seq [inc, 0-based], cds end index in seq [excl, 0-based]) :rtype (list, int, int, int, int)
Below is the the instruction that describes the task: ### Input: Helper to setup incorporate functions :return (transcript sequence, cds start [1-based], cds stop [1-based], cds start index in seq [inc, 0-based], cds end index in seq [excl, 0-based]) :rtype (list, int, int, int, int) ### Res...
def dock(self, other): ''' Subtract another conc from this one. This is the opposite of concatenation. For example, if ABC + DEF = ABCDEF, then logically ABCDEF - DEF = ABC. ''' # e.g. self has mults at indices [0, 1, 2, 3, 4, 5, 6] len=7 # e.g. other has mults at indices [0, 1, 2] len=3 new = list(...
Subtract another conc from this one. This is the opposite of concatenation. For example, if ABC + DEF = ABCDEF, then logically ABCDEF - DEF = ABC.
Below is the the instruction that describes the task: ### Input: Subtract another conc from this one. This is the opposite of concatenation. For example, if ABC + DEF = ABCDEF, then logically ABCDEF - DEF = ABC. ### Response: def dock(self, other): ''' Subtract another conc from this one. This is the...
def get_entries(self, start=0, end=0, data_request=None, steam_ids=None): """Get leaderboard entries. :param start: start entry, not index (e.g. rank 1 is ``start=1``) :type start: :class:`int` :param end: end entry, not index (e.g. only one entry then ``start=1,end=1``) :type e...
Get leaderboard entries. :param start: start entry, not index (e.g. rank 1 is ``start=1``) :type start: :class:`int` :param end: end entry, not index (e.g. only one entry then ``start=1,end=1``) :type end: :class:`int` :param data_request: data being requested :type data...
Below is the the instruction that describes the task: ### Input: Get leaderboard entries. :param start: start entry, not index (e.g. rank 1 is ``start=1``) :type start: :class:`int` :param end: end entry, not index (e.g. only one entry then ``start=1,end=1``) :type end: :class:`int`...
def add_mandates(self, representative, rep_json): ''' Create mandates from rep data based on variant configuration ''' # Mandate in country group for party constituency if rep_json.get('parti_ratt_financier'): constituency, _ = Constituency.objects.get_or_create( ...
Create mandates from rep data based on variant configuration
Below is the the instruction that describes the task: ### Input: Create mandates from rep data based on variant configuration ### Response: def add_mandates(self, representative, rep_json): ''' Create mandates from rep data based on variant configuration ''' # Mandate in country gr...
def updated(bank, key, cachedir): ''' Return the epoch of the mtime for this cache file ''' key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(key_file): log.warning('Cache file "%s" does not exist', key_file) return None try: ...
Return the epoch of the mtime for this cache file
Below is the the instruction that describes the task: ### Input: Return the epoch of the mtime for this cache file ### Response: def updated(bank, key, cachedir): ''' Return the epoch of the mtime for this cache file ''' key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key))...
def upload(self, path, docs, **params): """ A convenience method for uploading a set of dictionaries representing documents. You still need to specify the URL to upload to, which will look like ROOT_URL/projects/myaccount/project_id/docs. """ json_data = json.dumps(list(d...
A convenience method for uploading a set of dictionaries representing documents. You still need to specify the URL to upload to, which will look like ROOT_URL/projects/myaccount/project_id/docs.
Below is the the instruction that describes the task: ### Input: A convenience method for uploading a set of dictionaries representing documents. You still need to specify the URL to upload to, which will look like ROOT_URL/projects/myaccount/project_id/docs. ### Response: def upload(self, path, do...
def generate_checks(fact): """Given a fact, generate a list of Check objects for checking it.""" yield TypeCheck(type(fact)) fact_captured = False for key, value in fact.items(): if (isinstance(key, str) and key.startswith('__') and key.endswith('__')): ...
Given a fact, generate a list of Check objects for checking it.
Below is the the instruction that describes the task: ### Input: Given a fact, generate a list of Check objects for checking it. ### Response: def generate_checks(fact): """Given a fact, generate a list of Check objects for checking it.""" yield TypeCheck(type(fact)) fact_captured = False for key...
def extract(text, default=UNKNOWN): """extracts calling convention from the text. If the calling convention could not be found, the "default"is used""" if not text: return default found = CALLING_CONVENTION_TYPES.pattern.match(text) if found: return found....
extracts calling convention from the text. If the calling convention could not be found, the "default"is used
Below is the the instruction that describes the task: ### Input: extracts calling convention from the text. If the calling convention could not be found, the "default"is used ### Response: def extract(text, default=UNKNOWN): """extracts calling convention from the text. If the calling convention ...
def create_decl_string( return_type, arguments_types, with_defaults=True): """ Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :clas...
Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t`
Below is the the instruction that describes the task: ### Input: Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t` ### Response:...
def nx_to_ontology(graph, source_node, output_path, base_iri): """Graph nodes are ID's, and have a 'label' in the node data with the right label :param graph: :param source_node: :param str output_path: :param base_iri: """ ontology = owlready.Ontology(base_iri) parent_lookup = { ...
Graph nodes are ID's, and have a 'label' in the node data with the right label :param graph: :param source_node: :param str output_path: :param base_iri:
Below is the the instruction that describes the task: ### Input: Graph nodes are ID's, and have a 'label' in the node data with the right label :param graph: :param source_node: :param str output_path: :param base_iri: ### Response: def nx_to_ontology(graph, source_node, output_path, base_iri): ...
def conjugate(self): """Complex conjugate of of the product""" return self.__class__.create( *[arg.conjugate() for arg in reversed(self.args)])
Complex conjugate of of the product
Below is the the instruction that describes the task: ### Input: Complex conjugate of of the product ### Response: def conjugate(self): """Complex conjugate of of the product""" return self.__class__.create( *[arg.conjugate() for arg in reversed(self.args)])
def make_publication_epub(binders, publisher, publication_message, file): """Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request. """ if not isinstance(binders, (list, set, tuple,)): binders = [binders] packages = [...
Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request.
Below is the the instruction that describes the task: ### Input: Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request. ### Response: def make_publication_epub(binders, publisher, publication_message, file): """Creates an epub file ...
def Copy(self, name=None): """Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist """ new = copy.copy(self) new.d = copy.copy(self.d) new.nam...
Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist
Below is the the instruction that describes the task: ### Input: Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist ### Response: def Copy(self, name=None): """Returns...
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None): """ Get multiple values from the cache, values not found are Nones. :param keys: list of str :param loads_fn: callable alternative to use as loads function :param namespace: str alternative namespace to ...
Get multiple values from the cache, values not found are Nones. :param keys: list of str :param loads_fn: callable alternative to use as loads function :param namespace: str alternative namespace to use :param timeout: int or float in seconds specifying maximum timeout for t...
Below is the the instruction that describes the task: ### Input: Get multiple values from the cache, values not found are Nones. :param keys: list of str :param loads_fn: callable alternative to use as loads function :param namespace: str alternative namespace to use :param timeout:...
def get_port_def(port_num, proto='tcp'): ''' Given a port number and protocol, returns the port definition expected by docker-py. For TCP ports this is simply an integer, for UDP ports this is (port_num, 'udp'). port_num can also be a string in the format 'port_num/udp'. If so, the "proto" argu...
Given a port number and protocol, returns the port definition expected by docker-py. For TCP ports this is simply an integer, for UDP ports this is (port_num, 'udp'). port_num can also be a string in the format 'port_num/udp'. If so, the "proto" argument will be ignored. The reason we need to be able t...
Below is the the instruction that describes the task: ### Input: Given a port number and protocol, returns the port definition expected by docker-py. For TCP ports this is simply an integer, for UDP ports this is (port_num, 'udp'). port_num can also be a string in the format 'port_num/udp'. If so, the ...
def filter_query(self, query, filter_info, model): """Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :return Query...
Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :return Query: the sorted query
Below is the the instruction that describes the task: ### Input: Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :retur...
def run(self, dag:DAGCircuit) -> DAGCircuit: """ Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit """ circ = dagcircuit_to_tk(dag, _DROP_CONDS=self.DROP_CONDS,_BO...
Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit
Below is the the instruction that describes the task: ### Input: Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit ### Response: def run(self, dag:DAGCircuit) -> DAGCircuit: """ ...
def login(self, username, password): """ Log in. AuthenticationFailedException exception is raised if authentication fails. """ url = get_url("/login.action", scheme="https") params = { 'username': username, 'password': password, 'submit-login...
Log in. AuthenticationFailedException exception is raised if authentication fails.
Below is the the instruction that describes the task: ### Input: Log in. AuthenticationFailedException exception is raised if authentication fails. ### Response: def login(self, username, password): """ Log in. AuthenticationFailedException exception is raised if authentication fails. ...
def parse(cls, request: web.Request) -> AuthWidgetData: """ Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest` """ try: query = dict(request.query) query['id...
Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest`
Below is the the instruction that describes the task: ### Input: Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest` ### Response: def parse(cls, request: web.Request) -> AuthWidgetData: """ Pa...
def create_node(self, *args, **kwargs): """ Creates a new IOU VM. :returns: IOUVM instance """ with (yield from self._iou_id_lock): # wait for a node to be completely created before adding a new one # this is important otherwise we allocate the same appl...
Creates a new IOU VM. :returns: IOUVM instance
Below is the the instruction that describes the task: ### Input: Creates a new IOU VM. :returns: IOUVM instance ### Response: def create_node(self, *args, **kwargs): """ Creates a new IOU VM. :returns: IOUVM instance """ with (yield from self._iou_id_lock): ...
def type_id(self): """ A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes th...
A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes the class id e.g. ``oauth2.Facebo...
Below is the the instruction that describes the task: ### Input: A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part ...
def p_optional_value(t): """optional_value : value | empty""" # return value or None. t[0] = t[1] # Note this must be unsigned value = t[0] if value is None or value[0].isdigit(): return msg = '' if value[0] == '-': msg = "Can't use negative index %s...
optional_value : value | empty
Below is the the instruction that describes the task: ### Input: optional_value : value | empty ### Response: def p_optional_value(t): """optional_value : value | empty""" # return value or None. t[0] = t[1] # Note this must be unsigned value = t[0] ...
def get_time_interval(start_time, end_time): """ 获取两个unix时间戳之间的时间间隔 :param: * start_time: (int) 开始时间,unix 时间戳 * end_time: (int) 结束时间,unix 时间戳 :return: * interval_dict: (dict) 时间间隔字典 举例如下:: print('--- get_time_interval demo ---') import time start = ...
获取两个unix时间戳之间的时间间隔 :param: * start_time: (int) 开始时间,unix 时间戳 * end_time: (int) 结束时间,unix 时间戳 :return: * interval_dict: (dict) 时间间隔字典 举例如下:: print('--- get_time_interval demo ---') import time start = int(time.time()) end = start - 98908 prin...
Below is the the instruction that describes the task: ### Input: 获取两个unix时间戳之间的时间间隔 :param: * start_time: (int) 开始时间,unix 时间戳 * end_time: (int) 结束时间,unix 时间戳 :return: * interval_dict: (dict) 时间间隔字典 举例如下:: print('--- get_time_interval demo ---') import time ...
def find_bounds(model): """ Return the median upper and lower bound of the metabolic model. Bounds can vary from model to model. Cobrapy defaults to (-1000, 1000) but this may not be the case for merged or autogenerated models. In these cases, this function is used to iterate over all the bounds of...
Return the median upper and lower bound of the metabolic model. Bounds can vary from model to model. Cobrapy defaults to (-1000, 1000) but this may not be the case for merged or autogenerated models. In these cases, this function is used to iterate over all the bounds of all the reactions and find the ...
Below is the the instruction that describes the task: ### Input: Return the median upper and lower bound of the metabolic model. Bounds can vary from model to model. Cobrapy defaults to (-1000, 1000) but this may not be the case for merged or autogenerated models. In these cases, this function is used ...
def insert(self, index, *grids): """Return a copy with ``grids`` inserted before ``index``. The given grids are inserted (as a block) into ``self``, yielding a new grid whose number of dimensions is the sum of the numbers of dimensions of all involved grids. Note that no changes...
Return a copy with ``grids`` inserted before ``index``. The given grids are inserted (as a block) into ``self``, yielding a new grid whose number of dimensions is the sum of the numbers of dimensions of all involved grids. Note that no changes are made in-place. Parameters ...
Below is the the instruction that describes the task: ### Input: Return a copy with ``grids`` inserted before ``index``. The given grids are inserted (as a block) into ``self``, yielding a new grid whose number of dimensions is the sum of the numbers of dimensions of all involved grids. ...
def next_url(request): """ Returns URL to redirect to from the ``next`` param in the request. """ next = request.GET.get("next", request.POST.get("next", "")) host = request.get_host() return next if next and is_safe_url(next, host=host) else None
Returns URL to redirect to from the ``next`` param in the request.
Below is the the instruction that describes the task: ### Input: Returns URL to redirect to from the ``next`` param in the request. ### Response: def next_url(request): """ Returns URL to redirect to from the ``next`` param in the request. """ next = request.GET.get("next", request.POST.get("next",...
def register_deliver_command(self, deliver_func): """ Add 'deliver' command for transferring a project to another user., :param deliver_func: function to run when user choses this option """ description = "Initiate delivery of a project to another user. Removes other user's curre...
Add 'deliver' command for transferring a project to another user., :param deliver_func: function to run when user choses this option
Below is the the instruction that describes the task: ### Input: Add 'deliver' command for transferring a project to another user., :param deliver_func: function to run when user choses this option ### Response: def register_deliver_command(self, deliver_func): """ Add 'deliver' command for...
def import_from(self, from_loc, module_name, import_loc, names): """ (2.6, 2.7) import_from: ('from' ('.'* dotted_name | '.'+) 'import' ('*' | '(' import_as_names ')' | import_as_names)) (3.0-) # note below: the ('.' | '...') is necessary because '...' is to...
(2.6, 2.7) import_from: ('from' ('.'* dotted_name | '.'+) 'import' ('*' | '(' import_as_names ')' | import_as_names)) (3.0-) # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS import_from: ('from' (('.' | '...')* dotted_name | ('.' |...
Below is the the instruction that describes the task: ### Input: (2.6, 2.7) import_from: ('from' ('.'* dotted_name | '.'+) 'import' ('*' | '(' import_as_names ')' | import_as_names)) (3.0-) # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIP...
def apply(self, s, active=None): """ Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :...
Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed ...
Below is the the instruction that describes the task: ### Input: Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns:...
def build_import_pattern(mapping1, mapping2): u""" mapping1: A dict mapping py3k modules to all possible py2k replacements mapping2: A dict mapping py2k modules to the things they do This builds a HUGE pattern to match all ways that things can be imported """ # py3k: urllib.request, py2k: ('urll...
u""" mapping1: A dict mapping py3k modules to all possible py2k replacements mapping2: A dict mapping py2k modules to the things they do This builds a HUGE pattern to match all ways that things can be imported
Below is the the instruction that describes the task: ### Input: u""" mapping1: A dict mapping py3k modules to all possible py2k replacements mapping2: A dict mapping py2k modules to the things they do This builds a HUGE pattern to match all ways that things can be imported ### Response: def build_impo...
def sg_get_context(): r"""Get current context information Returns: tf.sg_opt class object which contains all context information """ global _context # merge current context res = tf.sg_opt() for c in _context: res += c return res
r"""Get current context information Returns: tf.sg_opt class object which contains all context information
Below is the the instruction that describes the task: ### Input: r"""Get current context information Returns: tf.sg_opt class object which contains all context information ### Response: def sg_get_context(): r"""Get current context information Returns: tf.sg_opt class object which contain...
def classification_tikhonov(G, y, M, tau=0): r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math...
r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_X tr(X^T L X) \ \text{...
Below is the the instruction that describes the task: ### Input: r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > ...
def GetDWORD(self, buff, idx=0): '''Internal method. Reads a double word (4 bytes) from a buffer. ''' result = buff[idx] + (buff[idx+1] << 8) + (buff[idx+2] << 16) + \ (buff[idx+3] << 24) if result == 0xFFFFFFFF: result = 0 return result
Internal method. Reads a double word (4 bytes) from a buffer.
Below is the the instruction that describes the task: ### Input: Internal method. Reads a double word (4 bytes) from a buffer. ### Response: def GetDWORD(self, buff, idx=0): '''Internal method. Reads a double word (4 bytes) from a buffer. ''' result = buff[idx] + (buff[idx+1...
def project_list(self, limit=None): """ Provide the project list :param limit: OPTIONAL 25 is default :return: """ params = {} if limit: params['limit'] = limit return (self.get('rest/api/1.0/projects', params=params) or {}).get('values')
Provide the project list :param limit: OPTIONAL 25 is default :return:
Below is the the instruction that describes the task: ### Input: Provide the project list :param limit: OPTIONAL 25 is default :return: ### Response: def project_list(self, limit=None): """ Provide the project list :param limit: OPTIONAL 25 is default :return: ...
def save(url, destination): """ This is just the thread target. It's actually responsible for downloading and saving. :param str url: which dump to download :param str destination: a file path to save to """ r = requests.get(url, stream=True) with open(destination, 'wb') as fd: ...
This is just the thread target. It's actually responsible for downloading and saving. :param str url: which dump to download :param str destination: a file path to save to
Below is the the instruction that describes the task: ### Input: This is just the thread target. It's actually responsible for downloading and saving. :param str url: which dump to download :param str destination: a file path to save to ### Response: def save(url, destination): """ This is jus...
def unload_plug_in(self, name): """Unloads a DBGF plug-in. in name of type str The plug-in name or DLL. Special name 'all' unloads all plug-ins. """ if not isinstance(name, basestring): raise TypeError("name can only be an instance of type basestring") s...
Unloads a DBGF plug-in. in name of type str The plug-in name or DLL. Special name 'all' unloads all plug-ins.
Below is the the instruction that describes the task: ### Input: Unloads a DBGF plug-in. in name of type str The plug-in name or DLL. Special name 'all' unloads all plug-ins. ### Response: def unload_plug_in(self, name): """Unloads a DBGF plug-in. in name of type str ...
def get_image_output(self): """ Create the output for the image This is the Koji Content Generator metadata, along with the 'docker save' output to upload. :return: tuple, (metadata dict, Output instance) """ saved_image = self.workflow.exported_image_sequence...
Create the output for the image This is the Koji Content Generator metadata, along with the 'docker save' output to upload. :return: tuple, (metadata dict, Output instance)
Below is the the instruction that describes the task: ### Input: Create the output for the image This is the Koji Content Generator metadata, along with the 'docker save' output to upload. :return: tuple, (metadata dict, Output instance) ### Response: def get_image_output(self): "...
def evaluate(self, x): """TODO: will become _evaluate once polynomial filtering is merged.""" if not hasattr(self, '_coefficients'): # Graph Fourier transform -> modulation -> inverse GFT. c = self.G.igft(self._kernels.evaluate(self.G.e).squeeze()) c = np.sqrt(self.G...
TODO: will become _evaluate once polynomial filtering is merged.
Below is the the instruction that describes the task: ### Input: TODO: will become _evaluate once polynomial filtering is merged. ### Response: def evaluate(self, x): """TODO: will become _evaluate once polynomial filtering is merged.""" if not hasattr(self, '_coefficients'): # Graph F...
def size(self,*args): """ Set the size of the chart, args are width,height and can be tuple APIPARAM: chs """ if len(args) == 2: x,y = map(int,args) else: x,y = map(int,args[0]) self.check_size(x,y) self['chs'] = '%dx%d'%(x,y) ...
Set the size of the chart, args are width,height and can be tuple APIPARAM: chs
Below is the the instruction that describes the task: ### Input: Set the size of the chart, args are width,height and can be tuple APIPARAM: chs ### Response: def size(self,*args): """ Set the size of the chart, args are width,height and can be tuple APIPARAM: chs """ ...
def make_qadapter(**kwargs): """ Return the concrete :class:`QueueAdapter` class from a string. Note that one can register a customized version with: .. example:: from qadapters import SlurmAdapter class MyAdapter(SlurmAdapter): QTYPE = "myslurm" # Add your cus...
Return the concrete :class:`QueueAdapter` class from a string. Note that one can register a customized version with: .. example:: from qadapters import SlurmAdapter class MyAdapter(SlurmAdapter): QTYPE = "myslurm" # Add your customized code here # Register you...
Below is the the instruction that describes the task: ### Input: Return the concrete :class:`QueueAdapter` class from a string. Note that one can register a customized version with: .. example:: from qadapters import SlurmAdapter class MyAdapter(SlurmAdapter): QTYPE = "myslurm...
def _update_resource_view(self, log=False): # type: () -> bool """Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not """ update = False if 'id' in self.data and self._load_from_hdx('resource vi...
Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not
Below is the the instruction that describes the task: ### Input: Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not ### Response: def _update_resource_view(self, log=False): # type: () -> bool """Check if resourc...
def ParsePartitionsTable( self, parser_mediator, database=None, table=None, **unused_kwargs): """Parses the Partitions table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.fil...
Parses the Partitions table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Optional[pyesedb.table]): table. Raises: ValueError: if the data...
Below is the the instruction that describes the task: ### Input: Parses the Partitions table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Option...
def explode(self, contactgroups, notificationways): """Explode all contact for each contactsgroup :param contactgroups: contactgroups to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :param notificationways: notificationways to explode :type notificatio...
Explode all contact for each contactsgroup :param contactgroups: contactgroups to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :param notificationways: notificationways to explode :type notificationways: alignak.objects.notificationway.Notificationways ...
Below is the the instruction that describes the task: ### Input: Explode all contact for each contactsgroup :param contactgroups: contactgroups to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :param notificationways: notificationways to explode :type notif...
def _get_client_secret(client, service_id): """ Get client secret for service :param client: Accounts Service API Client :param service_id: Service ID :return: Client secret (if available) """ try: response = client.accounts.services[service_id].secrets.get() except httpclient.HT...
Get client secret for service :param client: Accounts Service API Client :param service_id: Service ID :return: Client secret (if available)
Below is the the instruction that describes the task: ### Input: Get client secret for service :param client: Accounts Service API Client :param service_id: Service ID :return: Client secret (if available) ### Response: def _get_client_secret(client, service_id): """ Get client secret for servi...
def __find_new(self, hueobjecttype): ''' Starts a search for new Hue objects ''' assert hueobjecttype in ['lights', 'sensors'], \ 'Unsupported object type {}'.format(hueobjecttype) url = '{}/{}'.format(self.API, hueobjecttype) return self._request( ...
Starts a search for new Hue objects
Below is the the instruction that describes the task: ### Input: Starts a search for new Hue objects ### Response: def __find_new(self, hueobjecttype): ''' Starts a search for new Hue objects ''' assert hueobjecttype in ['lights', 'sensors'], \ 'Unsupported object type {...
def base_show_parser(): """Creates a parser with arguments specific to formatting a single resource. Returns: {ArgumentParser}: Base parser with default show args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( '-k', '--key', type=str, ...
Creates a parser with arguments specific to formatting a single resource. Returns: {ArgumentParser}: Base parser with default show args
Below is the the instruction that describes the task: ### Input: Creates a parser with arguments specific to formatting a single resource. Returns: {ArgumentParser}: Base parser with default show args ### Response: def base_show_parser(): """Creates a parser with arguments specific to formatti...