code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def partial_regardless(self, fn, *a, **kw): """Like `partial`, but applies if callable is not annotated.""" if self.has_annotations(fn): return self.partial(fn, *a, **kw) else: return functools.partial(fn, *a, **kw)
Like `partial`, but applies if callable is not annotated.
Below is the the instruction that describes the task: ### Input: Like `partial`, but applies if callable is not annotated. ### Response: def partial_regardless(self, fn, *a, **kw): """Like `partial`, but applies if callable is not annotated.""" if self.has_annotations(fn): return self.p...
def location(self): """The location of the element in the renderable canvas.""" if self._w3c: old_loc = self._execute(Command.GET_ELEMENT_RECT)['value'] else: old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value'] new_loc = {"x": round(old_loc['x']), ...
The location of the element in the renderable canvas.
Below is the the instruction that describes the task: ### Input: The location of the element in the renderable canvas. ### Response: def location(self): """The location of the element in the renderable canvas.""" if self._w3c: old_loc = self._execute(Command.GET_ELEMENT_RECT)['value'] ...
def restrict_to_version(self, version): """Restricts the generated PDF file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been performed on the given...
Restricts the generated PDF file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to...
Below is the the instruction that describes the task: ### Input: Restricts the generated PDF file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been perf...
def add_command(self, cmd_name, *args): """Add command to action.""" self.__commands.append(Command(cmd_name, args))
Add command to action.
Below is the the instruction that describes the task: ### Input: Add command to action. ### Response: def add_command(self, cmd_name, *args): """Add command to action.""" self.__commands.append(Command(cmd_name, args))
def serialize(self, value): """See base class.""" return self.list_sep.join([_helpers.str_or_unicode(x) for x in value])
See base class.
Below is the the instruction that describes the task: ### Input: See base class. ### Response: def serialize(self, value): """See base class.""" return self.list_sep.join([_helpers.str_or_unicode(x) for x in value])
def union_rectangles(R): """Area of union of rectangles :param R: list of rectangles defined by (x1, y1, x2, y2) where (x1, y1) is top left corner and (x2, y2) bottom right corner :returns: area :complexity: :math:`O(n^2)` """ if R == []: return 0 X = [] Y = [] for j ...
Area of union of rectangles :param R: list of rectangles defined by (x1, y1, x2, y2) where (x1, y1) is top left corner and (x2, y2) bottom right corner :returns: area :complexity: :math:`O(n^2)`
Below is the the instruction that describes the task: ### Input: Area of union of rectangles :param R: list of rectangles defined by (x1, y1, x2, y2) where (x1, y1) is top left corner and (x2, y2) bottom right corner :returns: area :complexity: :math:`O(n^2)` ### Response: def union_rectangles(...
def get_views(self, mo_refs, properties=None): """Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve...
Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve in the views. :type properties: list :ret...
Below is the the instruction that describes the task: ### Input: Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties ...
def get_tag(note_store, my_tags): """ get the tags from his Evernote account :param note_store Evernote Instance :param my_tags string :return: array of the tag to create """ tag_id = [] listtags = note_store.listTags() # cut the st...
get the tags from his Evernote account :param note_store Evernote Instance :param my_tags string :return: array of the tag to create
Below is the the instruction that describes the task: ### Input: get the tags from his Evernote account :param note_store Evernote Instance :param my_tags string :return: array of the tag to create ### Response: def get_tag(note_store, my_tags): """ get the t...
def NOAC_metric(bpmn_graph): """ Returns the value of the NOAC metric (Number of Activities and control flow elements) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. """ activities_count = all_activities_count(bpmn_graph) cont...
Returns the value of the NOAC metric (Number of Activities and control flow elements) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
Below is the the instruction that describes the task: ### Input: Returns the value of the NOAC metric (Number of Activities and control flow elements) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. ### Response: def NOAC_metric(bpmn_graph): ...
def json_encoder_with_precision(precision, JSONEncoderClass): """ Context manager to set float precision during json encoding """ needs_class_hack = not hasattr(json.encoder, 'FLOAT_REPR') try: if precision is not None: def float_repr(o): return format(o, '.%sf' %...
Context manager to set float precision during json encoding
Below is the the instruction that describes the task: ### Input: Context manager to set float precision during json encoding ### Response: def json_encoder_with_precision(precision, JSONEncoderClass): """ Context manager to set float precision during json encoding """ needs_class_hack = not hasattr...
def synthesize_member(member_name, default = None, contract = None, read_only = False, getter_name = None, setter_name = None, private_member_name = None): """ When applied to a cl...
When applied to a class, this decorator adds getter/setter methods to it and overrides the constructor in order to set\ the default value of the member. By default, the getter will be named ``member_name``. (Ex.: ``member_name = 'member' => instance.member()``) By default, the setter will be named ``me...
Below is the the instruction that describes the task: ### Input: When applied to a class, this decorator adds getter/setter methods to it and overrides the constructor in order to set\ the default value of the member. By default, the getter will be named ``member_name``. (Ex.: ``member_name = 'member' => in...
def get_metric_data(self, metric_name=None, metric=None, days=None, hours=1, minutes=None, statistics=None, period=None): """ Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of ...
Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of hours. The maximum window is 14 days. Based on the time frame this method will calculate the correct ``period`` to return the maximum number of data points up to th...
Below is the the instruction that describes the task: ### Input: Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of hours. The maximum window is 14 days. Based on the time frame this method will calculate the correct ``...
def _SetAllFieldTypes(self, package, desc_proto, scope): """Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of av...
Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of available types.
Below is the the instruction that describes the task: ### Input: Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope ...
def is_stone_backend(cls, path): """ Returns True if the file name matches the format of a stone backend, ie. its inner extension of "stoneg". For example: xyz.stoneg.py """ path_without_ext, _ = os.path.splitext(path) _, second_ext = os.path.splitext(path_without_ext) ...
Returns True if the file name matches the format of a stone backend, ie. its inner extension of "stoneg". For example: xyz.stoneg.py
Below is the the instruction that describes the task: ### Input: Returns True if the file name matches the format of a stone backend, ie. its inner extension of "stoneg". For example: xyz.stoneg.py ### Response: def is_stone_backend(cls, path): """ Returns True if the file name matches the ...
def get_filename(self, index): """Return filename associated with *index*""" if index: return osp.normpath(to_text_string(self.fsmodel.filePath(index)))
Return filename associated with *index*
Below is the the instruction that describes the task: ### Input: Return filename associated with *index* ### Response: def get_filename(self, index): """Return filename associated with *index*""" if index: return osp.normpath(to_text_string(self.fsmodel.filePath(index)))
def _tar_and_copy(src_dir, target_dir): """Tar and gzip src_dir and copy to GCS target_dir.""" src_dir = src_dir.rstrip("/") target_dir = target_dir.rstrip("/") tmp_dir = tempfile.gettempdir().rstrip("/") src_base = os.path.basename(src_dir) shell_run( "tar --exclude=.git -zcf {tmp_dir}/{src_base}.tar...
Tar and gzip src_dir and copy to GCS target_dir.
Below is the the instruction that describes the task: ### Input: Tar and gzip src_dir and copy to GCS target_dir. ### Response: def _tar_and_copy(src_dir, target_dir): """Tar and gzip src_dir and copy to GCS target_dir.""" src_dir = src_dir.rstrip("/") target_dir = target_dir.rstrip("/") tmp_dir = tempfile...
def add(self): '''Save an object to Instapaper after instantiating it. Example:: folder = Folder(instapaper, title='stuff') result = folder.add() ''' # TODO validation per object type submit_attribs = {} for attrib in self.ATTRIBUTES: ...
Save an object to Instapaper after instantiating it. Example:: folder = Folder(instapaper, title='stuff') result = folder.add()
Below is the the instruction that describes the task: ### Input: Save an object to Instapaper after instantiating it. Example:: folder = Folder(instapaper, title='stuff') result = folder.add() ### Response: def add(self): '''Save an object to Instapaper after instantiating...
def transform(self, X): """Apply dimensionality reduction on X. X is projected on the first principal components previous extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples in the numb...
Apply dimensionality reduction on X. X is projected on the first principal components previous extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_fea...
Below is the the instruction that describes the task: ### Input: Apply dimensionality reduction on X. X is projected on the first principal components previous extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New...
def update(self, **kwargs): """Due to a password decryption bug we will disable update() method for 12.1.0 and up """ tmos_version = self._meta_data['bigip'].tmos_version if LooseVersion(tmos_version) > LooseVersion('12.0.0'): msg = "Update() is unsupported for User...
Due to a password decryption bug we will disable update() method for 12.1.0 and up
Below is the the instruction that describes the task: ### Input: Due to a password decryption bug we will disable update() method for 12.1.0 and up ### Response: def update(self, **kwargs): """Due to a password decryption bug we will disable update() method for 12.1.0 and up """ ...
def _get_file(self, config): """ Read a per-user .ini file, which is expected to have either a ``[scraperkit]`` or a ``[$SCRAPER_NAME]`` section. """ config_file = SafeConfigParser() config_file.read([os.path.expanduser('~/.scrapekit.ini')]) if config_file.has_section('scrapekit'...
Read a per-user .ini file, which is expected to have either a ``[scraperkit]`` or a ``[$SCRAPER_NAME]`` section.
Below is the the instruction that describes the task: ### Input: Read a per-user .ini file, which is expected to have either a ``[scraperkit]`` or a ``[$SCRAPER_NAME]`` section. ### Response: def _get_file(self, config): """ Read a per-user .ini file, which is expected to have either a ``[s...
def exists(self, relpath, rsc=None, useFilepath=None): """ Checks to see if the inputed path represents an existing file or directory. :param relpath | <str> rsc | <str> useFilepath | <bool> or None """ path = self...
Checks to see if the inputed path represents an existing file or directory. :param relpath | <str> rsc | <str> useFilepath | <bool> or None
Below is the the instruction that describes the task: ### Input: Checks to see if the inputed path represents an existing file or directory. :param relpath | <str> rsc | <str> useFilepath | <bool> or None ### Response: def exists(self, relpath, ...
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the ...
Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code.
Below is the the instruction that describes the task: ### Input: Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. ### Response: def handshake(self, server_hostname, verify, trust_bun...
def _get_core_transform(self, resolution): """The projection for the stereonet as a matplotlib transform. This is primarily called by LambertAxes._set_lim_and_transforms.""" return self._base_transform(self._center_longitude, self._center_latitude, ...
The projection for the stereonet as a matplotlib transform. This is primarily called by LambertAxes._set_lim_and_transforms.
Below is the the instruction that describes the task: ### Input: The projection for the stereonet as a matplotlib transform. This is primarily called by LambertAxes._set_lim_and_transforms. ### Response: def _get_core_transform(self, resolution): """The projection for the stereonet as a matplotlib ...
def run_once(name, cmd, env, shutdown, loop=None, utc=False): """Starts a child process and waits for its completion. .. note:: This function is a coroutine. Standard output and error streams are captured and forwarded to the parent process' standard output. Each line is prefixed with the current tim...
Starts a child process and waits for its completion. .. note:: This function is a coroutine. Standard output and error streams are captured and forwarded to the parent process' standard output. Each line is prefixed with the current time (as measured by the parent process) and the child process ``nam...
Below is the the instruction that describes the task: ### Input: Starts a child process and waits for its completion. .. note:: This function is a coroutine. Standard output and error streams are captured and forwarded to the parent process' standard output. Each line is prefixed with the current tim...
def alias_repository(self, repository_id=None, alias_id=None): """Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a poi...
Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another repository, it is reassigned to the given reposito...
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer ...
def error_lineno(self): """Get the line number with which to report violations.""" if isinstance(self.docstring, Docstring): return self.docstring.start return self.start
Get the line number with which to report violations.
Below is the the instruction that describes the task: ### Input: Get the line number with which to report violations. ### Response: def error_lineno(self): """Get the line number with which to report violations.""" if isinstance(self.docstring, Docstring): return self.docstring.start ...
def visitShapeOrRef(self, ctx: ShExDocParser.ShapeOrRefContext): """ shapeOrRef: shapeDefinition | shapeRef """ if ctx.shapeDefinition(): from pyshexc.parser_impl.shex_shape_definition_parser import ShexShapeDefinitionParser shdef_parser = ShexShapeDefinitionParser(self.context, ...
shapeOrRef: shapeDefinition | shapeRef
Below is the the instruction that describes the task: ### Input: shapeOrRef: shapeDefinition | shapeRef ### Response: def visitShapeOrRef(self, ctx: ShExDocParser.ShapeOrRefContext): """ shapeOrRef: shapeDefinition | shapeRef """ if ctx.shapeDefinition(): from pyshexc.parser_impl.shex_s...
def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread.start()
Spawns new NSThread to handle notifications.
Below is the the instruction that describes the task: ### Input: Spawns new NSThread to handle notifications. ### Response: def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarge...
def health_check(self): """Uses head object to make sure the file exists in S3.""" logger.debug('Health Check on S3 file for: {namespace}'.format( namespace=self.namespace )) try: self.client.head_object(Bucket=self.bucket_name, Key=self.data_file) re...
Uses head object to make sure the file exists in S3.
Below is the the instruction that describes the task: ### Input: Uses head object to make sure the file exists in S3. ### Response: def health_check(self): """Uses head object to make sure the file exists in S3.""" logger.debug('Health Check on S3 file for: {namespace}'.format( namespac...
def format_report(cls, instance, trcback, context=1): """ Formats a report using given exception. :param cls: Exception class. :type cls: object :param instance: Exception instance. :type instance: object :param trcback: Traceback. :type trcback: Traceback :param context: Context be...
Formats a report using given exception. :param cls: Exception class. :type cls: object :param instance: Exception instance. :type instance: object :param trcback: Traceback. :type trcback: Traceback :param context: Context being included. :type context: int :return: Formated report....
Below is the the instruction that describes the task: ### Input: Formats a report using given exception. :param cls: Exception class. :type cls: object :param instance: Exception instance. :type instance: object :param trcback: Traceback. :type trcback: Traceback :param context: Context...
def _generate_route_signature( self, route, namespace, # pylint: disable=unused-argument route_args, extra_args, doc_list, task_type_name, func_suffix): """Generates route method signature for the given route.""" ...
Generates route method signature for the given route.
Below is the the instruction that describes the task: ### Input: Generates route method signature for the given route. ### Response: def _generate_route_signature( self, route, namespace, # pylint: disable=unused-argument route_args, extra_args, ...
def f_remove(self, recursive=True, predicate=None): """Recursively removes all children of the trajectory :param recursive: Only here for consistency with signature of parent method. Cannot be set to `False` because the trajectory root node cannot be removed. :param pr...
Recursively removes all children of the trajectory :param recursive: Only here for consistency with signature of parent method. Cannot be set to `False` because the trajectory root node cannot be removed. :param predicate: Predicate which can evaluate for each nod...
Below is the the instruction that describes the task: ### Input: Recursively removes all children of the trajectory :param recursive: Only here for consistency with signature of parent method. Cannot be set to `False` because the trajectory root node cannot be removed. :pa...
def string_to_integer(value, strict=False): """ Return an integer corresponding to the string representation of a number. @param value: a string representation of an integer number. @param strict: indicate whether the specified string MUST be of a valid integer number representation. ...
Return an integer corresponding to the string representation of a number. @param value: a string representation of an integer number. @param strict: indicate whether the specified string MUST be of a valid integer number representation. @return: the integer value represented by the string. ...
Below is the the instruction that describes the task: ### Input: Return an integer corresponding to the string representation of a number. @param value: a string representation of an integer number. @param strict: indicate whether the specified string MUST be of a valid integer number represe...
def request(schema): """ Decorate a function with a request schema. """ def wrapper(func): setattr(func, REQUEST, schema) return func return wrapper
Decorate a function with a request schema.
Below is the the instruction that describes the task: ### Input: Decorate a function with a request schema. ### Response: def request(schema): """ Decorate a function with a request schema. """ def wrapper(func): setattr(func, REQUEST, schema) return func return wrapper
def list_properties(cls): """ returns a dictionary of properties assigned to the class""" rtn_dict = {} for attr in dir(cls): if attr not in ["properties", "__doc__", "doc"]: attr_val = getattr(cls, attr) if isinstance(attr_val, MODULE.rdfclass.RdfPropertyMeta): ...
returns a dictionary of properties assigned to the class
Below is the the instruction that describes the task: ### Input: returns a dictionary of properties assigned to the class ### Response: def list_properties(cls): """ returns a dictionary of properties assigned to the class""" rtn_dict = {} for attr in dir(cls): if attr not in ["properties", "__...
def train(self, word_s): """更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None """ for word in word_s: # 把词语的每个前缀更新到 prefix_set 中 for index in range(len(word)): self._set.add(word[:index + 1])
更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None
Below is the the instruction that describes the task: ### Input: 更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None ### Response: def train(self, word_s): """更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None ...
def _write_regpol_data(data_to_write, policy_file_path, gpt_ini_path, gpt_extension, gpt_extension_guid): ''' helper function to actually write the data to a Registry.pol file also updates/edits the gpt.ini file to ...
helper function to actually write the data to a Registry.pol file also updates/edits the gpt.ini file to include the ADM policy extensions to let the computer know user and/or machine registry policy files need to be processed data_to_write: data to write into the user/machine registry.pol file po...
Below is the the instruction that describes the task: ### Input: helper function to actually write the data to a Registry.pol file also updates/edits the gpt.ini file to include the ADM policy extensions to let the computer know user and/or machine registry policy files need to be processed data_t...
def output(self, name: str, value: Any): """ Export a stack output with a given name and value. """ self.outputs[name] = value
Export a stack output with a given name and value.
Below is the the instruction that describes the task: ### Input: Export a stack output with a given name and value. ### Response: def output(self, name: str, value: Any): """ Export a stack output with a given name and value. """ self.outputs[name] = value
def get_item_price_id(core, prices): """get item price id""" price_id = None for price in prices: if not price['locationGroupId']: capacity_min = int(price.get('capacityRestrictionMinimum', -1)) capacity_max = int(price.get('capacityRestrictionMaximum'...
get item price id
Below is the the instruction that describes the task: ### Input: get item price id ### Response: def get_item_price_id(core, prices): """get item price id""" price_id = None for price in prices: if not price['locationGroupId']: capacity_min = int(price.get('capac...
def as_list(self, decode=False): """ Return a list of items in the array. """ return [_decode(i) for i in self] if decode else list(self)
Return a list of items in the array.
Below is the the instruction that describes the task: ### Input: Return a list of items in the array. ### Response: def as_list(self, decode=False): """ Return a list of items in the array. """ return [_decode(i) for i in self] if decode else list(self)
def _writeOptionalXsecCards(self, fileObject, xSec, replaceParamFile): """ Write Optional Cross Section Cards to File Method """ if xSec.erode: fileObject.write('ERODE\n') if xSec.maxErosion != None: fileObject.write('MAX_EROSION %.6f\n' % xSec.maxEros...
Write Optional Cross Section Cards to File Method
Below is the the instruction that describes the task: ### Input: Write Optional Cross Section Cards to File Method ### Response: def _writeOptionalXsecCards(self, fileObject, xSec, replaceParamFile): """ Write Optional Cross Section Cards to File Method """ if xSec.erode: ...
def get_model_for_value(cls, value): """ Iterates through setting value subclasses, returning one that is compatible with the type of ``value``. Calls ``is_compatible()`` on each subclass. """ for related_object in get_all_related_objects(cls._meta): model = g...
Iterates through setting value subclasses, returning one that is compatible with the type of ``value``. Calls ``is_compatible()`` on each subclass.
Below is the the instruction that describes the task: ### Input: Iterates through setting value subclasses, returning one that is compatible with the type of ``value``. Calls ``is_compatible()`` on each subclass. ### Response: def get_model_for_value(cls, value): """ Iterates throug...
def mean(array, axis=None, skipna=None, **kwargs): """inhouse mean that can handle np.datetime64 or cftime.datetime dtypes""" from .common import _contains_cftime_datetimes array = asarray(array) if array.dtype.kind in 'Mm': offset = min(array) # xarray always uses np.datetime64[ns]...
inhouse mean that can handle np.datetime64 or cftime.datetime dtypes
Below is the the instruction that describes the task: ### Input: inhouse mean that can handle np.datetime64 or cftime.datetime dtypes ### Response: def mean(array, axis=None, skipna=None, **kwargs): """inhouse mean that can handle np.datetime64 or cftime.datetime dtypes""" from .common import _cont...
def connection_from_list_slice(list_slice, args=None, connection_type=None, edge_type=None, pageinfo_type=None, slice_start=0, list_length=0, list_slice_length=None): ''' Given a slice (subset) of an array, returns a connection object for use in ...
Given a slice (subset) of an array, returns a connection object for use in GraphQL. This function is similar to `connectionFromArray`, but is intended for use cases where you know the cardinality of the connection, consider it too large to materialize the entire array, and instead wish pass in a slice o...
Below is the the instruction that describes the task: ### Input: Given a slice (subset) of an array, returns a connection object for use in GraphQL. This function is similar to `connectionFromArray`, but is intended for use cases where you know the cardinality of the connection, consider it too large ...
def validate(self, command, token, team_id, method): """Validate request queries with registerd commands :param command: command parameter from request :param token: token parameter from request :param team_id: team_id parameter from request :param method: the request method ...
Validate request queries with registerd commands :param command: command parameter from request :param token: token parameter from request :param team_id: team_id parameter from request :param method: the request method
Below is the the instruction that describes the task: ### Input: Validate request queries with registerd commands :param command: command parameter from request :param token: token parameter from request :param team_id: team_id parameter from request :param method: the request metho...
def train(self, *args, **kwargs): """Train the classifier with a labeled and unlabeled feature sets and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling ``classify`` or ``accuracy`` methods and is included only to al...
Train the classifier with a labeled and unlabeled feature sets and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling ``classify`` or ``accuracy`` methods and is included only to allow passing in arguments to the ``tra...
Below is the the instruction that describes the task: ### Input: Train the classifier with a labeled and unlabeled feature sets and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling ``classify`` or ``accuracy`` methods an...
def ac3(space): """ AC-3 algorithm. This reduces the domains of the variables by propagating constraints to ensure arc consistency. :param Space space: The space to reduce """ #determine arcs arcs = {} for name in space.variables: arcs[name] = set([]) for const in space.cons...
AC-3 algorithm. This reduces the domains of the variables by propagating constraints to ensure arc consistency. :param Space space: The space to reduce
Below is the the instruction that describes the task: ### Input: AC-3 algorithm. This reduces the domains of the variables by propagating constraints to ensure arc consistency. :param Space space: The space to reduce ### Response: def ac3(space): """ AC-3 algorithm. This reduces the domains of the...
def pickFilepath( self ): """ Prompts the user to select a filepath from the system based on the \ current filepath mode. """ mode = self.filepathMode() filepath = '' filepaths = [] curr_dir = nativestring(self._filepathEdit.text()) if (...
Prompts the user to select a filepath from the system based on the \ current filepath mode.
Below is the the instruction that describes the task: ### Input: Prompts the user to select a filepath from the system based on the \ current filepath mode. ### Response: def pickFilepath( self ): """ Prompts the user to select a filepath from the system based on the \ current filep...
def lognoiserate(self, trigs): """ Calculate the log noise rate density over single-ifo newsnr Read in single trigger information, make the newsnr statistic and rescale by the fitted coefficients alpha and rate """ alphai, ratei, thresh = self.find_fits(trigs) ne...
Calculate the log noise rate density over single-ifo newsnr Read in single trigger information, make the newsnr statistic and rescale by the fitted coefficients alpha and rate
Below is the the instruction that describes the task: ### Input: Calculate the log noise rate density over single-ifo newsnr Read in single trigger information, make the newsnr statistic and rescale by the fitted coefficients alpha and rate ### Response: def lognoiserate(self, trigs): """ ...
def get_frip(self, sample): """ Calculates the fraction of reads in peaks for a given sample. :param pipelines.Sample sample: Sample object with "peaks" attribute. """ import pandas as pd with open(sample.frip, "r") as handle: content = handle.readlines() ...
Calculates the fraction of reads in peaks for a given sample. :param pipelines.Sample sample: Sample object with "peaks" attribute.
Below is the the instruction that describes the task: ### Input: Calculates the fraction of reads in peaks for a given sample. :param pipelines.Sample sample: Sample object with "peaks" attribute. ### Response: def get_frip(self, sample): """ Calculates the fraction of reads in peaks for a...
def restart(self): """ Tells the HAProxy control object to restart the process. If it's been fewer than `restart_interval` seconds since the previous restart, it will wait until the interval has passed. This staves off situations where the process is constantly restarting, as i...
Tells the HAProxy control object to restart the process. If it's been fewer than `restart_interval` seconds since the previous restart, it will wait until the interval has passed. This staves off situations where the process is constantly restarting, as it is possible to drop packets f...
Below is the the instruction that describes the task: ### Input: Tells the HAProxy control object to restart the process. If it's been fewer than `restart_interval` seconds since the previous restart, it will wait until the interval has passed. This staves off situations where the process ...
def html(self): """ str: HTML representation of the page Note: Not settable Warning: This can be slow for very large pages """ if self._html is False: self._html = None query_params = { "prop": "revisions", ...
str: HTML representation of the page Note: Not settable Warning: This can be slow for very large pages
Below is the the instruction that describes the task: ### Input: str: HTML representation of the page Note: Not settable Warning: This can be slow for very large pages ### Response: def html(self): """ str: HTML representation of the page ...
def remove_outdated(self, after, when=0): """ Remove keys that should not be available any more. Outdated means that the key was marked as inactive at a time that was longer ago then what is given in 'after'. :param after: The length of time the key will remain in the KeyBundle ...
Remove keys that should not be available any more. Outdated means that the key was marked as inactive at a time that was longer ago then what is given in 'after'. :param after: The length of time the key will remain in the KeyBundle before it should be removed. :param when: ...
Below is the the instruction that describes the task: ### Input: Remove keys that should not be available any more. Outdated means that the key was marked as inactive at a time that was longer ago then what is given in 'after'. :param after: The length of time the key will remain in the Key...
def user_parse(data): """Parse information from provider.""" for email in data.get('emails', []): if email.get('primary'): yield 'id', email.get('email') yield 'email', email.get('email') break
Parse information from provider.
Below is the the instruction that describes the task: ### Input: Parse information from provider. ### Response: def user_parse(data): """Parse information from provider.""" for email in data.get('emails', []): if email.get('primary'): yield 'id', email.get('email') ...
def set_row(self, index, values): """ Sets the values of the columns in a single row. :param index: index value :param values: dict with the keys as the column names and the values what to set that column to :return: nothing """ if self._sort: exists,...
Sets the values of the columns in a single row. :param index: index value :param values: dict with the keys as the column names and the values what to set that column to :return: nothing
Below is the the instruction that describes the task: ### Input: Sets the values of the columns in a single row. :param index: index value :param values: dict with the keys as the column names and the values what to set that column to :return: nothing ### Response: def set_row(self, index,...
def _register_servicer(self, servicer): """register serviser :param servicer: servicer """ name = servicer.__name__ if name in self._servicers: raise exceptions.ConfigException( 'servicer duplicated: {}'.format(name)) add_func = self._get_serv...
register serviser :param servicer: servicer
Below is the the instruction that describes the task: ### Input: register serviser :param servicer: servicer ### Response: def _register_servicer(self, servicer): """register serviser :param servicer: servicer """ name = servicer.__name__ if name in self._servicers...
def glue(self, pos): """Calculates the distance between the given position and the port :param (float, float) pos: Distance to this position is calculated :return: Distance to port :rtype: float """ # Distance between border of rectangle and point # Equation from...
Calculates the distance between the given position and the port :param (float, float) pos: Distance to this position is calculated :return: Distance to port :rtype: float
Below is the the instruction that describes the task: ### Input: Calculates the distance between the given position and the port :param (float, float) pos: Distance to this position is calculated :return: Distance to port :rtype: float ### Response: def glue(self, pos): """Calculat...
def load_match_config(self, match_config: MatchConfig, bot_config_overrides={}): """ Loads the match config into internal data structures, which prepares us to later launch bot processes and start the match. This is an alternative to the load_config method; they accomplish the same thin...
Loads the match config into internal data structures, which prepares us to later launch bot processes and start the match. This is an alternative to the load_config method; they accomplish the same thing.
Below is the the instruction that describes the task: ### Input: Loads the match config into internal data structures, which prepares us to later launch bot processes and start the match. This is an alternative to the load_config method; they accomplish the same thing. ### Response: def load_match...
def _lsm_load_pages(self): """Load and fix all pages from LSM file.""" # cache all pages to preserve corrected values pages = self.pages pages.cache = True pages.useframes = True # use first and second page as keyframes pages.keyframe = 1 pages.keyframe = ...
Load and fix all pages from LSM file.
Below is the the instruction that describes the task: ### Input: Load and fix all pages from LSM file. ### Response: def _lsm_load_pages(self): """Load and fix all pages from LSM file.""" # cache all pages to preserve corrected values pages = self.pages pages.cache = True pa...
def _show_stat(self): """ convenient functions to call the static show_stat_wrapper_multi with the given class members """ _show_stat_wrapper_multi_Progress(self.count, self.last_count, s...
convenient functions to call the static show_stat_wrapper_multi with the given class members
Below is the the instruction that describes the task: ### Input: convenient functions to call the static show_stat_wrapper_multi with the given class members ### Response: def _show_stat(self): """ convenient functions to call the static show_stat_wrapper_multi with the ...
def addDataFrameColumn(self, columnName, dtype=str, defaultValue=None): """ Adds a column to the dataframe as long as the model's editable property is set to True and the dtype is supported. :param columnName: str name of the column. :param dtype: qtpandas.mo...
Adds a column to the dataframe as long as the model's editable property is set to True and the dtype is supported. :param columnName: str name of the column. :param dtype: qtpandas.models.SupportedDtypes option :param defaultValue: (object) to default the...
Below is the the instruction that describes the task: ### Input: Adds a column to the dataframe as long as the model's editable property is set to True and the dtype is supported. :param columnName: str name of the column. :param dtype: qtpandas.models.SupportedDtypes op...
def curve_points(self, beginframe, endframe, framestep, birthframe, startframe, stopframe, deathframe, filternone=True, noiseframe=None): """ returns a list of frames from startframe to stopframe, in steps of framestepj warning: the list of points may include "None" elements...
returns a list of frames from startframe to stopframe, in steps of framestepj warning: the list of points may include "None" elements :param beginframe: first frame to include in list of points :param endframe: last frame to include in list of points :param framestep: framestep ...
Below is the the instruction that describes the task: ### Input: returns a list of frames from startframe to stopframe, in steps of framestepj warning: the list of points may include "None" elements :param beginframe: first frame to include in list of points :param endframe: last frame to i...
def dictionary(value): """ :param value: input string corresponding to a literal Python object :returns: the Python object >>> dictionary('') {} >>> dictionary('{}') {} >>> dictionary('{"a": 1}') {'a': 1} >>> dictionary('"vs30_clustering: true"') # an error real...
:param value: input string corresponding to a literal Python object :returns: the Python object >>> dictionary('') {} >>> dictionary('{}') {} >>> dictionary('{"a": 1}') {'a': 1} >>> dictionary('"vs30_clustering: true"') # an error really done by a user Traceback (mo...
Below is the the instruction that describes the task: ### Input: :param value: input string corresponding to a literal Python object :returns: the Python object >>> dictionary('') {} >>> dictionary('{}') {} >>> dictionary('{"a": 1}') {'a': 1} >>> dictionary('"vs30_cl...
def set_window_size_callback(window, cbfun): """ Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes...
Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);
Below is the the instruction that describes the task: ### Input: Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); ### Response: def set_window_size_callback(window, cbfun): """ Sets the size ...
def run(path, timer=False, repeat=3, number=10000, precision=2): """ Extracts and runs the '@cyther' code from the given file 'path' name """ code = extractAtCyther(path) if not code: output = "There was no '@cyther' code collected from the " \ "file '{}'\n".format(path) ...
Extracts and runs the '@cyther' code from the given file 'path' name
Below is the the instruction that describes the task: ### Input: Extracts and runs the '@cyther' code from the given file 'path' name ### Response: def run(path, timer=False, repeat=3, number=10000, precision=2): """ Extracts and runs the '@cyther' code from the given file 'path' name """ code = ex...
def lookup_jid(jid, ext_source=None, returned=True, missing=False, display_progress=False): ''' Return the printout from a previously executed job jid The jid to look up. ext_source The external job cache to use. Default: `Non...
Return the printout from a previously executed job jid The jid to look up. ext_source The external job cache to use. Default: `None`. returned : True If ``True``, include the minions that did return from the command. .. versionadded:: 2015.8.0 missing : False ...
Below is the the instruction that describes the task: ### Input: Return the printout from a previously executed job jid The jid to look up. ext_source The external job cache to use. Default: `None`. returned : True If ``True``, include the minions that did return from the comm...
def call(self, name, *args, **kwargs): """ Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now. """ # Like txkoji.Connection, we always want the full request f...
Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now.
Below is the the instruction that describes the task: ### Input: Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now. ### Response: def call(self, name, *args, **kwargs): """ ...
def check_shutdown_flag(self): """Shutdown the server if the flag has been set""" if self.shutdown_requested: tornado.ioloop.IOLoop.instance().stop() print("web server stopped.")
Shutdown the server if the flag has been set
Below is the the instruction that describes the task: ### Input: Shutdown the server if the flag has been set ### Response: def check_shutdown_flag(self): """Shutdown the server if the flag has been set""" if self.shutdown_requested: tornado.ioloop.IOLoop.instance().stop() p...
def next(self, n=1): """Move up by `n` steps in the Hilbert space:: >>> hs = LocalSpace('tls', basis=('g', 'e')) >>> ascii(BasisKet('g', hs=hs).next()) '|e>^(tls)' >>> ascii(BasisKet(0, hs=hs).next()) '|e>^(tls)' We can also go multiple step...
Move up by `n` steps in the Hilbert space:: >>> hs = LocalSpace('tls', basis=('g', 'e')) >>> ascii(BasisKet('g', hs=hs).next()) '|e>^(tls)' >>> ascii(BasisKet(0, hs=hs).next()) '|e>^(tls)' We can also go multiple steps: >>> hs = LocalS...
Below is the the instruction that describes the task: ### Input: Move up by `n` steps in the Hilbert space:: >>> hs = LocalSpace('tls', basis=('g', 'e')) >>> ascii(BasisKet('g', hs=hs).next()) '|e>^(tls)' >>> ascii(BasisKet(0, hs=hs).next()) '|e>^(tls)' ...
def _cicled(self, s1, s2): """ source: https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py#L18 """ rows = len(s1) + 1 cols = len(s2) + 1 prev = None if numpy: cur = numpy.arange(cols) else: cur = range...
source: https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py#L18
Below is the the instruction that describes the task: ### Input: source: https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py#L18 ### Response: def _cicled(self, s1, s2): """ source: https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py#L18...
def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name self.dct = ch_dct if ch_dct['type'] == 'analog': fmter = fmt.green else: fmter = fmt.blue sel...
Parent widget calls this whenever the user edits channel info.
Below is the the instruction that describes the task: ### Input: Parent widget calls this whenever the user edits channel info. ### Response: def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name ...
def kind(units): """Find the kind of given units. Parameters ---------- units : string The units of interest Returns ------- string The kind of the given units. If no match is found, returns None. """ for k, v in dicts.items(): if units in v.keys(): ...
Find the kind of given units. Parameters ---------- units : string The units of interest Returns ------- string The kind of the given units. If no match is found, returns None.
Below is the the instruction that describes the task: ### Input: Find the kind of given units. Parameters ---------- units : string The units of interest Returns ------- string The kind of the given units. If no match is found, returns None. ### Response: def kind(units): ...
def put_job(self, fun, *args, **kwargs): """ put job if possible, non-blocking :param fun: :param args: :param kwargs: :return: """ if not args and not kwargs and isinstance(fun, (tuple, list)): # ex) q.put_job([fun, args, kwargs]) ...
put job if possible, non-blocking :param fun: :param args: :param kwargs: :return:
Below is the the instruction that describes the task: ### Input: put job if possible, non-blocking :param fun: :param args: :param kwargs: :return: ### Response: def put_job(self, fun, *args, **kwargs): """ put job if possible, non-blocking :param fun: ...
def get_connection(self): """ Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance. """ if self.sniffer_timeout: if time.time() >= self.last_sniff + self.sniffer_timeout: self.sniff_hosts() ...
Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance.
Below is the the instruction that describes the task: ### Input: Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance. ### Response: def get_connection(self): """ Retreive a :class:`~elasticsearch.Connection` instance from the ...
def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be ...
Compute Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the sample rate of the signal we are working with, in Hz. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25...
Below is the the instruction that describes the task: ### Input: Compute Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the sample rate of the signal we are working with, in Hz. :param winlen...
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title): """ Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The ti...
Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the plot :return: The modified axis object. :rtype: AxesSubplot
Below is the the instruction that describes the task: ### Input: Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the...
def run(self, name, config, builder): """Builds the topology and submits it""" if not isinstance(name, str): raise RuntimeError("Name has to be a string type") if not isinstance(config, Config): raise RuntimeError("config has to be a Config type") if not isinstance(builder, Builder): r...
Builds the topology and submits it
Below is the the instruction that describes the task: ### Input: Builds the topology and submits it ### Response: def run(self, name, config, builder): """Builds the topology and submits it""" if not isinstance(name, str): raise RuntimeError("Name has to be a string type") if not isinstance(confi...
def nmap_fp(target, oport=80, cport=81): """nmap fingerprinting nmap_fp(target, [oport=80,] [cport=81,]) -> list of best guesses with accuracy """ sigs = nmap_sig(target, oport, cport) return nmap_search(sigs)
nmap fingerprinting nmap_fp(target, [oport=80,] [cport=81,]) -> list of best guesses with accuracy
Below is the the instruction that describes the task: ### Input: nmap fingerprinting nmap_fp(target, [oport=80,] [cport=81,]) -> list of best guesses with accuracy ### Response: def nmap_fp(target, oport=80, cport=81): """nmap fingerprinting nmap_fp(target, [oport=80,] [cport=81,]) -> list of best guesses with...
def delete_account_api_key(self, account_id, api_key, **kwargs): # noqa: E501 """Delete the API key. # noqa: E501 An endpoint for deleting an API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apikey} -H 'Authorization: Bearer API_KEY'`...
Delete the API key. # noqa: E501 An endpoint for deleting an API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apikey} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HTTP request by default. To make an...
Below is the the instruction that describes the task: ### Input: Delete the API key. # noqa: E501 An endpoint for deleting an API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apikey} -H 'Authorization: Bearer API_KEY'` # noqa: E501 ...
def manual_setpoint_encode(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch): ''' Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) ...
Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll : Desired roll rate in radians per second (float) pitch : Desired pitch rate in radi...
Below is the the instruction that describes the task: ### Input: Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll : Desired roll rate in radians per second (float) ...
def PartialDynamicSystem(self, ieq, variable): """ returns dynamical system blocks associated to output variable """ if ieq == 0: # U1=0 if variable == self.variables[0]: return[Gain(self.commands[0], variable, -self.Tmax)]
returns dynamical system blocks associated to output variable
Below is the the instruction that describes the task: ### Input: returns dynamical system blocks associated to output variable ### Response: def PartialDynamicSystem(self, ieq, variable): """ returns dynamical system blocks associated to output variable """ if ieq == 0: ...
def configure(self, options, conf): """Configure which kinds of exceptions trigger plugin. """ self.conf = conf self.enabled = options.epdb_debugErrors or options.epdb_debugFailures self.enabled_for_errors = options.epdb_debugErrors self.enabled_for_failures = options.epd...
Configure which kinds of exceptions trigger plugin.
Below is the the instruction that describes the task: ### Input: Configure which kinds of exceptions trigger plugin. ### Response: def configure(self, options, conf): """Configure which kinds of exceptions trigger plugin. """ self.conf = conf self.enabled = options.epdb_debugErrors ...
def attach_data(self, node): '''Generic method called for visit_XXXX() with XXXX in GatherOMPData.statements list ''' if self.current: for curr in self.current: md = OMPDirective(curr) metadata.add(node, md) self.current = list() ...
Generic method called for visit_XXXX() with XXXX in GatherOMPData.statements list
Below is the the instruction that describes the task: ### Input: Generic method called for visit_XXXX() with XXXX in GatherOMPData.statements list ### Response: def attach_data(self, node): '''Generic method called for visit_XXXX() with XXXX in GatherOMPData.statements list ''' ...
def supportsType(self, type_uri): """Does this endpoint support this type? I consider C{/server} endpoints to implicitly support C{/signon}. """ return ( (type_uri in self.type_uris) or (type_uri == OPENID_2_0_TYPE and self.isOPIdentifier()) )
Does this endpoint support this type? I consider C{/server} endpoints to implicitly support C{/signon}.
Below is the the instruction that describes the task: ### Input: Does this endpoint support this type? I consider C{/server} endpoints to implicitly support C{/signon}. ### Response: def supportsType(self, type_uri): """Does this endpoint support this type? I consider C{/server} endpoints...
def get_token(self): """ Retrieves the token from the File System :return dict or None: The token if exists, None otherwise """ token = None if self.token_path.exists(): with self.token_path.open('r') as token_file: token = self.token_construct...
Retrieves the token from the File System :return dict or None: The token if exists, None otherwise
Below is the the instruction that describes the task: ### Input: Retrieves the token from the File System :return dict or None: The token if exists, None otherwise ### Response: def get_token(self): """ Retrieves the token from the File System :return dict or None: The token if exis...
def add_ignore(self): """ Writes a .gitignore file to ignore the generated data file. """ path = self.lazy_folder + self.ignore_filename # If the file exists, return. if os.path.isfile(os.path.realpath(path)): return None sp, sf = os.path.split(self.data_fil...
Writes a .gitignore file to ignore the generated data file.
Below is the the instruction that describes the task: ### Input: Writes a .gitignore file to ignore the generated data file. ### Response: def add_ignore(self): """ Writes a .gitignore file to ignore the generated data file. """ path = self.lazy_folder + self.ignore_filename # If t...
def _parse_seq_preheader(line): """ $3=227(209): """ match = re.match(r"\$ (\d+) = (\d+) \( (\d+) \):", line, re.VERBOSE) if not match: raise ValueError("Unparseable header: " + line) index, this_len, query_len = match.groups() return map(int, (index, this_len, query_len))
$3=227(209):
Below is the the instruction that describes the task: ### Input: $3=227(209): ### Response: def _parse_seq_preheader(line): """ $3=227(209): """ match = re.match(r"\$ (\d+) = (\d+) \( (\d+) \):", line, re.VERBOSE) if not match: raise ValueError("Unparseable header: " + line) index, ...
def c_ls(api, args, verbose=False): """ List bitstreams of an object:: usage: cdstar ls [options] <URL> options: -t sort by modification time, newest first -s sort by filesize, biggest first -r reverse order while sorting """ obj = api.get_object(args['<URL>'].split('/')[-1]...
List bitstreams of an object:: usage: cdstar ls [options] <URL> options: -t sort by modification time, newest first -s sort by filesize, biggest first -r reverse order while sorting
Below is the the instruction that describes the task: ### Input: List bitstreams of an object:: usage: cdstar ls [options] <URL> options: -t sort by modification time, newest first -s sort by filesize, biggest first -r reverse order while sorting ### Response: def c_ls(api, arg...
def check_synced(localval, comm=None): """ It's common to forget to initialize your variables to the same values, or (less commonly) if you update them in some other way than adam, to get them out of sync. This function checks that variables on all MPI workers are the same, and raises an AssertionEr...
It's common to forget to initialize your variables to the same values, or (less commonly) if you update them in some other way than adam, to get them out of sync. This function checks that variables on all MPI workers are the same, and raises an AssertionError otherwise Arguments: comm: MPI com...
Below is the the instruction that describes the task: ### Input: It's common to forget to initialize your variables to the same values, or (less commonly) if you update them in some other way than adam, to get them out of sync. This function checks that variables on all MPI workers are the same, and raises ...
def _save_pys(self, filepath): """Saves file as pys file and returns True if save success Parameters ---------- filepath: String \tTarget file path for xls file """ try: with Bz2AOpen(filepath, "wb", main_window=self.main_...
Saves file as pys file and returns True if save success Parameters ---------- filepath: String \tTarget file path for xls file
Below is the the instruction that describes the task: ### Input: Saves file as pys file and returns True if save success Parameters ---------- filepath: String \tTarget file path for xls file ### Response: def _save_pys(self, filepath): """Saves file as pys file and return...
def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None): """Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates ...
Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates the base mapping. Used if an OS has specific differences. e.g. {"Po": "PortChannel"} vs ...
Below is the the instruction that describes the task: ### Input: Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates the base mapping. Us...
def mask_xdata(self) -> DataAndMetadata.DataAndMetadata: """Return the mask by combining any mask graphics on this data item as extended data. .. versionadded:: 1.0 Scriptable: Yes """ display_data_channel = self.__display_item.display_data_channel shape = display_data_...
Return the mask by combining any mask graphics on this data item as extended data. .. versionadded:: 1.0 Scriptable: Yes
Below is the the instruction that describes the task: ### Input: Return the mask by combining any mask graphics on this data item as extended data. .. versionadded:: 1.0 Scriptable: Yes ### Response: def mask_xdata(self) -> DataAndMetadata.DataAndMetadata: """Return the mask by combining ...
def warning(*tokens: Token, **kwargs: Any) -> None: """ Print a warning message """ tokens = [brown, "Warning:"] + list(tokens) # type: ignore kwargs["fileobj"] = sys.stderr message(*tokens, **kwargs)
Print a warning message
Below is the the instruction that describes the task: ### Input: Print a warning message ### Response: def warning(*tokens: Token, **kwargs: Any) -> None: """ Print a warning message """ tokens = [brown, "Warning:"] + list(tokens) # type: ignore kwargs["fileobj"] = sys.stderr message(*tokens, **kw...
def to_array(self): """ Serializes this InputContactMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputContactMessageContent, self).to_array() array['phone_number'] = u(self.phone_number) # py2:...
Serializes this InputContactMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
Below is the the instruction that describes the task: ### Input: Serializes this InputContactMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict ### Response: def to_array(self): """ Serializes this InputContactMessageContent to a diction...
def wait_for_element_present(driver, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ Searches for the specified element by the given selector. Returns the element object if the element is present on the page. The element can be invisible. Raises an excepti...
Searches for the specified element by the given selector. Returns the element object if the element is present on the page. The element can be invisible. Raises an exception if the element does not appear in the specified timeout. @Params driver - the webdriver object selector - the locator that...
Below is the the instruction that describes the task: ### Input: Searches for the specified element by the given selector. Returns the element object if the element is present on the page. The element can be invisible. Raises an exception if the element does not appear in the specified timeout. @Par...
def pa_pan(self, viewer, event, msg=True): """Interactively pan the image by a pan gesture. (the back end must support gestures) """ return self.gs_pan(viewer, event.state, event.delta_x, event.delta_y, msg=msg)
Interactively pan the image by a pan gesture. (the back end must support gestures)
Below is the the instruction that describes the task: ### Input: Interactively pan the image by a pan gesture. (the back end must support gestures) ### Response: def pa_pan(self, viewer, event, msg=True): """Interactively pan the image by a pan gesture. (the back end must support gestures) ...
def post_mortem_excepthook(type, value, tb): """ For post mortem exception handling, print a banner and enable post mortem debugging. """ clear_post_mortem() ipython_shell = get_ipython() ipython_shell.showtraceback((type, value, tb)) p = pdb.Pdb(ipython_shell.colors) if not type ==...
For post mortem exception handling, print a banner and enable post mortem debugging.
Below is the the instruction that describes the task: ### Input: For post mortem exception handling, print a banner and enable post mortem debugging. ### Response: def post_mortem_excepthook(type, value, tb): """ For post mortem exception handling, print a banner and enable post mortem debugging. ...
def enable_performance_data(self): """Enable performance data processing (globally) Format of the line that triggers function call:: ENABLE_PERFORMANCE_DATA :return: None """ if not self.my_conf.process_performance_data: self.my_conf.modified_attributes |= \...
Enable performance data processing (globally) Format of the line that triggers function call:: ENABLE_PERFORMANCE_DATA :return: None
Below is the the instruction that describes the task: ### Input: Enable performance data processing (globally) Format of the line that triggers function call:: ENABLE_PERFORMANCE_DATA :return: None ### Response: def enable_performance_data(self): """Enable performance data process...
def init_layout(self): """ Add all child widgets to the view """ super(AndroidViewGroup, self).init_layout() widget = self.widget i = 0 for child in self.children(): child_widget = child.widget if child_widget: if child.layout_param...
Add all child widgets to the view
Below is the the instruction that describes the task: ### Input: Add all child widgets to the view ### Response: def init_layout(self): """ Add all child widgets to the view """ super(AndroidViewGroup, self).init_layout() widget = self.widget i = 0 for child in self....
def interface_detail(self): """list[dict]: A list of dictionary items describing the interface type, name, role, mac, admin and operational state of interfaces of all rbridges. This method currently only lists the Physical Interfaces ( Gigabitethernet, tengigabitethernet, fortygi...
list[dict]: A list of dictionary items describing the interface type, name, role, mac, admin and operational state of interfaces of all rbridges. This method currently only lists the Physical Interfaces ( Gigabitethernet, tengigabitethernet, fortygigabitethernet, hundredgigabitet...
Below is the the instruction that describes the task: ### Input: list[dict]: A list of dictionary items describing the interface type, name, role, mac, admin and operational state of interfaces of all rbridges. This method currently only lists the Physical Interfaces ( Gigabitetherne...