code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def start_proxy(self): """ Starts Cloud SQL Proxy. You have to remember to stop the proxy if you started it! """ self._download_sql_proxy_if_needed() if self.sql_proxy_process: raise AirflowException("The sql proxy is already running: {}".format( ...
Starts Cloud SQL Proxy. You have to remember to stop the proxy if you started it!
Below is the the instruction that describes the task: ### Input: Starts Cloud SQL Proxy. You have to remember to stop the proxy if you started it! ### Response: def start_proxy(self): """ Starts Cloud SQL Proxy. You have to remember to stop the proxy if you started it! """...
def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
Helper for _AddMessageMethods().
Below is the the instruction that describes the task: ### Input: Helper for _AddMessageMethods(). ### Response: def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None try: return self._format_num(value) except (TypeError, ValueError): self.fail('invalid', input=value) except...
Format the value or raise a :exc:`ValidationError` if an error occurs.
Below is the the instruction that describes the task: ### Input: Format the value or raise a :exc:`ValidationError` if an error occurs. ### Response: def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None ...
def flatten_element(p): """ Convenience function to return record-style time series representation from elements ('p') members in station element. member['standard'] is a standard_name parameter name, typically CF based. Ideally, member['value'] should already be floating point value, so it's re...
Convenience function to return record-style time series representation from elements ('p') members in station element. member['standard'] is a standard_name parameter name, typically CF based. Ideally, member['value'] should already be floating point value, so it's ready to use. Useful with most pyo...
Below is the the instruction that describes the task: ### Input: Convenience function to return record-style time series representation from elements ('p') members in station element. member['standard'] is a standard_name parameter name, typically CF based. Ideally, member['value'] should already be flo...
def evaluate_model_single_recording(model_file, recording): """ Evaluate a model for a single recording. Parameters ---------- model_file : string Model file (.tar) recording : The handwritten recording. """ (preprocessing_queue, feature_list, model, output_semantic...
Evaluate a model for a single recording. Parameters ---------- model_file : string Model file (.tar) recording : The handwritten recording.
Below is the the instruction that describes the task: ### Input: Evaluate a model for a single recording. Parameters ---------- model_file : string Model file (.tar) recording : The handwritten recording. ### Response: def evaluate_model_single_recording(model_file, recording): ...
def undecorate(cls, function): ''' Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator. ''' if cls.is_function_validated(function): return cls.get_function_validator(function).functi...
Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator.
Below is the the instruction that describes the task: ### Input: Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator. ### Response: def undecorate(cls, function): ''' Remove validator decoration from a func...
def _from_json(json_data): """ Creates a Report from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Report """ if 'bbox' in json_data: box = BoundingBox._from_json(json_data['bbox']) else: ...
Creates a Report from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Report
Below is the the instruction that describes the task: ### Input: Creates a Report from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Report ### Response: def _from_json(json_data): """ Creates a Report from json data. ...
def set_source(self, source_id): """Sets the source. arg: source_id (osid.id.Id): the new publisher raise: InvalidArgument - ``source_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``source_id`` is ``null`` *compliance...
Sets the source. arg: source_id (osid.id.Id): the new publisher raise: InvalidArgument - ``source_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``source_id`` is ``null`` *compliance: mandatory -- This method must be implement...
Below is the the instruction that describes the task: ### Input: Sets the source. arg: source_id (osid.id.Id): the new publisher raise: InvalidArgument - ``source_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``source_id`` is ``n...
def value(board, who='x'): """Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', '...
Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', '...
Below is the the instruction that describes the task: ### Input: Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b...
def _init_properties(self): """ Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping """ self._missing = {} for k, p in self.params.items(): if p.required: self._missing[k] = p ...
Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping
Below is the the instruction that describes the task: ### Input: Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping ### Response: def _init_properties(self): """ Loop through the list of Properties, extract the derive...
def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report( self.debug, "Validating %%s checksum for %s" % filename) if not checker.is_valid(): tfp.close() os.unlink(filename) raise ...
checker is a ContentChecker
Below is the the instruction that describes the task: ### Input: checker is a ContentChecker ### Response: def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report( self.debug, "Validating %%s checksum for %s" % filenam...
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Applies to the main object in the AdjointLayout. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values ...
Return the values along the requested dimension. Applies to the main object in the AdjointLayout. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior depends ...
Below is the the instruction that describes the task: ### Input: Return the values along the requested dimension. Applies to the main object in the AdjointLayout. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values ...
def update_channels(cls, installation_id, channels_to_add=set(), channels_to_remove=set(), **kw): """ Allow an application to manually subscribe or unsubscribe an installation to a certain push channel in a unified operation. this is based on: https://www...
Allow an application to manually subscribe or unsubscribe an installation to a certain push channel in a unified operation. this is based on: https://www.parse.com/docs/rest#installations-updating installation_id: the installation id you'd like to add a channel to channels_to_a...
Below is the the instruction that describes the task: ### Input: Allow an application to manually subscribe or unsubscribe an installation to a certain push channel in a unified operation. this is based on: https://www.parse.com/docs/rest#installations-updating installation_id: the...
def get_instance(self, payload): """ Build an instance of UsageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.UsageInstance :rtype: twilio.rest.api.v2010.account.usage.UsageInstance """ return UsageInsta...
Build an instance of UsageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.UsageInstance :rtype: twilio.rest.api.v2010.account.usage.UsageInstance
Below is the the instruction that describes the task: ### Input: Build an instance of UsageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.UsageInstance :rtype: twilio.rest.api.v2010.account.usage.UsageInstance ### Response: def ge...
def total(self): ''' Returns sum of all counts in all features that are multisets. ''' feats = imap(lambda name: self[name], self._counters()) return sum(chain(*map(lambda mset: map(abs, mset.values()), feats)))
Returns sum of all counts in all features that are multisets.
Below is the the instruction that describes the task: ### Input: Returns sum of all counts in all features that are multisets. ### Response: def total(self): ''' Returns sum of all counts in all features that are multisets. ''' feats = imap(lambda name: self[name], self._counters())...
def read_pixel_register(self, pix_regs=None, dcs=range(40), overwrite_config=False): '''The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register. Pixels without any data are masked. Parameters ---------- pix_regs ...
The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register. Pixels without any data are masked. Parameters ---------- pix_regs : iterable, string List of pixel register to read (e.g. Enable, C_High, ...). ...
Below is the the instruction that describes the task: ### Input: The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register. Pixels without any data are masked. Parameters ---------- pix_regs : iterable, string ...
def flux(self, photon_energy, distance=1 * u.kpc, seed=None): """Differential flux at a given distance from the source from a single seed photon field Parameters ---------- photon_energy : :class:`~astropy.units.Quantity` float or array Photon energy array. ...
Differential flux at a given distance from the source from a single seed photon field Parameters ---------- photon_energy : :class:`~astropy.units.Quantity` float or array Photon energy array. distance : :class:`~astropy.units.Quantity` float, optional D...
Below is the the instruction that describes the task: ### Input: Differential flux at a given distance from the source from a single seed photon field Parameters ---------- photon_energy : :class:`~astropy.units.Quantity` float or array Photon energy array. dist...
def cli(execute, region, aws_access_key_id, aws_secret_access_key, s3_staging_dir, athenaclirc, profile, database): '''A Athena terminal client with auto-completion and syntax highlighting. \b Examples: - athenacli - athenacli my_database ''' if (athenaclirc == ATHENACLIRC) and ...
A Athena terminal client with auto-completion and syntax highlighting. \b Examples: - athenacli - athenacli my_database
Below is the the instruction that describes the task: ### Input: A Athena terminal client with auto-completion and syntax highlighting. \b Examples: - athenacli - athenacli my_database ### Response: def cli(execute, region, aws_access_key_id, aws_secret_access_key, s3_staging_dir, athe...
def upload_object(bucket_path, bucket, content='', metadata=None, acl=None, cache_control=None, content_type=None): """Upload an arbitrary object to an S3 bucket. Parameters ---------- bucket_path : `str` Destination path (also known as the key name) of the f...
Upload an arbitrary object to an S3 bucket. Parameters ---------- bucket_path : `str` Destination path (also known as the key name) of the file in the S3 bucket. content : `str` or `bytes`, optional Object content. bucket : boto3 Bucket instance S3 bucket. metada...
Below is the the instruction that describes the task: ### Input: Upload an arbitrary object to an S3 bucket. Parameters ---------- bucket_path : `str` Destination path (also known as the key name) of the file in the S3 bucket. content : `str` or `bytes`, optional Object cont...
def insert(self, key, minhash, check_duplication=True): ''' Insert a key to the index, together with a MinHash (or weighted MinHash) of the set referenced by the key. :param str key: The identifier of the set. :param datasketch.MinHash minhash: The MinHash of the set. ...
Insert a key to the index, together with a MinHash (or weighted MinHash) of the set referenced by the key. :param str key: The identifier of the set. :param datasketch.MinHash minhash: The MinHash of the set. :param bool check_duplication: To avoid duplicate keys in the storage...
Below is the the instruction that describes the task: ### Input: Insert a key to the index, together with a MinHash (or weighted MinHash) of the set referenced by the key. :param str key: The identifier of the set. :param datasketch.MinHash minhash: The MinHash of the set. ...
def check(self, values, namespace): """specifying a plain tuple allows arguments that are tuples or lists; specifying a specialized (subclassed) tuple allows only that type; specifying a list allows only that list type.""" is_tuplish_type = (issubclass(self._cls, tg.Tuple) or ...
specifying a plain tuple allows arguments that are tuples or lists; specifying a specialized (subclassed) tuple allows only that type; specifying a list allows only that list type.
Below is the the instruction that describes the task: ### Input: specifying a plain tuple allows arguments that are tuples or lists; specifying a specialized (subclassed) tuple allows only that type; specifying a list allows only that list type. ### Response: def check(self, values, namespace): ...
def _consolidate_slices(slices): """Consolidate adjacent slices in a list of slices. """ result = [] last_slice = slice(None) for slice_ in slices: if not isinstance(slice_, slice): raise ValueError('list element is not a slice: %r' % slice_) if (result and last_slice.sto...
Consolidate adjacent slices in a list of slices.
Below is the the instruction that describes the task: ### Input: Consolidate adjacent slices in a list of slices. ### Response: def _consolidate_slices(slices): """Consolidate adjacent slices in a list of slices. """ result = [] last_slice = slice(None) for slice_ in slices: if not isin...
def _colorize(self, depth_im, color_im): """Colorize a depth image from the PhoXi using a color image from the webcam. Parameters ---------- depth_im : DepthImage The PhoXi depth image. color_im : ColorImage Corresponding color image. Returns ...
Colorize a depth image from the PhoXi using a color image from the webcam. Parameters ---------- depth_im : DepthImage The PhoXi depth image. color_im : ColorImage Corresponding color image. Returns ------- ColorImage A colori...
Below is the the instruction that describes the task: ### Input: Colorize a depth image from the PhoXi using a color image from the webcam. Parameters ---------- depth_im : DepthImage The PhoXi depth image. color_im : ColorImage Corresponding color image. ...
def imshow(data, photometric=None, planarconfig=None, bitspersample=None, interpolation=None, cmap=None, vmin=None, vmax=None, figure=None, title=None, dpi=96, subplot=None, maxdim=None, **kwargs): """Plot n-dimensional images using matplotlib.pyplot. Return figure, subplot and...
Plot n-dimensional images using matplotlib.pyplot. Return figure, subplot and plot axis. Requires pyplot already imported C{from matplotlib import pyplot}. Parameters ---------- data : nd array The image data. photometric : {'MINISWHITE', 'MINISBLACK', 'RGB', or 'PALETTE'} The ...
Below is the the instruction that describes the task: ### Input: Plot n-dimensional images using matplotlib.pyplot. Return figure, subplot and plot axis. Requires pyplot already imported C{from matplotlib import pyplot}. Parameters ---------- data : nd array The image data. photome...
def update_note(note, **kwargs): """ Update a note """ note_i = _get_note(note.id) if note.ref_key != note_i.ref_key: raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key)) note_i.set_ref(note.ref_key, note.ref_id) ...
Update a note
Below is the the instruction that describes the task: ### Input: Update a note ### Response: def update_note(note, **kwargs): """ Update a note """ note_i = _get_note(note.id) if note.ref_key != note_i.ref_key: raise HydraError("Cannot convert a %s note to a %s note. Please create a ne...
def analyse_text(text): """ Check if code contains REBOL header and so it probably not R code """ if re.match(r'^\s*REBOL\s*\[', text, re.IGNORECASE): # The code starts with REBOL header return 1.0 elif re.search(r'\s*REBOL\s*[', text, re.IGNORECASE): ...
Check if code contains REBOL header and so it probably not R code
Below is the the instruction that describes the task: ### Input: Check if code contains REBOL header and so it probably not R code ### Response: def analyse_text(text): """ Check if code contains REBOL header and so it probably not R code """ if re.match(r'^\s*REBOL\s*\[', text, re....
def pageassert(func): ''' Decorator that assert page number ''' @wraps(func) def wrapper(*args, **kwargs): if args[0] < 1 or args[0] > 40: raise ValueError('Page Number not found') return func(*args, **kwargs) return wrapper
Decorator that assert page number
Below is the the instruction that describes the task: ### Input: Decorator that assert page number ### Response: def pageassert(func): ''' Decorator that assert page number ''' @wraps(func) def wrapper(*args, **kwargs): if args[0] < 1 or args[0] > 40: raise ValueError('Page ...
def build_locator(selector): """ - ID = "#valid_id" - CLASS_NAME = ".valid_class_name" - TAG_NAME = "valid_tag_name" - XPATH = start with "./" or "//" or "$x:" - LINK_TEXT = start with "$link_text:" - PARTIAL_LINK_TEXT = start with "$partial_link_text:" - NAME = "@valid_name_attribute_va...
- ID = "#valid_id" - CLASS_NAME = ".valid_class_name" - TAG_NAME = "valid_tag_name" - XPATH = start with "./" or "//" or "$x:" - LINK_TEXT = start with "$link_text:" - PARTIAL_LINK_TEXT = start with "$partial_link_text:" - NAME = "@valid_name_attribute_value" CSS_SELECTOR = all other that s...
Below is the the instruction that describes the task: ### Input: - ID = "#valid_id" - CLASS_NAME = ".valid_class_name" - TAG_NAME = "valid_tag_name" - XPATH = start with "./" or "//" or "$x:" - LINK_TEXT = start with "$link_text:" - PARTIAL_LINK_TEXT = start with "$partial_link_text:" - NAME...
def parse_text_to_table(txt): """ takes a blob of text and finds delimiter OR guesses the column positions to parse into a table. input: txt = blob of text, lines separated by \n output: res = table of text """ res = [] # resulting table delim = identify_delim(txt) print('txt to pars...
takes a blob of text and finds delimiter OR guesses the column positions to parse into a table. input: txt = blob of text, lines separated by \n output: res = table of text
Below is the the instruction that describes the task: ### Input: takes a blob of text and finds delimiter OR guesses the column positions to parse into a table. input: txt = blob of text, lines separated by \n output: res = table of text ### Response: def parse_text_to_table(txt): """ takes a blob of ...
def close(self): """ Destructor for this audio interface. Waits the threads to finish their streams, if desired. """ with self.halting: # Avoid simultaneous "close" threads if not self.finished: # Ignore all "close" calls, but the first, self.finished = True # and any call to play wo...
Destructor for this audio interface. Waits the threads to finish their streams, if desired.
Below is the the instruction that describes the task: ### Input: Destructor for this audio interface. Waits the threads to finish their streams, if desired. ### Response: def close(self): """ Destructor for this audio interface. Waits the threads to finish their streams, if desired. """ wit...
def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides): """Convenience method for quickly allowing other resources to access this one""" response_headers = {} if origins: @hug.response_middleware() def process_data(reque...
Convenience method for quickly allowing other resources to access this one
Below is the the instruction that describes the task: ### Input: Convenience method for quickly allowing other resources to access this one ### Response: def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides): """Convenience method for quickly allowing ot...
def tag_del(self, item, tag): """ Remove tag from the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str """ tags = list(self.item(item, "tags")) if tag in tags: tags.remove(tag) ...
Remove tag from the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str
Below is the the instruction that describes the task: ### Input: Remove tag from the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str ### Response: def tag_del(self, item, tag): """ Remove tag from the tags of it...
def get_record(self): """Override the base.""" self.recid = self.get_recid() self.remove_controlfields() self.update_system_numbers() self.add_systemnumber("Inspire", recid=self.recid) self.add_control_number("003", "SzGeCERN") self.update_collections() se...
Override the base.
Below is the the instruction that describes the task: ### Input: Override the base. ### Response: def get_record(self): """Override the base.""" self.recid = self.get_recid() self.remove_controlfields() self.update_system_numbers() self.add_systemnumber("Inspire", recid=self...
def guard_activate(analysis_service): """Returns whether the transition activate can be performed for the analysis service passed in """ calculation = analysis_service.getCalculation() if not calculation: return True # If the calculation is inactive, we cannot activate the service i...
Returns whether the transition activate can be performed for the analysis service passed in
Below is the the instruction that describes the task: ### Input: Returns whether the transition activate can be performed for the analysis service passed in ### Response: def guard_activate(analysis_service): """Returns whether the transition activate can be performed for the analysis service passed in...
def get_sections(self, s, base, sections=['Parameters', 'Other Parameters']): """ Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must app...
Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must appear in the :attr:`param_like_sections` or the :attr:`text_sections` attribute. Parameters ----...
Below is the the instruction that describes the task: ### Input: Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must appear in the :attr:`param_like_sections` or ...
def _sync(self, timeout_ms=30000): """ Reimplements MatrixClient._sync, add 'account_data' support to /sync """ response = self.api.sync(self.sync_token, timeout_ms) prev_sync_token = self.sync_token self.sync_token = response["next_batch"] if self._handle_thread is not None: ...
Reimplements MatrixClient._sync, add 'account_data' support to /sync
Below is the the instruction that describes the task: ### Input: Reimplements MatrixClient._sync, add 'account_data' support to /sync ### Response: def _sync(self, timeout_ms=30000): """ Reimplements MatrixClient._sync, add 'account_data' support to /sync """ response = self.api.sync(self.sync_toke...
def __purge(): """Remove all dead signal receivers from the global receivers collection. Note: It is assumed that the caller holds the __lock. """ global __receivers newreceivers = collections.defaultdict(list) for signal, receivers in six.iteritems(__receivers): alive = [x for...
Remove all dead signal receivers from the global receivers collection. Note: It is assumed that the caller holds the __lock.
Below is the the instruction that describes the task: ### Input: Remove all dead signal receivers from the global receivers collection. Note: It is assumed that the caller holds the __lock. ### Response: def __purge(): """Remove all dead signal receivers from the global receivers collection. ...
def is_F_hypergraph(self): """Indicates whether the hypergraph is an F-hypergraph. In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every hyperedge has exactly one node in the tail. :returns: bool -- True iff the hypergraph is an F-hypergraph. """ for hyp...
Indicates whether the hypergraph is an F-hypergraph. In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every hyperedge has exactly one node in the tail. :returns: bool -- True iff the hypergraph is an F-hypergraph.
Below is the the instruction that describes the task: ### Input: Indicates whether the hypergraph is an F-hypergraph. In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every hyperedge has exactly one node in the tail. :returns: bool -- True iff the hypergraph is an F-hypergrap...
def authenticate( self, end_user_ip, personal_number=None, requirement=None, **kwargs ): """Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. Note that personal number is not needed when authentication is to be done on t...
Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. Note that personal number is not needed when authentication is to be done on the same device, provided that the returned ``autoStartToken`` is used to open the BankID Client. ...
Below is the the instruction that describes the task: ### Input: Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. Note that personal number is not needed when authentication is to be done on the same device, provided that the returned ...
def _DoCopyFile(source_filename, target_filename, copy_symlink=True): ''' :param unicode source_filename: The source filename. Schemas: local, ftp, http :param unicode target_filename: Target filename. Schemas: local, ftp :param copy_symlink: @see _CopyFileLoca...
:param unicode source_filename: The source filename. Schemas: local, ftp, http :param unicode target_filename: Target filename. Schemas: local, ftp :param copy_symlink: @see _CopyFileLocal :raises FileNotFoundError: If source_filename does not exist
Below is the the instruction that describes the task: ### Input: :param unicode source_filename: The source filename. Schemas: local, ftp, http :param unicode target_filename: Target filename. Schemas: local, ftp :param copy_symlink: @see _CopyFileLocal :raise...
def truncate(self, size): """ Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file """ self.sftp._log( DEBUG, "truncate({...
Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file
Below is the the instruction that describes the task: ### Input: Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file ### Response: def truncate(self, size): ...
def apply_cats(df, trn): """Changes any columns of strings in df into categorical variables using trn as a template for the category codes. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. The category codes are determined by trn. ...
Changes any columns of strings in df into categorical variables using trn as a template for the category codes. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. The category codes are determined by trn. trn: A pandas dataframe. Whe...
Below is the the instruction that describes the task: ### Input: Changes any columns of strings in df into categorical variables using trn as a template for the category codes. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. The c...
def mul_table(self, other): """ Fast multiplication using a the LWNAF precomputation table. """ # Get a BigInt other = coerceBigInt(other) if not other: return NotImplemented other %= orderG2() # Building the precomputation table, if there is ...
Fast multiplication using a the LWNAF precomputation table.
Below is the the instruction that describes the task: ### Input: Fast multiplication using a the LWNAF precomputation table. ### Response: def mul_table(self, other): """ Fast multiplication using a the LWNAF precomputation table. """ # Get a BigInt other = coerceBigInt(othe...
def to_dataframe(self, dtypes=None): """Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently pa...
Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro libr...
Below is the the instruction that describes the task: ### Input: Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. ...
def wrap_hvac(msg): """Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class?""" # pylint: disable=missing-docstring def wrap_call(func): ...
Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class?
Below is the the instruction that describes the task: ### Input: Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class? ### Response: def wrap_hv...
def summarize_variable(self, variable = None, use_baseline = False, weighted = False, force_compute = False): """ Prints a summary of a variable including its memory usage. :param string variable: the variable being summarized :param bool use_baseline: the tax-benefit-system...
Prints a summary of a variable including its memory usage. :param string variable: the variable being summarized :param bool use_baseline: the tax-benefit-system considered :param bool weighted: whether the produced statistics should be weigthted or not :param bool force...
Below is the the instruction that describes the task: ### Input: Prints a summary of a variable including its memory usage. :param string variable: the variable being summarized :param bool use_baseline: the tax-benefit-system considered :param bool weighted: whether the produce...
def main(self): """ Run the necessary methods in the correct order """ if not os.path.isfile(self.gdcs_report): logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Run the analyses ShortKSippingMethods(self, self.cutoff) ...
Run the necessary methods in the correct order
Below is the the instruction that describes the task: ### Input: Run the necessary methods in the correct order ### Response: def main(self): """ Run the necessary methods in the correct order """ if not os.path.isfile(self.gdcs_report): logging.info('Starting {} analysi...
def __GetAuthorizationTokenUsingMasterKey(verb, resource_id_or_fullname, resource_type, headers, master_key): """Gets the authorization token using `mas...
Gets the authorization token using `master_key. :param str verb: :param str resource_id_or_fullname: :param str resource_type: :param dict headers: :param str master_key: :return: The authorization token. :rtype: dict
Below is the the instruction that describes the task: ### Input: Gets the authorization token using `master_key. :param str verb: :param str resource_id_or_fullname: :param str resource_type: :param dict headers: :param str master_key: :return: The authorization token. :rtype: ...
def makedbthreads(self, folder): """ Setup and create threads for class :param folder: folder with sequence files with which to create blast databases """ # Create and start threads for each fasta file in the list for i in range(len(folder)): # Send the thread...
Setup and create threads for class :param folder: folder with sequence files with which to create blast databases
Below is the the instruction that describes the task: ### Input: Setup and create threads for class :param folder: folder with sequence files with which to create blast databases ### Response: def makedbthreads(self, folder): """ Setup and create threads for class :param folder: fol...
def sampleLocationFromFeature(self, feature): """ Samples a location from one specific feature. This is only supported with three dimensions. """ if feature == "face": return self._sampleFromFaces() elif feature == "edge": return self._sampleFromEdges() elif feature == "vertex":...
Samples a location from one specific feature. This is only supported with three dimensions.
Below is the the instruction that describes the task: ### Input: Samples a location from one specific feature. This is only supported with three dimensions. ### Response: def sampleLocationFromFeature(self, feature): """ Samples a location from one specific feature. This is only supported with th...
def related_lua_args(self): '''Generator of load_related arguments''' related = self.queryelem.select_related if related: meta = self.meta for rel in related: field = meta.dfields[rel] relmodel = field.relmodel bk = ...
Generator of load_related arguments
Below is the the instruction that describes the task: ### Input: Generator of load_related arguments ### Response: def related_lua_args(self): '''Generator of load_related arguments''' related = self.queryelem.select_related if related: meta = self.meta for rel ...
def generate_output_network(self, json_data=None, hr=True, show_name=False, colorize=True): """ The function for generating CLI output RDAP network results. Args: json_data (:obj:`dict`): The data to process. Defaults to None. hr (:obj:`bo...
The function for generating CLI output RDAP network results. Args: json_data (:obj:`dict`): The data to process. Defaults to None. hr (:obj:`bool`): Enable human readable key translations. Defaults to True. show_name (:obj:`bool`): Show human readable name (d...
Below is the the instruction that describes the task: ### Input: The function for generating CLI output RDAP network results. Args: json_data (:obj:`dict`): The data to process. Defaults to None. hr (:obj:`bool`): Enable human readable key translations. Defaults to T...
def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None): """Reset object attributes when state is INIT.""" logger.debug('Reseting attributes.') if iface is None: iface = conf.iface if client_mac is None: # scapy for python 3 returns byte, not tuple...
Reset object attributes when state is INIT.
Below is the the instruction that describes the task: ### Input: Reset object attributes when state is INIT. ### Response: def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None): """Reset object attributes when state is INIT.""" logger.debug('Reseting attributes.') if iface...
def remove_writer(self, address): """ Remove a writer address from the routing table, if present. """ log_debug("[#0000] C: <ROUTING> Removing writer %r", address) self.routing_table.writers.discard(address) log_debug("[#0000] C: <ROUTING> table=%r", self.routing_table)
Remove a writer address from the routing table, if present.
Below is the the instruction that describes the task: ### Input: Remove a writer address from the routing table, if present. ### Response: def remove_writer(self, address): """ Remove a writer address from the routing table, if present. """ log_debug("[#0000] C: <ROUTING> Removing writer %...
def get_rmse(self, data_x=None, data_y=None): """ Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line ...
Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps b...
Below is the the instruction that describes the task: ### Input: Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line ...
def PROFILE_SDRAUTIAN(sg0,GamD,Gam0,Gam2,Shift0,Shift2,anuVC,sg): """ # Speed dependent Rautian profile based on HTP. # Input parameters: # sg0 : Unperturbed line position in cm-1 (Input). # GamD : Doppler HWHM in cm-1 (Input) # Gam0 : Speed-averaged line-width in cm-1 (...
# Speed dependent Rautian profile based on HTP. # Input parameters: # sg0 : Unperturbed line position in cm-1 (Input). # GamD : Doppler HWHM in cm-1 (Input) # Gam0 : Speed-averaged line-width in cm-1 (Input). # Gam2 : Speed dependence of the line-width in cm-1...
Below is the the instruction that describes the task: ### Input: # Speed dependent Rautian profile based on HTP. # Input parameters: # sg0 : Unperturbed line position in cm-1 (Input). # GamD : Doppler HWHM in cm-1 (Input) # Gam0 : Speed-averaged line-width in cm-1 (Input). ...
def find_by_user(self, user, params={}, **options): """Returns the compact records for all teams to which user is assigned. Parameters ---------- user : {String} An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the keyw...
Returns the compact records for all teams to which user is assigned. Parameters ---------- user : {String} An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the keyword `me` to indicate the current user making the request...
Below is the the instruction that describes the task: ### Input: Returns the compact records for all teams to which user is assigned. Parameters ---------- user : {String} An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the...
def start(self): ''' Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Syndic, self).start() if check_user(self.config['user']): ...
Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
Below is the the instruction that describes the task: ### Input: Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ### Response: def start(self): ''' Start the...
def assume(self, cond): """ Optimizer hint: assume *cond* is always true. """ fn = self.module.declare_intrinsic("llvm.assume") return self.call(fn, [cond])
Optimizer hint: assume *cond* is always true.
Below is the the instruction that describes the task: ### Input: Optimizer hint: assume *cond* is always true. ### Response: def assume(self, cond): """ Optimizer hint: assume *cond* is always true. """ fn = self.module.declare_intrinsic("llvm.assume") return self.call(fn, [...
def _forward_request(transaction, destination, path): """ Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. ...
Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. :rtype : Transaction :return: the edited transaction
Below is the the instruction that describes the task: ### Input: Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. :rt...
def fromML(mat): """ Convert a matrix from the new mllib-local representation. This does NOT copy the data; it copies references. :param mat: a :py:class:`pyspark.ml.linalg.Matrix` :return: a :py:class:`pyspark.mllib.linalg.Matrix` .. versionadded:: 2.0.0 """ ...
Convert a matrix from the new mllib-local representation. This does NOT copy the data; it copies references. :param mat: a :py:class:`pyspark.ml.linalg.Matrix` :return: a :py:class:`pyspark.mllib.linalg.Matrix` .. versionadded:: 2.0.0
Below is the the instruction that describes the task: ### Input: Convert a matrix from the new mllib-local representation. This does NOT copy the data; it copies references. :param mat: a :py:class:`pyspark.ml.linalg.Matrix` :return: a :py:class:`pyspark.mllib.linalg.Matrix` .. ver...
def _RunMethod(self, method_config, request, global_params=None, upload=None, upload_config=None, download=None): """Call this method with request.""" if upload is not None and download is not None: # TODO(craigcitro): This just involves refactoring the logic #...
Call this method with request.
Below is the the instruction that describes the task: ### Input: Call this method with request. ### Response: def _RunMethod(self, method_config, request, global_params=None, upload=None, upload_config=None, download=None): """Call this method with request.""" if upload is not No...
def make_datastore_api(client): """Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API insta...
Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API instance with the proper credentials.
Below is the the instruction that describes the task: ### Input: Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :...
def set_learning_rate(self, lr): """Sets a new learning rate of the optimizer. Parameters ---------- lr : float The new learning rate of the optimizer. """ if not isinstance(self._optimizer, opt.Optimizer): raise UserWarning("Optimizer has to be d...
Sets a new learning rate of the optimizer. Parameters ---------- lr : float The new learning rate of the optimizer.
Below is the the instruction that describes the task: ### Input: Sets a new learning rate of the optimizer. Parameters ---------- lr : float The new learning rate of the optimizer. ### Response: def set_learning_rate(self, lr): """Sets a new learning rate of the optimiz...
def write(self, data: Union[bytes, memoryview]) -> "Future[None]": """Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memory...
Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memoryview`. .. versionchanged:: 4.0 Now returns a `.Future` if...
Below is the the instruction that describes the task: ### Input: Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memoryview`. ...
def autoencoder_residual(): """Residual autoencoder model.""" hparams = autoencoder_autoregressive() hparams.optimizer = "Adafactor" hparams.clip_grad_norm = 1.0 hparams.learning_rate_constant = 0.5 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt...
Residual autoencoder model.
Below is the the instruction that describes the task: ### Input: Residual autoencoder model. ### Response: def autoencoder_residual(): """Residual autoencoder model.""" hparams = autoencoder_autoregressive() hparams.optimizer = "Adafactor" hparams.clip_grad_norm = 1.0 hparams.learning_rate_constant = 0.5...
def mapkeys(function, dict_): """Return a new dictionary where the keys come from applying ``function`` to the keys of given dictionary. .. warning:: If ``function`` returns the same value for more than one key, it is undefined which key will be chosen for the resulting dictionary. :p...
Return a new dictionary where the keys come from applying ``function`` to the keys of given dictionary. .. warning:: If ``function`` returns the same value for more than one key, it is undefined which key will be chosen for the resulting dictionary. :param function: Function taking a dict...
Below is the the instruction that describes the task: ### Input: Return a new dictionary where the keys come from applying ``function`` to the keys of given dictionary. .. warning:: If ``function`` returns the same value for more than one key, it is undefined which key will be chosen for t...
def _ensure_patient_group_is_ok(patient_object, patient_name=None): """ Ensure that the provided entries for the patient groups is formatted properly. :param set|dict patient_object: The values passed to the samples patient group :param str patient_name: Optional name for the set :raises ParameterE...
Ensure that the provided entries for the patient groups is formatted properly. :param set|dict patient_object: The values passed to the samples patient group :param str patient_name: Optional name for the set :raises ParameterError: If required entry doesnt exist
Below is the the instruction that describes the task: ### Input: Ensure that the provided entries for the patient groups is formatted properly. :param set|dict patient_object: The values passed to the samples patient group :param str patient_name: Optional name for the set :raises ParameterError: If re...
def calculate_lstm_output_shapes(operator): ''' See LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 3], output_count_range=[1, 3]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operat...
See LSTM's conversion function for its output shapes.
Below is the the instruction that describes the task: ### Input: See LSTM's conversion function for its output shapes. ### Response: def calculate_lstm_output_shapes(operator): ''' See LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[...
def construct_start_message(self): """Collect preliminary run info at the start of the DFK. Returns : - Message dict dumped as json string, ready for UDP """ uname = getpass.getuser().encode('latin1') hashed_username = hashlib.sha256(uname).hexdigest()[0:10] ...
Collect preliminary run info at the start of the DFK. Returns : - Message dict dumped as json string, ready for UDP
Below is the the instruction that describes the task: ### Input: Collect preliminary run info at the start of the DFK. Returns : - Message dict dumped as json string, ready for UDP ### Response: def construct_start_message(self): """Collect preliminary run info at the start of the DF...
def get_output_files(self): """ Return list of output files for this DAG node and its job. """ output_files = list(self.__output_files) if isinstance(self.job(), CondorDAGJob): output_files = output_files + self.job().get_output_files() return output_files
Return list of output files for this DAG node and its job.
Below is the the instruction that describes the task: ### Input: Return list of output files for this DAG node and its job. ### Response: def get_output_files(self): """ Return list of output files for this DAG node and its job. """ output_files = list(self.__output_files) if isinstance(self.jo...
def matchTypes(accept_types, have_types): """Given the result of parsing an Accept: header, and the available MIME types, return the acceptable types with their quality markdowns. For example: >>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5') >>> matchTypes(acceptable, ['text/...
Given the result of parsing an Accept: header, and the available MIME types, return the acceptable types with their quality markdowns. For example: >>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5') >>> matchTypes(acceptable, ['text/plain', 'text/html', 'image/jpeg']) [('text/h...
Below is the the instruction that describes the task: ### Input: Given the result of parsing an Accept: header, and the available MIME types, return the acceptable types with their quality markdowns. For example: >>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5') >>> matchTypes...
def _respond(self, channel, text): """Respond to a message on the current socket. Args: channel (:py:class:`str`): The channel to send to. text (:py:class:`str`): The message text to send. """ result = self._format_message(channel, text) if result is not Non...
Respond to a message on the current socket. Args: channel (:py:class:`str`): The channel to send to. text (:py:class:`str`): The message text to send.
Below is the the instruction that describes the task: ### Input: Respond to a message on the current socket. Args: channel (:py:class:`str`): The channel to send to. text (:py:class:`str`): The message text to send. ### Response: def _respond(self, channel, text): """Respond to...
def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: self.switch_to_plugin() editorstack.set_or_clear_breakpoint()
Set/Clear breakpoint
Below is the the instruction that describes the task: ### Input: Set/Clear breakpoint ### Response: def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: self.switch_to_plugin() edi...
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None): """ Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start() """ operation = RunOperation(client, container, interactive=interac...
Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start()
Below is the the instruction that describes the task: ### Input: Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start() ### Response: def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None): ...
def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) py31compat.makedirs(dirname, exist_ok=True)
Ensure that the parent directory of `path` exists
Below is the the instruction that describes the task: ### Input: Ensure that the parent directory of `path` exists ### Response: def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) py31compat.makedirs(dirname, exist_ok=True)
def CheckTrailingSemicolon(filename, clean_lines, linenum, error): """Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any error...
Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Below is the the instruction that describes the task: ### Input: Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors f...
def del_tag( self, tag): """*delete a tag this taskpaper object* **Key Arguments:** - ``tag`` -- the tag to delete to the object **Usage:** .. code-block:: python aTask.del_tag("@due") """ if tag.replace("@", "...
*delete a tag this taskpaper object* **Key Arguments:** - ``tag`` -- the tag to delete to the object **Usage:** .. code-block:: python aTask.del_tag("@due")
Below is the the instruction that describes the task: ### Input: *delete a tag this taskpaper object* **Key Arguments:** - ``tag`` -- the tag to delete to the object **Usage:** .. code-block:: python aTask.del_tag("@due") ### Response: def del_tag( ...
def insert_pattern(self, pattern, index): """ Inserts given pattern into the Model. :param pattern: Pattern. :type pattern: unicode :param index: Insertion index. :type index: int :return: Method success. :rtype: bool """ LOGGER.debug("> ...
Inserts given pattern into the Model. :param pattern: Pattern. :type pattern: unicode :param index: Insertion index. :type index: int :return: Method success. :rtype: bool
Below is the the instruction that describes the task: ### Input: Inserts given pattern into the Model. :param pattern: Pattern. :type pattern: unicode :param index: Insertion index. :type index: int :return: Method success. :rtype: bool ### Response: def insert_patt...
def temp_file_context(raw_dump_path, logger=None): """this contextmanager implements conditionally deleting a pathname at the end of a context if the pathname indicates that it is a temp file by having the word 'TEMPORARY' embedded in it.""" try: yield raw_dump_path finally: if 'TEMP...
this contextmanager implements conditionally deleting a pathname at the end of a context if the pathname indicates that it is a temp file by having the word 'TEMPORARY' embedded in it.
Below is the the instruction that describes the task: ### Input: this contextmanager implements conditionally deleting a pathname at the end of a context if the pathname indicates that it is a temp file by having the word 'TEMPORARY' embedded in it. ### Response: def temp_file_context(raw_dump_path, logger...
def RobotFactory(path, parent=None): '''Return an instance of SuiteFile, ResourceFile, SuiteFolder Exactly which is returned depends on whether it's a file or folder, and if a file, the contents of the file. If there is a testcase table, this will return an instance of SuiteFile, otherwise it will ...
Return an instance of SuiteFile, ResourceFile, SuiteFolder Exactly which is returned depends on whether it's a file or folder, and if a file, the contents of the file. If there is a testcase table, this will return an instance of SuiteFile, otherwise it will return an instance of ResourceFile.
Below is the the instruction that describes the task: ### Input: Return an instance of SuiteFile, ResourceFile, SuiteFolder Exactly which is returned depends on whether it's a file or folder, and if a file, the contents of the file. If there is a testcase table, this will return an instance of SuiteFil...
def get_singleton(cls, annotators=None, **options): """ Get or create a corenlp parser with the given annotator and options Note: multiple parsers with the same annotator and different options are not supported. """ if annotators is not None: annotators ...
Get or create a corenlp parser with the given annotator and options Note: multiple parsers with the same annotator and different options are not supported.
Below is the the instruction that describes the task: ### Input: Get or create a corenlp parser with the given annotator and options Note: multiple parsers with the same annotator and different options are not supported. ### Response: def get_singleton(cls, annotators=None, **options): ...
def set_code_exprs(self, codes): """Convenience: sets all the code expressions at once.""" self.code_objs = dict() self._codes = [] for code in codes: self.append_code_expr(code)
Convenience: sets all the code expressions at once.
Below is the the instruction that describes the task: ### Input: Convenience: sets all the code expressions at once. ### Response: def set_code_exprs(self, codes): """Convenience: sets all the code expressions at once.""" self.code_objs = dict() self._codes = [] for code in codes: ...
def _query_entities(self, table_name, filter=None, select=None, max_results=None, marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA, property_resolver=None, timeout=None, _context=None): ''' Returns a list of entities under the specified table. ...
Returns a list of entities under the specified table. Makes a single list request to the service. Used internally by the query_entities method. :param str table_name: The name of the table to query. :param str filter: Returns only entities that satisfy the specified fil...
Below is the the instruction that describes the task: ### Input: Returns a list of entities under the specified table. Makes a single list request to the service. Used internally by the query_entities method. :param str table_name: The name of the table to query. :param str fil...
def do_trace(self, arg): """ t - trace at the current assembly instruction trace - trace at the current assembly instruction """ if arg: # XXX this check is to be removed raise CmdError("too many arguments") if self.lastEvent is None: raise Cmd...
t - trace at the current assembly instruction trace - trace at the current assembly instruction
Below is the the instruction that describes the task: ### Input: t - trace at the current assembly instruction trace - trace at the current assembly instruction ### Response: def do_trace(self, arg): """ t - trace at the current assembly instruction trace - trace at the current asse...
def parseExternalSubset(self, ExternalID, SystemID): """parse Markup declarations from an external subset [30] extSubset ::= textDecl? extSubsetDecl [31] extSubsetDecl ::= (markupdecl | conditionalSect | PEReference | S) * """ libxml2mod.xmlParseExternalSubset(self._o, ExternalID,...
parse Markup declarations from an external subset [30] extSubset ::= textDecl? extSubsetDecl [31] extSubsetDecl ::= (markupdecl | conditionalSect | PEReference | S) *
Below is the the instruction that describes the task: ### Input: parse Markup declarations from an external subset [30] extSubset ::= textDecl? extSubsetDecl [31] extSubsetDecl ::= (markupdecl | conditionalSect | PEReference | S) * ### Response: def parseExternalSubset(self, ExternalID, Syst...
def read(self, size=None): """ Read `size` of bytes.""" if size is None: return self.buf.read() + self.open_file.read() contents = self.buf.read(size) if len(contents) < size: contents += self.open_file.read(size - len(contents)) return contents
Read `size` of bytes.
Below is the the instruction that describes the task: ### Input: Read `size` of bytes. ### Response: def read(self, size=None): """ Read `size` of bytes.""" if size is None: return self.buf.read() + self.open_file.read() contents = self.buf.read(size) if len(contents) < size: contents +...
def _preSynapticTRNCells(self, i, j): """ Given a relay cell at the given coordinate, return a list of the (x,y) coordinates of all TRN cells that project to it. This assumes a 3X3 fan-in. :param i, j: relay cell Coordinates :return: """ xmin = max(i - 1, 0) xmax = min(i + 2, self.trnW...
Given a relay cell at the given coordinate, return a list of the (x,y) coordinates of all TRN cells that project to it. This assumes a 3X3 fan-in. :param i, j: relay cell Coordinates :return:
Below is the the instruction that describes the task: ### Input: Given a relay cell at the given coordinate, return a list of the (x,y) coordinates of all TRN cells that project to it. This assumes a 3X3 fan-in. :param i, j: relay cell Coordinates :return: ### Response: def _preSynapticTRNCells(self,...
def open(self, url): """ Open a document at the specified URL. The document URL's needs not contain a protocol identifier, and if it does, that protocol identifier is ignored when looking up the store content. Missing documents referenced using the internal 'suds' proto...
Open a document at the specified URL. The document URL's needs not contain a protocol identifier, and if it does, that protocol identifier is ignored when looking up the store content. Missing documents referenced using the internal 'suds' protocol are reported by raising an ex...
Below is the the instruction that describes the task: ### Input: Open a document at the specified URL. The document URL's needs not contain a protocol identifier, and if it does, that protocol identifier is ignored when looking up the store content. Missing documents referenced usi...
def _expand(dat, counts, start, end): """ expand the same counts from start to end """ for pos in range(start, end): for s in counts: dat[s][pos] += counts[s] return dat
expand the same counts from start to end
Below is the the instruction that describes the task: ### Input: expand the same counts from start to end ### Response: def _expand(dat, counts, start, end): """ expand the same counts from start to end """ for pos in range(start, end): for s in counts: dat[s][pos] += counts[s] ...
def _abort_all_transfers(self, exception): """ Abort any ongoing transfers and clear all buffers """ pending_reads = len(self._commands_to_read) # invalidate _transfer_list for transfer in self._transfer_list: transfer.add_error(exception) # clear all ...
Abort any ongoing transfers and clear all buffers
Below is the the instruction that describes the task: ### Input: Abort any ongoing transfers and clear all buffers ### Response: def _abort_all_transfers(self, exception): """ Abort any ongoing transfers and clear all buffers """ pending_reads = len(self._commands_to_read) #...
def build_ast(expression, debug = False): """build an AST from an Excel formula expression in reverse polish notation""" #use a directed graph to store the tree G = DiGraph() stack = [] for n in expression: # Since the graph does not maintain the order of adding nodes/edges # add a...
build an AST from an Excel formula expression in reverse polish notation
Below is the the instruction that describes the task: ### Input: build an AST from an Excel formula expression in reverse polish notation ### Response: def build_ast(expression, debug = False): """build an AST from an Excel formula expression in reverse polish notation""" #use a directed graph to store the...
def translate_url(context, language): """ Translates the current URL for the given language code, eg: {% translate_url de %} """ try: request = context["request"] except KeyError: return "" view = resolve(request.path) current_language = translation.get_language() ...
Translates the current URL for the given language code, eg: {% translate_url de %}
Below is the the instruction that describes the task: ### Input: Translates the current URL for the given language code, eg: {% translate_url de %} ### Response: def translate_url(context, language): """ Translates the current URL for the given language code, eg: {% translate_url de %} ...
def commit(self): """Makes a ``ReadModifyWriteRow`` API request. This commits modifications made by :meth:`append_cell_value` and :meth:`increment_cell_value`. If no modifications were made, makes no API request and just returns ``{}``. Modifies a row atomically, reading the la...
Makes a ``ReadModifyWriteRow`` API request. This commits modifications made by :meth:`append_cell_value` and :meth:`increment_cell_value`. If no modifications were made, makes no API request and just returns ``{}``. Modifies a row atomically, reading the latest existing timesta...
Below is the the instruction that describes the task: ### Input: Makes a ``ReadModifyWriteRow`` API request. This commits modifications made by :meth:`append_cell_value` and :meth:`increment_cell_value`. If no modifications were made, makes no API request and just returns ``{}``. M...
def most_recent_submission(project, group): """Return the most recent submission for the user and project id.""" return (Submission.query_by(project=project, group=group) .order_by(Submission.created_at.desc()).first())
Return the most recent submission for the user and project id.
Below is the the instruction that describes the task: ### Input: Return the most recent submission for the user and project id. ### Response: def most_recent_submission(project, group): """Return the most recent submission for the user and project id.""" return (Submission.query_by(project=project,...
def bkg_subtract(self, analyte, bkg, ind=None, focus_stage='despiked'): """ Subtract provided background from signal (focus stage). Results is saved in new 'bkgsub' focus stage Returns ------- None """ if 'bkgsub' not in self.data.keys(): sel...
Subtract provided background from signal (focus stage). Results is saved in new 'bkgsub' focus stage Returns ------- None
Below is the the instruction that describes the task: ### Input: Subtract provided background from signal (focus stage). Results is saved in new 'bkgsub' focus stage Returns ------- None ### Response: def bkg_subtract(self, analyte, bkg, ind=None, focus_stage='despiked'): ...
def sink_update( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: update a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type project: str :param project: ID of the p...
API call: update a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :type ...
Below is the the instruction that describes the task: ### Input: API call: update a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type project: str :param project: ID of the project containing the sink. :type sink_nam...
def parse_authentication_request(self, request_body, http_headers=None): # type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest """ Parses and verifies an authentication request. :param request_body: urlencoded authentication request :param http_heade...
Parses and verifies an authentication request. :param request_body: urlencoded authentication request :param http_headers: http headers
Below is the the instruction that describes the task: ### Input: Parses and verifies an authentication request. :param request_body: urlencoded authentication request :param http_headers: http headers ### Response: def parse_authentication_request(self, request_body, http_headers=None): # ...
def walk_dir(path, args, state): """ Check all files in `path' to see if there is any requests that we should send out on the bus. """ if args.debug: sys.stderr.write("Walking %s\n" % path) for root, _dirs, files in os.walk(path): if not safe_process_files(root, files, args, sta...
Check all files in `path' to see if there is any requests that we should send out on the bus.
Below is the the instruction that describes the task: ### Input: Check all files in `path' to see if there is any requests that we should send out on the bus. ### Response: def walk_dir(path, args, state): """ Check all files in `path' to see if there is any requests that we should send out on the ...
def train_set_producer(socket, train_archive, patch_archive, wnid_map): """Load/send images from the training set TAR file or patch images. Parameters ---------- socket : :class:`zmq.Socket` PUSH socket on which to send loaded images. train_archive : str or file-like object Filenam...
Load/send images from the training set TAR file or patch images. Parameters ---------- socket : :class:`zmq.Socket` PUSH socket on which to send loaded images. train_archive : str or file-like object Filename or file handle for the TAR archive of training images. patch_archive : s...
Below is the the instruction that describes the task: ### Input: Load/send images from the training set TAR file or patch images. Parameters ---------- socket : :class:`zmq.Socket` PUSH socket on which to send loaded images. train_archive : str or file-like object Filename or file ...