code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def log_once(log_func, msg, *args, **kwargs): """"Logs a message only once.""" if msg not in _LOG_ONCE_SEEN: log_func(msg, *args, **kwargs) # Key on the message, ignoring args. This should fit most use cases. _LOG_ONCE_SEEN.add(msg)
Logs a message only once.
Below is the the instruction that describes the task: ### Input: Logs a message only once. ### Response: def log_once(log_func, msg, *args, **kwargs): """"Logs a message only once.""" if msg not in _LOG_ONCE_SEEN: log_func(msg, *args, **kwargs) # Key on the message, ignoring args. This should fit most ...
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Calculates a message digest hash for every file in a directory or ' 'storage media image.')) argument_parser.add_argument( 'source',...
The main program function. Returns: bool: True if successful or False if not.
Below is the the instruction that describes the task: ### Input: The main program function. Returns: bool: True if successful or False if not. ### Response: def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser...
def setup_destination(self): """Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure. """ # Do we have a separate identifier? if (not self.identifier): # No separate identi...
Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure.
Below is the the instruction that describes the task: ### Input: Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure. ### Response: def setup_destination(self): """Setup output directory based on self.d...
def cleanOptions(options): """ Takes an options dict and returns a tuple containing the daemonize boolean, the reload boolean, and the parsed list of cleaned options as would be expected to be passed to hx """ _reload = options.pop('reload') dev = options.pop('dev') opts = [] store_t...
Takes an options dict and returns a tuple containing the daemonize boolean, the reload boolean, and the parsed list of cleaned options as would be expected to be passed to hx
Below is the the instruction that describes the task: ### Input: Takes an options dict and returns a tuple containing the daemonize boolean, the reload boolean, and the parsed list of cleaned options as would be expected to be passed to hx ### Response: def cleanOptions(options): """ Takes an optio...
def _ConvertValueBinaryDataToUBInt64(self, value): """Converts a binary data value into an integer. Args: value (bytes): binary data value containing an unsigned 64-bit big-endian integer. Returns: int: integer representation of binary data value or None if value is not set...
Converts a binary data value into an integer. Args: value (bytes): binary data value containing an unsigned 64-bit big-endian integer. Returns: int: integer representation of binary data value or None if value is not set. Raises: ParseError: if the integer value cann...
Below is the the instruction that describes the task: ### Input: Converts a binary data value into an integer. Args: value (bytes): binary data value containing an unsigned 64-bit big-endian integer. Returns: int: integer representation of binary data value or None if value is ...
def setup(menu=True): """Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Attributes: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to connect with Pyblish QML, def...
Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Attributes: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to connect with Pyblish QML, default provided by ...
Below is the the instruction that describes the task: ### Input: Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Attributes: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an availab...
def create_basic_op_node(op_name, node, kwargs): """Helper function to create a basic operator node that doesn't contain op specific attrs""" name, input_nodes, _ = get_inputs(node, kwargs) node = onnx.helper.make_node( op_name, input_nodes, [name], name=name ) r...
Helper function to create a basic operator node that doesn't contain op specific attrs
Below is the the instruction that describes the task: ### Input: Helper function to create a basic operator node that doesn't contain op specific attrs ### Response: def create_basic_op_node(op_name, node, kwargs): """Helper function to create a basic operator node that doesn't contain op specific attr...
def load_and_preprocess_imdb_data(n_gram=None): """Load IMDb data and augment with hashed n-gram features.""" X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(nb_words=VOCAB_SIZE) if n_gram is not None: X_train = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x i...
Load IMDb data and augment with hashed n-gram features.
Below is the the instruction that describes the task: ### Input: Load IMDb data and augment with hashed n-gram features. ### Response: def load_and_preprocess_imdb_data(n_gram=None): """Load IMDb data and augment with hashed n-gram features.""" X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(...
def create_new_metadata(self, rsa_public_key): # type: (EncryptionMetadata, # cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey) # -> None """Create new metadata entries for encryption (upload) :param EncryptionMetadata self: this :param cryptograph...
Create new metadata entries for encryption (upload) :param EncryptionMetadata self: this :param cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey: rsa public key
Below is the the instruction that describes the task: ### Input: Create new metadata entries for encryption (upload) :param EncryptionMetadata self: this :param cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey: rsa public key ### Response: def create_new_metadata(self, rsa_pub...
def idle_task(self): '''run periodic tasks''' if self.starting_motor: if self.gasheli_settings.ignition_disable_time > 0: elapsed = time.time() - self.motor_t1 if elapsed >= self.gasheli_settings.ignition_disable_time: self.module('rc').set...
run periodic tasks
Below is the the instruction that describes the task: ### Input: run periodic tasks ### Response: def idle_task(self): '''run periodic tasks''' if self.starting_motor: if self.gasheli_settings.ignition_disable_time > 0: elapsed = time.time() - self.motor_t1 ...
def applications(self): """returns all the group applications to join""" url = self._url + "/applications" params = {"f" : "json"} res = self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy...
returns all the group applications to join
Below is the the instruction that describes the task: ### Input: returns all the group applications to join ### Response: def applications(self): """returns all the group applications to join""" url = self._url + "/applications" params = {"f" : "json"} res = self._get(url=url, ...
def real_python3(python, version_dict): """ Determine the path of the real python executable, which is then used for venv creation. This is necessary, because an active virtualenv environment will cause venv creation to malfunction. By getting the path of the real executable, this issue is bypassed....
Determine the path of the real python executable, which is then used for venv creation. This is necessary, because an active virtualenv environment will cause venv creation to malfunction. By getting the path of the real executable, this issue is bypassed. The provided `python` path may be either: ...
Below is the the instruction that describes the task: ### Input: Determine the path of the real python executable, which is then used for venv creation. This is necessary, because an active virtualenv environment will cause venv creation to malfunction. By getting the path of the real executable, this i...
def delete_project(self, id): """ Delete a project from the Gitlab server Gitlab currently returns a Boolean True if the deleted and as such we return an empty Dictionary :param id: The ID of the project or NAMESPACE/PROJECT_NAME :return: Dictionary :raise: Http...
Delete a project from the Gitlab server Gitlab currently returns a Boolean True if the deleted and as such we return an empty Dictionary :param id: The ID of the project or NAMESPACE/PROJECT_NAME :return: Dictionary :raise: HttpError: If invalid response returned
Below is the the instruction that describes the task: ### Input: Delete a project from the Gitlab server Gitlab currently returns a Boolean True if the deleted and as such we return an empty Dictionary :param id: The ID of the project or NAMESPACE/PROJECT_NAME :return: Dictionary ...
def shuffle(qsize=1024, iterable=None): """ add example :param qsize: :param iterable: :return: """ @iterflow def shuffleit(it): from random import randrange q = [] for i, d in enumerate(it): q.insert(randrange(0, len(q) + 1), d) if i < q...
add example :param qsize: :param iterable: :return:
Below is the the instruction that describes the task: ### Input: add example :param qsize: :param iterable: :return: ### Response: def shuffle(qsize=1024, iterable=None): """ add example :param qsize: :param iterable: :return: """ @iterflow def shuffleit(it): fr...
def _create_model(self, X, Y): """ Creates the model given some input data X and Y. """ # --- define kernel self.input_dim = X.shape[1] if self.kernel is None: kern = GPy.kern.Matern52(self.input_dim, variance=1., ARD=self.ARD) #+ GPy.kern.Bias(self.input_dim...
Creates the model given some input data X and Y.
Below is the the instruction that describes the task: ### Input: Creates the model given some input data X and Y. ### Response: def _create_model(self, X, Y): """ Creates the model given some input data X and Y. """ # --- define kernel self.input_dim = X.shape[1] if...
def sequence(self, other, exclude_list_fields=None): """Return a copy of this object which combines all the fields common to both `self` and `other`. List fields will be concatenated. The return type of this method is the type of `self` (or whatever `.copy()` returns), but the `other` argument can be ...
Return a copy of this object which combines all the fields common to both `self` and `other`. List fields will be concatenated. The return type of this method is the type of `self` (or whatever `.copy()` returns), but the `other` argument can be any `_ExtensibleAlgebraic` instance.
Below is the the instruction that describes the task: ### Input: Return a copy of this object which combines all the fields common to both `self` and `other`. List fields will be concatenated. The return type of this method is the type of `self` (or whatever `.copy()` returns), but the `other` argumen...
def average_neighbor_distance(points, num_neigh): """! @brief Returns average distance for establish links between specified number of nearest neighbors. @param[in] points (list): Input data, list of points where each point represented by list. @param[in] num_neigh (uint): Number of neighbors ...
! @brief Returns average distance for establish links between specified number of nearest neighbors. @param[in] points (list): Input data, list of points where each point represented by list. @param[in] num_neigh (uint): Number of neighbors that should be used for distance calculation. @...
Below is the the instruction that describes the task: ### Input: ! @brief Returns average distance for establish links between specified number of nearest neighbors. @param[in] points (list): Input data, list of points where each point represented by list. @param[in] num_neigh (uint): Number of...
def set_hook_data(self, key, data): """Set hook data for the given key. Args: key(str): The key to store the hook data in. data(:class:`collections.Mapping`): A dictionary of data to store, as returned from a hook. """ if not isinstance(data, col...
Set hook data for the given key. Args: key(str): The key to store the hook data in. data(:class:`collections.Mapping`): A dictionary of data to store, as returned from a hook.
Below is the the instruction that describes the task: ### Input: Set hook data for the given key. Args: key(str): The key to store the hook data in. data(:class:`collections.Mapping`): A dictionary of data to store, as returned from a hook. ### Response: def set_hoo...
def delete_record(self, record_id): """ Delete a record with record_id. """ self._delete( urljoin(self.base_url, "informationobjects/{}".format(record_id)), expected_response=204, ) return {"status": "Deleted"}
Delete a record with record_id.
Below is the the instruction that describes the task: ### Input: Delete a record with record_id. ### Response: def delete_record(self, record_id): """ Delete a record with record_id. """ self._delete( urljoin(self.base_url, "informationobjects/{}".format(record_id)), ...
def get_by_id(self, reply_id): ''' Get the reply by id. ''' reply = MReply.get_by_uid(reply_id) logger.info('get_reply: {0}'.format(reply_id)) self.render('misc/reply/show_reply.html', reply=reply, username=reply.user_name, ...
Get the reply by id.
Below is the the instruction that describes the task: ### Input: Get the reply by id. ### Response: def get_by_id(self, reply_id): ''' Get the reply by id. ''' reply = MReply.get_by_uid(reply_id) logger.info('get_reply: {0}'.format(reply_id)) self.render('misc/reply...
def strict_dependencies(self, dep_context): """ :param dep_context: A DependencyContext with configuration for the request. :return: targets that this target "strictly" depends on. This set of dependencies contains only directly declared dependencies, with two exceptions: 1) aliases are expand...
:param dep_context: A DependencyContext with configuration for the request. :return: targets that this target "strictly" depends on. This set of dependencies contains only directly declared dependencies, with two exceptions: 1) aliases are expanded transitively 2) the strict_dependencies of ta...
Below is the the instruction that describes the task: ### Input: :param dep_context: A DependencyContext with configuration for the request. :return: targets that this target "strictly" depends on. This set of dependencies contains only directly declared dependencies, with two exceptions: 1) alias...
def replace_u_start_month(month): """Find the earliest legitimate month.""" month = month.lstrip('-') if month == 'uu' or month == '0u': return '01' if month == 'u0': return '10' return month.replace('u', '0')
Find the earliest legitimate month.
Below is the the instruction that describes the task: ### Input: Find the earliest legitimate month. ### Response: def replace_u_start_month(month): """Find the earliest legitimate month.""" month = month.lstrip('-') if month == 'uu' or month == '0u': return '01' if month == 'u0': r...
def extract_altitude(self): ''' Extract altitude ''' altitude_ref = { 0: 1, 1: -1} fields = ['GPS GPSAltitude', 'EXIF GPS GPSAltitude'] refs = ['GPS GPSAltitudeRef', 'EXIF GPS GPSAltitudeRef'] altitude, _ = self._extract_alternative_fields(...
Extract altitude
Below is the the instruction that describes the task: ### Input: Extract altitude ### Response: def extract_altitude(self): ''' Extract altitude ''' altitude_ref = { 0: 1, 1: -1} fields = ['GPS GPSAltitude', 'EXIF GPS GPSAltitude'] refs = ['GP...
def _set_microcode(self, v, load=False): """ Setter method for microcode, mapped from YANG variable /firmware/peripheral_update/microcode (container) If this variable is read-only (config: false) in the source YANG file, then _set_microcode is considered as a private method. Backends looking to popu...
Setter method for microcode, mapped from YANG variable /firmware/peripheral_update/microcode (container) If this variable is read-only (config: false) in the source YANG file, then _set_microcode is considered as a private method. Backends looking to populate this variable should do so via calling thisO...
Below is the the instruction that describes the task: ### Input: Setter method for microcode, mapped from YANG variable /firmware/peripheral_update/microcode (container) If this variable is read-only (config: false) in the source YANG file, then _set_microcode is considered as a private method. Backends...
def convert_to_numpy_bytes(data, length=None): """ Decodes data to Numpy UTF-8 econded string (bytes\_). Decodes `data` to a Numpy UTF-8 encoded string, which is ``numpy.bytes_``, or an array of them in which case it will be ASCII encoded instead. If it can't be decoded, it is returned as is. Unsig...
Decodes data to Numpy UTF-8 econded string (bytes\_). Decodes `data` to a Numpy UTF-8 encoded string, which is ``numpy.bytes_``, or an array of them in which case it will be ASCII encoded instead. If it can't be decoded, it is returned as is. Unsigned integers, Python string types (``str``, ``bytes``),...
Below is the the instruction that describes the task: ### Input: Decodes data to Numpy UTF-8 econded string (bytes\_). Decodes `data` to a Numpy UTF-8 encoded string, which is ``numpy.bytes_``, or an array of them in which case it will be ASCII encoded instead. If it can't be decoded, it is returned as...
def to_bytes(self, frame, state): """ Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. ...
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
Below is the the instruction that describes the task: ### Input: Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``F...
def encode_args(args, extra=False): """ Encode a list of arguments """ if not args: return '' methodargs = ', '.join([encode(a) for a in args]) if extra: methodargs += ', ' return methodargs
Encode a list of arguments
Below is the the instruction that describes the task: ### Input: Encode a list of arguments ### Response: def encode_args(args, extra=False): """ Encode a list of arguments """ if not args: return '' methodargs = ', '.join([encode(a) for a in args]) if extra: methodargs += ...
def discretize(self, method, *args, **kwargs): """ Discretizes the continuous distribution into discrete probability masses using various methods. Parameters ---------- method : A Discretizer Class from pgmpy.discretize *args, **kwargs: The parameter...
Discretizes the continuous distribution into discrete probability masses using various methods. Parameters ---------- method : A Discretizer Class from pgmpy.discretize *args, **kwargs: The parameters to be given to the Discretizer Class. Returns --...
Below is the the instruction that describes the task: ### Input: Discretizes the continuous distribution into discrete probability masses using various methods. Parameters ---------- method : A Discretizer Class from pgmpy.discretize *args, **kwargs: The paramet...
def GetWSAActionInput(operation): """Find wsa:Action attribute, and return value or the default.""" attr = operation.input.action if attr is not None: return attr portType = operation.getPortType() targetNamespace = portType.getTargetNamespace() ptName = portType.name msgName = opera...
Find wsa:Action attribute, and return value or the default.
Below is the the instruction that describes the task: ### Input: Find wsa:Action attribute, and return value or the default. ### Response: def GetWSAActionInput(operation): """Find wsa:Action attribute, and return value or the default.""" attr = operation.input.action if attr is not None: retur...
def get_etag(file_path): """Return a strong Entity Tag for a (file)path. http://www.webdav.org/specs/rfc4918.html#etag Returns the following as entity tags:: Non-file - md5(pathname) Win32 - md5(pathname)-lastmodifiedtime-filesize Others - inode-lastmodifiedtime-filesize """ ...
Return a strong Entity Tag for a (file)path. http://www.webdav.org/specs/rfc4918.html#etag Returns the following as entity tags:: Non-file - md5(pathname) Win32 - md5(pathname)-lastmodifiedtime-filesize Others - inode-lastmodifiedtime-filesize
Below is the the instruction that describes the task: ### Input: Return a strong Entity Tag for a (file)path. http://www.webdav.org/specs/rfc4918.html#etag Returns the following as entity tags:: Non-file - md5(pathname) Win32 - md5(pathname)-lastmodifiedtime-filesize Others - inod...
def parse_hpo_gene(hpo_line): """Parse hpo gene information Args: hpo_line(str): A iterable with hpo phenotype lines Yields: hpo_info(dict) """ if not len(hpo_line) > 3: return {} hpo_line = hpo_line.rstrip().split('\t') hpo_info = {} hpo...
Parse hpo gene information Args: hpo_line(str): A iterable with hpo phenotype lines Yields: hpo_info(dict)
Below is the the instruction that describes the task: ### Input: Parse hpo gene information Args: hpo_line(str): A iterable with hpo phenotype lines Yields: hpo_info(dict) ### Response: def parse_hpo_gene(hpo_line): """Parse hpo gene information Ar...
def save_libsvm(X, y, path): """Save data as a LibSVM file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the CSV file to save data. """ dump_svmlight_file(X, y, path, zero_based=False)
Save data as a LibSVM file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the CSV file to save data.
Below is the the instruction that describes the task: ### Input: Save data as a LibSVM file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the CSV file to save data. ### Response: def save_libsvm(X, y, path): """Save data as...
def spawn(self, function, *args, **kwargs): # type: (Callable[..., Any], *Any, **Any) -> Spawned """Runs the function in a worker thread, returning a Result object Args: function: Function to run args: Positional arguments to run the function with kwargs: Key...
Runs the function in a worker thread, returning a Result object Args: function: Function to run args: Positional arguments to run the function with kwargs: Keyword arguments to run the function with Returns: Spawned: Something you can call wait(timeout) ...
Below is the the instruction that describes the task: ### Input: Runs the function in a worker thread, returning a Result object Args: function: Function to run args: Positional arguments to run the function with kwargs: Keyword arguments to run the function with ...
def get_block(self, usage_id, for_parent=None): """ Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data. """ def_id = self.id_reader.get_definition_id(usage_id) try: block_type = self.id_reader.get_block_type(de...
Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data.
Below is the the instruction that describes the task: ### Input: Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data. ### Response: def get_block(self, usage_id, for_parent=None): """ Create an XBlock instance in this runtime. The `u...
def before_log(logger, log_level): """Before call strategy that logs to some logger the attempt.""" def log_it(retry_state): logger.log(log_level, "Starting call to '%s', this is the %s time calling it.", _utils.get_callback_name(retry_state.fn), ...
Before call strategy that logs to some logger the attempt.
Below is the the instruction that describes the task: ### Input: Before call strategy that logs to some logger the attempt. ### Response: def before_log(logger, log_level): """Before call strategy that logs to some logger the attempt.""" def log_it(retry_state): logger.log(log_level, ...
def async_comp_check(self, original, loc, tokens): """Check for Python 3.6 async comprehension.""" return self.check_py("36", "async comprehension", original, loc, tokens)
Check for Python 3.6 async comprehension.
Below is the the instruction that describes the task: ### Input: Check for Python 3.6 async comprehension. ### Response: def async_comp_check(self, original, loc, tokens): """Check for Python 3.6 async comprehension.""" return self.check_py("36", "async comprehension", original, loc, tokens)
def on_packet(packet): """ Callback function that is called everytime a data packet arrives from QTM """ print("Framenumber: {}".format(packet.framenumber)) header, markers = packet.get_3d_markers() print("Component info: {}".format(header)) for marker in markers: print("\t", marker)
Callback function that is called everytime a data packet arrives from QTM
Below is the the instruction that describes the task: ### Input: Callback function that is called everytime a data packet arrives from QTM ### Response: def on_packet(packet): """ Callback function that is called everytime a data packet arrives from QTM """ print("Framenumber: {}".format(packet.framenumber...
def _propagate_up(self, handle, target_id, name=None): """ In a non-master context, propagate an update towards the master. :param int handle: :data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE` :param int target_id: ID of the connecting or disconnec...
In a non-master context, propagate an update towards the master. :param int handle: :data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE` :param int target_id: ID of the connecting or disconnecting context. :param str name: For :data:`mitogen.core....
Below is the the instruction that describes the task: ### Input: In a non-master context, propagate an update towards the master. :param int handle: :data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE` :param int target_id: ID of the connecting or disconnecting c...
def _read(self): ''' Read in from disk ''' if msgpack is None: log.error('Cache cannot be read from the disk: msgpack is missing') elif not os.path.exists(self._path): log.debug('Cache path does not exist for reading: %s', self._path) else: ...
Read in from disk
Below is the the instruction that describes the task: ### Input: Read in from disk ### Response: def _read(self): ''' Read in from disk ''' if msgpack is None: log.error('Cache cannot be read from the disk: msgpack is missing') elif not os.path.exists(self._path)...
def bugreport(dest_file="default.log"): """ Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT] try: dest_file_handler = open(dest_file,...
Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution
Below is the the instruction that describes the task: ### Input: Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution ### Response: def bugreport(dest_file="default.log"): """ Prints dumpsys, dumpstate, and logcat data ...
def _pick_best_quality_score(vrn_file): """Flexible quality score selection, picking the best available. Implementation based on discussion: https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249 (RTG=AVR/GATK=VQSLOD/MuTect=t_lod_fstar, otherwise...
Flexible quality score selection, picking the best available. Implementation based on discussion: https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249 (RTG=AVR/GATK=VQSLOD/MuTect=t_lod_fstar, otherwise GQ, otherwise QUAL, otherwise DP.) For Mu...
Below is the the instruction that describes the task: ### Input: Flexible quality score selection, picking the best available. Implementation based on discussion: https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249 (RTG=AVR/GATK=VQSLOD/MuTect=...
def value(self, val): """Set the color using length-N array of (from HSV)""" hsv = self._hsv hsv[:, 2] = _array_clip_val(val) self.rgba = _hsv_to_rgb(hsv)
Set the color using length-N array of (from HSV)
Below is the the instruction that describes the task: ### Input: Set the color using length-N array of (from HSV) ### Response: def value(self, val): """Set the color using length-N array of (from HSV)""" hsv = self._hsv hsv[:, 2] = _array_clip_val(val) self.rgba = _hsv_to_rgb(hsv)
def patch_request(self, id_or_uri, body, timeout=-1, custom_headers=None): """ Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. body: Patch request bo...
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. body: Patch request body timeout: Timeout in seconds. Wait for task completion by default. The timeout do...
Below is the the instruction that describes the task: ### Input: Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. body: Patch request body timeout: Ti...
def update_team_days_off(self, days_off_patch, team_context, iteration_id): """UpdateTeamDaysOff. Set a team's days off for an iteration :param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_0.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of...
UpdateTeamDaysOff. Set a team's days off for an iteration :param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_0.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of start and end dates :param :class:`<TeamContext> <azure.devops.v5_0.work.model...
Below is the the instruction that describes the task: ### Input: UpdateTeamDaysOff. Set a team's days off for an iteration :param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_0.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of start and end dat...
def read_block_data(self, block): """Read LEB data from file Argument: Obj:block -- Block data is desired for. """ self.seek(block.file_offset + block.ec_hdr.data_offset) buf = self._fhandle.read(block.size - block.ec_hdr.data_offset - block.vid_hdr.data_pad) ...
Read LEB data from file Argument: Obj:block -- Block data is desired for.
Below is the the instruction that describes the task: ### Input: Read LEB data from file Argument: Obj:block -- Block data is desired for. ### Response: def read_block_data(self, block): """Read LEB data from file Argument: Obj:block -- Block data is desire...
def to_staff(email_class, **data): """ Email staff users """ for user in get_user_model().objects.filter(is_staff=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language()...
Email staff users
Below is the the instruction that describes the task: ### Input: Email staff users ### Response: def to_staff(email_class, **data): """ Email staff users """ for user in get_user_model().objects.filter(is_staff=True): try: email_class().send([user.email], user.language, **data) ...
def OSXEnumerateRunningServicesFromClient(args): """Get running launchd jobs. Args: args: Unused. Yields: `rdf_client.OSXServiceInformation` instances. Raises: UnsupportedOSVersionError: for OS X earlier than 10.6. """ del args # Unused. osx_version = client_utils_osx.OSXVersion() vers...
Get running launchd jobs. Args: args: Unused. Yields: `rdf_client.OSXServiceInformation` instances. Raises: UnsupportedOSVersionError: for OS X earlier than 10.6.
Below is the the instruction that describes the task: ### Input: Get running launchd jobs. Args: args: Unused. Yields: `rdf_client.OSXServiceInformation` instances. Raises: UnsupportedOSVersionError: for OS X earlier than 10.6. ### Response: def OSXEnumerateRunningServicesFromClient(args): ...
def _token_to_subtoken_ids(self, token): """Converts token to a list of subtoken ids. Args: token: a string. Returns: a list of integers in the range [0, vocab_size) """ cache_location = hash(token) % self._cache_size cache_key, cache_value = self._cache[cache_location] if cache...
Converts token to a list of subtoken ids. Args: token: a string. Returns: a list of integers in the range [0, vocab_size)
Below is the the instruction that describes the task: ### Input: Converts token to a list of subtoken ids. Args: token: a string. Returns: a list of integers in the range [0, vocab_size) ### Response: def _token_to_subtoken_ids(self, token): """Converts token to a list of subtoken ids. ...
def LOGGER(filename): """creates a logger with the given name. You can use it as follows:: log = cloudmesh.common.LOGGER(__file__) log.error("this is an error") log.info("this is an info") log.warning("this is a warning") """ pwd = os.getcwd() name = filename.replace(p...
creates a logger with the given name. You can use it as follows:: log = cloudmesh.common.LOGGER(__file__) log.error("this is an error") log.info("this is an info") log.warning("this is a warning")
Below is the the instruction that describes the task: ### Input: creates a logger with the given name. You can use it as follows:: log = cloudmesh.common.LOGGER(__file__) log.error("this is an error") log.info("this is an info") log.warning("this is a warning") ### Response: def L...
def diff_compute(self, text1, text2, checklines, deadline): """Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't r...
Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't run a line-level diff first to identify the changed areas. ...
Below is the the instruction that describes the task: ### Input: Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't...
def class_get_help(cls, inst=None): """Get the help string for this class in ReST format. If `inst` is given, it's current trait values will be used in place of class defaults. """ assert inst is None or isinstance(inst, cls) cls_traits = cls.class_traits(config=...
Get the help string for this class in ReST format. If `inst` is given, it's current trait values will be used in place of class defaults.
Below is the the instruction that describes the task: ### Input: Get the help string for this class in ReST format. If `inst` is given, it's current trait values will be used in place of class defaults. ### Response: def class_get_help(cls, inst=None): """Get the help string for th...
def _get_goid2dbids(associations): """Return gene2go data for user-specified taxids.""" go2ids = cx.defaultdict(set) for ntd in associations: go2ids[ntd.GO_ID].add(ntd.DB_ID) return dict(go2ids)
Return gene2go data for user-specified taxids.
Below is the the instruction that describes the task: ### Input: Return gene2go data for user-specified taxids. ### Response: def _get_goid2dbids(associations): """Return gene2go data for user-specified taxids.""" go2ids = cx.defaultdict(set) for ntd in associations: go2ids[ntd....
def ObjectEnum(ctx): """Object Enumeration. Should export the whole list from the game for the best accuracy. """ return Enum( ctx, villager_male=83, villager_female=293, scout_cavalry=448, eagle_warrior=751, king=434, flare=332, relic=285...
Object Enumeration. Should export the whole list from the game for the best accuracy.
Below is the the instruction that describes the task: ### Input: Object Enumeration. Should export the whole list from the game for the best accuracy. ### Response: def ObjectEnum(ctx): """Object Enumeration. Should export the whole list from the game for the best accuracy. """ return Enum( ...
def _collect_fields(self): """ Iterate over all Field objects within, including multi fields. """ for f in itervalues(self.properties.to_dict()): yield f # multi fields if hasattr(f, 'fields'): for inner_f in itervalues(f.fields.to_dict()): ...
Iterate over all Field objects within, including multi fields.
Below is the the instruction that describes the task: ### Input: Iterate over all Field objects within, including multi fields. ### Response: def _collect_fields(self): """ Iterate over all Field objects within, including multi fields. """ for f in itervalues(self.properties.to_dict()): ...
def packed_parallel_tsv_dataset(filenames=gin.REQUIRED, dataset_split=gin.REQUIRED, batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, vocabulary=gin.REQUIRED, ...
Reads parallel tab-separated text file. One example per line.
Below is the the instruction that describes the task: ### Input: Reads parallel tab-separated text file. One example per line. ### Response: def packed_parallel_tsv_dataset(filenames=gin.REQUIRED, dataset_split=gin.REQUIRED, batch_size=gin.REQUIRED, ...
def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.lingeling and self.status == False: return pysolvers.lingeling_core(self.lingeling, self.prev_assumps)
Get an unsatisfiable core if the formula was previously unsatisfied.
Below is the the instruction that describes the task: ### Input: Get an unsatisfiable core if the formula was previously unsatisfied. ### Response: def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.l...
def decode_aes256_base64_auto(data, encryption_key): """Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data.""" assert isinstance(data, bytes) length = len(data) if length == 0: return b'' elif data[0] == b'!'[0]: return decode_aes256_cbc_base64(data, encrypti...
Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data.
Below is the the instruction that describes the task: ### Input: Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data. ### Response: def decode_aes256_base64_auto(data, encryption_key): """Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data.""" assert isinstance...
def determine_selection_of_iterable_values_from_config(config: DictLike, possible_iterables: Mapping[str, Type[enum.Enum]]) -> Dict[str, List[Any]]: """ Determine iterable values to use to create objects for a given configuration. All values of an iterable can be included be setting the value to ``True`` (Not ...
Determine iterable values to use to create objects for a given configuration. All values of an iterable can be included be setting the value to ``True`` (Not as a single value list, but as the only value.). Alternatively, an iterator can be disabled by setting the value to ``False``. Args: config:...
Below is the the instruction that describes the task: ### Input: Determine iterable values to use to create objects for a given configuration. All values of an iterable can be included be setting the value to ``True`` (Not as a single value list, but as the only value.). Alternatively, an iterator can be d...
def store(self): """ Store and return packages for upgrading """ data = repo_data(self.PACKAGES_TXT, "slack", self.flag) black = BlackList().packages(pkgs=data[0], repo="slack") for name, loc, comp, uncomp in zip(data[0], data[1], data[2], data[3]): status(0.0...
Store and return packages for upgrading
Below is the the instruction that describes the task: ### Input: Store and return packages for upgrading ### Response: def store(self): """ Store and return packages for upgrading """ data = repo_data(self.PACKAGES_TXT, "slack", self.flag) black = BlackList().packages(pkgs=d...
def _gorg(a): """Return the farthest origin of a generic class (internal helper).""" assert isinstance(a, GenericMeta) while a.__origin__ is not None: a = a.__origin__ return a
Return the farthest origin of a generic class (internal helper).
Below is the the instruction that describes the task: ### Input: Return the farthest origin of a generic class (internal helper). ### Response: def _gorg(a): """Return the farthest origin of a generic class (internal helper).""" assert isinstance(a, GenericMeta) while a.__origin__ is not None: ...
def get_import_data_url(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the import data url """ return get_data_url(deployment_name, endpoint_type='http-import', app_url=app_url, ...
return the import data url
Below is the the instruction that describes the task: ### Input: return the import data url ### Response: def get_import_data_url(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the import data url """ return get_data_url(d...
def patch(self, resource_endpoint, data={}): """Don't use it.""" url = self._create_request_url(resource_endpoint) return req.patch(url, headers=self.auth_header, json=data)
Don't use it.
Below is the the instruction that describes the task: ### Input: Don't use it. ### Response: def patch(self, resource_endpoint, data={}): """Don't use it.""" url = self._create_request_url(resource_endpoint) return req.patch(url, headers=self.auth_header, json=data)
def get_session_list(self, account): """ 获取客服的会话列表 详情请参考 http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html :param account: 完整客服账号 :return: 客服的会话列表 """ res = self._get( 'https://api.weixin.qq.com/customservice/kfsession/getse...
获取客服的会话列表 详情请参考 http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html :param account: 完整客服账号 :return: 客服的会话列表
Below is the the instruction that describes the task: ### Input: 获取客服的会话列表 详情请参考 http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html :param account: 完整客服账号 :return: 客服的会话列表 ### Response: def get_session_list(self, account): """ 获取客服的会话列表 详情请...
def transfer(self, volume, source, dest, **kwargs): """ Transfer will move a volume of liquid from a source location(s) to a dest location(s). It is a higher-level command, incorporating other :any:`Pipette` commands, like :any:`aspirate` and :any:`dispense`, designed to make pro...
Transfer will move a volume of liquid from a source location(s) to a dest location(s). It is a higher-level command, incorporating other :any:`Pipette` commands, like :any:`aspirate` and :any:`dispense`, designed to make protocol writing easier at the cost of specificity. Parame...
Below is the the instruction that describes the task: ### Input: Transfer will move a volume of liquid from a source location(s) to a dest location(s). It is a higher-level command, incorporating other :any:`Pipette` commands, like :any:`aspirate` and :any:`dispense`, designed to make protoc...
def Nasv(macs,T): ''' Returns ------- Na*<sigma v> for MACS [mb] at T [K]. ''' Na = avogadro_constant k = boltzmann_constant vtherm=(2.*k*T/mass_H_atom)**0.5 s = macs*1.e-27 Nasv = s*vtherm*Na return Nasv
Returns ------- Na*<sigma v> for MACS [mb] at T [K].
Below is the the instruction that describes the task: ### Input: Returns ------- Na*<sigma v> for MACS [mb] at T [K]. ### Response: def Nasv(macs,T): ''' Returns ------- Na*<sigma v> for MACS [mb] at T [K]. ''' Na = avogadro_constant k = boltzmann_con...
def _is_valid_input(self, inpt, metadata, array): """The _is_valid_input method takes three arguments: the user input to be checked, the associated osid.Metadata object containing validation requirements and a boolean value indicating whether this is an array value. """ ...
The _is_valid_input method takes three arguments: the user input to be checked, the associated osid.Metadata object containing validation requirements and a boolean value indicating whether this is an array value.
Below is the the instruction that describes the task: ### Input: The _is_valid_input method takes three arguments: the user input to be checked, the associated osid.Metadata object containing validation requirements and a boolean value indicating whether this is an array value. ### Respons...
def set_parameter_scale(self, name, par, scale): """Update the scale of a parameter while keeping its value constant.""" name = self.roi.get_source_by_name(name).name idx = self.like.par_index(name, par) current_bounds = list(self.like.model[idx].getBounds()) current_scale = self...
Update the scale of a parameter while keeping its value constant.
Below is the the instruction that describes the task: ### Input: Update the scale of a parameter while keeping its value constant. ### Response: def set_parameter_scale(self, name, par, scale): """Update the scale of a parameter while keeping its value constant.""" name = self.roi.get_source_by_nam...
def allclose_variable(a, b, limits, rtols=None, atols=None): '''Returns True if two arrays are element-wise equal within several different tolerances. Tolerance values are always positive, usually very small. Based on numpy's allclose function. Only atols or rtols needs to be specified; both are u...
Returns True if two arrays are element-wise equal within several different tolerances. Tolerance values are always positive, usually very small. Based on numpy's allclose function. Only atols or rtols needs to be specified; both are used if given. Parameters ---------- a, b : array_li...
Below is the the instruction that describes the task: ### Input: Returns True if two arrays are element-wise equal within several different tolerances. Tolerance values are always positive, usually very small. Based on numpy's allclose function. Only atols or rtols needs to be specified; both are ...
def create_connections(self, connection_map): '''Create agent connections from a given connection map. :param dict connection_map: A map of connections to be created. Dictionary where keys are agent addresses and values are lists of (addr, attitude)-tuples suitable f...
Create agent connections from a given connection map. :param dict connection_map: A map of connections to be created. Dictionary where keys are agent addresses and values are lists of (addr, attitude)-tuples suitable for :meth:`~creamas.core.agent.CreativeAgent.a...
Below is the the instruction that describes the task: ### Input: Create agent connections from a given connection map. :param dict connection_map: A map of connections to be created. Dictionary where keys are agent addresses and values are lists of (addr, attitude)-tuples ...
def delete(self, table_name): """Delete a table in user's CARTO account. Args: table_name (str): Name of table to delete Returns: bool: `True` if table is removed """ dataset = Dataset(self, table_name) deleted = dataset.delete() if dele...
Delete a table in user's CARTO account. Args: table_name (str): Name of table to delete Returns: bool: `True` if table is removed
Below is the the instruction that describes the task: ### Input: Delete a table in user's CARTO account. Args: table_name (str): Name of table to delete Returns: bool: `True` if table is removed ### Response: def delete(self, table_name): """Delete a table in user'...
def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]: """ Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Resu...
Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``op(E)``. ...
Below is the the instruction that describes the task: ### Input: Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Result` if it is ...
def cyvcf_add_filter(rec, name): """Add a FILTER value to a cyvcf2 record """ if rec.FILTER: filters = rec.FILTER.split(";") else: filters = [] if name not in filters: filters.append(name) rec.FILTER = filters return rec
Add a FILTER value to a cyvcf2 record
Below is the the instruction that describes the task: ### Input: Add a FILTER value to a cyvcf2 record ### Response: def cyvcf_add_filter(rec, name): """Add a FILTER value to a cyvcf2 record """ if rec.FILTER: filters = rec.FILTER.split(";") else: filters = [] if name not in fil...
def configure_node(self, node): """Slaves need to know if they are collocated and what files have moved.""" node.slaveinput['cov_master_host'] = socket.gethostname() node.slaveinput['cov_master_topdir'] = self.topdir node.slaveinput['cov_master_rsync_roots'] = [str(root) for root in nod...
Slaves need to know if they are collocated and what files have moved.
Below is the the instruction that describes the task: ### Input: Slaves need to know if they are collocated and what files have moved. ### Response: def configure_node(self, node): """Slaves need to know if they are collocated and what files have moved.""" node.slaveinput['cov_master_host'] = sock...
def times_like(X, sr=22050, hop_length=512, n_fft=None, axis=-1): """Return an array of time values to match the time axis from a feature matrix. Parameters ---------- X : np.ndarray or scalar - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. - If scalar, X...
Return an array of time values to match the time axis from a feature matrix. Parameters ---------- X : np.ndarray or scalar - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. - If scalar, X represents the number of frames. sr : number > 0 [scalar] a...
Below is the the instruction that describes the task: ### Input: Return an array of time values to match the time axis from a feature matrix. Parameters ---------- X : np.ndarray or scalar - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. - If scalar, X rep...
def parse(argv=None): """ Parse some arguments using the parser. """ if argv is None: argv = sys.argv[1:] # Evade http://bugs.python.org/issue9253 if not argv or argv[0] not in {"run", "transform"}: argv = ["run"] + argv arguments = _clean(_parser.parse_args(argv)) re...
Parse some arguments using the parser.
Below is the the instruction that describes the task: ### Input: Parse some arguments using the parser. ### Response: def parse(argv=None): """ Parse some arguments using the parser. """ if argv is None: argv = sys.argv[1:] # Evade http://bugs.python.org/issue9253 if not argv or ...
def _get_ignore_from_manifest_lines(lines): """Gather the various ignore patterns from a MANIFEST.in. 'lines' should be a list of strings with comments removed and continuation lines joined. Returns a list of standard ignore patterns and a list of regular expressions to ignore. """ ignore ...
Gather the various ignore patterns from a MANIFEST.in. 'lines' should be a list of strings with comments removed and continuation lines joined. Returns a list of standard ignore patterns and a list of regular expressions to ignore.
Below is the the instruction that describes the task: ### Input: Gather the various ignore patterns from a MANIFEST.in. 'lines' should be a list of strings with comments removed and continuation lines joined. Returns a list of standard ignore patterns and a list of regular expressions to ignore. #...
def get_schema_input_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_schema = ET.Element("get_schema") config = get_schema input = ET.SubElement(get_schema, "input") version = ET.SubElement(input, "version") version.te...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_schema_input_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_schema = ET.Element("get_schema") config = get_schema input =...
def from_array(array): """ Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from ...
Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat
Below is the the instruction that describes the task: ### Input: Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat ### Response: def from_array(array): """ Deserialize a new Chat from a given dictionary. :return: new Chat instance. ...
def call_async(self, func: Callable, *args, **kwargs): """ Call the given callable in the event loop thread. This method lets you call asynchronous code from a worker thread. Do not use it from within the event loop thread. If the callable returns an awaitable, it is resolved b...
Call the given callable in the event loop thread. This method lets you call asynchronous code from a worker thread. Do not use it from within the event loop thread. If the callable returns an awaitable, it is resolved before returning to the caller. :param func: a regular function or ...
Below is the the instruction that describes the task: ### Input: Call the given callable in the event loop thread. This method lets you call asynchronous code from a worker thread. Do not use it from within the event loop thread. If the callable returns an awaitable, it is resolved before ...
def _is_ready(self, as_of): """Is the RecurringCost ready to be enacted as of the date `as_of` This determines if `as_of` precedes the start of `initial_billing_cycle`. If so, we should not be enacting this RecurringCost yet. Args: as_of (Date): """ if self....
Is the RecurringCost ready to be enacted as of the date `as_of` This determines if `as_of` precedes the start of `initial_billing_cycle`. If so, we should not be enacting this RecurringCost yet. Args: as_of (Date):
Below is the the instruction that describes the task: ### Input: Is the RecurringCost ready to be enacted as of the date `as_of` This determines if `as_of` precedes the start of `initial_billing_cycle`. If so, we should not be enacting this RecurringCost yet. Args: as_of (Date)...
def consultar_cep(cep, ambiente=PRODUCAO): """Retorna o endereço correspondente ao número de CEP informado. Arguments: cep {str} -- CEP a ser consultado. Keyword Arguments: ambiente {int} -- Indica qual será o webservice utilizado na consulta de CEP. Valor default é PRODUCAO (default: {PRO...
Retorna o endereço correspondente ao número de CEP informado. Arguments: cep {str} -- CEP a ser consultado. Keyword Arguments: ambiente {int} -- Indica qual será o webservice utilizado na consulta de CEP. Valor default é PRODUCAO (default: {PRODUCAO}) Raises: KeyError -- Quando am...
Below is the the instruction that describes the task: ### Input: Retorna o endereço correspondente ao número de CEP informado. Arguments: cep {str} -- CEP a ser consultado. Keyword Arguments: ambiente {int} -- Indica qual será o webservice utilizado na consulta de CEP. Valor default é PROD...
def get_bpf_pointer(tcpdump_lines): """Create a BPF Pointer for TCPDump filter""" if conf.use_pypy: return _legacy_bpf_pointer(tcpdump_lines) # Allocate BPF instructions size = int(tcpdump_lines[0]) bpf_insn_a = bpf_insn * size bip = bpf_insn_a() # Fill the BPF instruction structur...
Create a BPF Pointer for TCPDump filter
Below is the the instruction that describes the task: ### Input: Create a BPF Pointer for TCPDump filter ### Response: def get_bpf_pointer(tcpdump_lines): """Create a BPF Pointer for TCPDump filter""" if conf.use_pypy: return _legacy_bpf_pointer(tcpdump_lines) # Allocate BPF instructions s...
def _read_ftdna_famfinder(file): """ Read and parse Family Tree DNA (FTDNA) "famfinder" file. https://www.familytreedna.com Parameters ---------- file : str path to file Returns ------- pandas.DataFrame individual's genetic data ...
Read and parse Family Tree DNA (FTDNA) "famfinder" file. https://www.familytreedna.com Parameters ---------- file : str path to file Returns ------- pandas.DataFrame individual's genetic data normalized for use with `lineage` str...
Below is the the instruction that describes the task: ### Input: Read and parse Family Tree DNA (FTDNA) "famfinder" file. https://www.familytreedna.com Parameters ---------- file : str path to file Returns ------- pandas.DataFrame in...
def process_data(self, data): """Convert an unknown data input into a geojson dictionary.""" if isinstance(data, dict): self.embed = True return data elif isinstance(data, str): if data.lower().startswith(('http:', 'ftp:', 'https:')): if not se...
Convert an unknown data input into a geojson dictionary.
Below is the the instruction that describes the task: ### Input: Convert an unknown data input into a geojson dictionary. ### Response: def process_data(self, data): """Convert an unknown data input into a geojson dictionary.""" if isinstance(data, dict): self.embed = True r...
def _baseplot(cls, session, type, *args, **kwargs): """ Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all pl...
Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-type specific positional and keyword arguments, which will be...
Below is the the instruction that describes the task: ### Input: Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-...
def delete_archive(self, archive_id): """ Deletes an OpenTok archive. You can only delete an archive which has a status of "available" or "uploaded". Deleting an archive removes its record from the list of archives. For an "available" archive, it also removes the archive file, m...
Deletes an OpenTok archive. You can only delete an archive which has a status of "available" or "uploaded". Deleting an archive removes its record from the list of archives. For an "available" archive, it also removes the archive file, making it unavailable for download. :param String ...
Below is the the instruction that describes the task: ### Input: Deletes an OpenTok archive. You can only delete an archive which has a status of "available" or "uploaded". Deleting an archive removes its record from the list of archives. For an "available" archive, it also removes the arch...
def main(): """ Called by PyBridge.start() """ #: If we set the TMP env variable the dev reloader will save file #: and load changes in this directory instead of overwriting the #: ones installed with the app. os.environ['TMP'] = os.path.join(sys.path[0], '../tmp') from enamlnative.android...
Called by PyBridge.start()
Below is the the instruction that describes the task: ### Input: Called by PyBridge.start() ### Response: def main(): """ Called by PyBridge.start() """ #: If we set the TMP env variable the dev reloader will save file #: and load changes in this directory instead of overwriting the #: ones in...
def sos(self, year): """Returns the SOS (Strength of Schedule) for a team in a year, based on SRS. :year: The year for the season in question. :returns: A float of SOS. """ try: sos_text = self._year_info_pq(year, 'SOS').text() except ValueError: ...
Returns the SOS (Strength of Schedule) for a team in a year, based on SRS. :year: The year for the season in question. :returns: A float of SOS.
Below is the the instruction that describes the task: ### Input: Returns the SOS (Strength of Schedule) for a team in a year, based on SRS. :year: The year for the season in question. :returns: A float of SOS. ### Response: def sos(self, year): """Returns the SOS (Strength of Sched...
def l2traceroute_result_output_l2_hop_results_l2_hop_egress_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") l2traceroute_result = ET.Element("l2traceroute_result") config = l2traceroute_result output = ET.SubElement(l2traceroute_re...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def l2traceroute_result_output_l2_hop_results_l2_hop_egress_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") l2traceroute_result = ET.Element("l...
def _build_url(self, api_call): """Build request url. Parameters: api_call (str): Base API Call. Returns: Complete url (str). """ if self.api_version in ('1.13.0', '1.13.0+update.1', '1.13.0+update.2'): if '/' not in api_call: ...
Build request url. Parameters: api_call (str): Base API Call. Returns: Complete url (str).
Below is the the instruction that describes the task: ### Input: Build request url. Parameters: api_call (str): Base API Call. Returns: Complete url (str). ### Response: def _build_url(self, api_call): """Build request url. Parameters: api_call...
def text_remove_empty_lines(text): """ Whitespace normalization: - Strip empty lines - Strip trailing whitespace """ lines = [ line.rstrip() for line in text.splitlines() if line.strip() ] return "\n".join(lines)
Whitespace normalization: - Strip empty lines - Strip trailing whitespace
Below is the the instruction that describes the task: ### Input: Whitespace normalization: - Strip empty lines - Strip trailing whitespace ### Response: def text_remove_empty_lines(text): """ Whitespace normalization: - Strip empty lines - Strip trailing whitespace """ lin...
def from_file(filename, use_cores=True, thresh=1.e-4): """ Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). ...
Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). Otherwise, use shell positions and discard core positio...
Below is the the instruction that describes the task: ### Input: Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). Otherw...
def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "w\n" ) write = file.write count_sid = len( sid_standard_names ) # `mac_extras' contains the list of glyph names in the Macintosh standard # encoding which are not ...
main program body
Below is the the instruction that describes the task: ### Input: main program body ### Response: def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "w\n" ) write = file.write count_sid = len( sid_standard_names ) ...
def is_valid_with_config(self, config): """ Check if output format is valid with other process parameters. Parameters ---------- config : dictionary output configuration parameters Returns ------- is_valid : bool """ validate_...
Check if output format is valid with other process parameters. Parameters ---------- config : dictionary output configuration parameters Returns ------- is_valid : bool
Below is the the instruction that describes the task: ### Input: Check if output format is valid with other process parameters. Parameters ---------- config : dictionary output configuration parameters Returns ------- is_valid : bool ### Response: def i...
def CORS(func=None): """ CORS support """ def w(r=None): from uliweb import request, response if request.method == 'OPTIONS': response = Response(status=204) response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Contr...
CORS support
Below is the the instruction that describes the task: ### Input: CORS support ### Response: def CORS(func=None): """ CORS support """ def w(r=None): from uliweb import request, response if request.method == 'OPTIONS': response = Response(status=204) respons...
def is_valid_email(self): """A bool value that indicates whether the address is a valid email address. Note that the check is done be matching to the regular expression at Email.re_email which is very basic and far from covering end-cases... """ ...
A bool value that indicates whether the address is a valid email address. Note that the check is done be matching to the regular expression at Email.re_email which is very basic and far from covering end-cases...
Below is the the instruction that describes the task: ### Input: A bool value that indicates whether the address is a valid email address. Note that the check is done be matching to the regular expression at Email.re_email which is very basic and far from covering end-cases......
def download_kitchen(split=False): """Download structured grid of kitchen with velocity field. Use the ``split`` argument to extract all of the furniture in the kitchen. """ mesh = _download_and_read('kitchen.vtk') if not split: return mesh extents = { 'door' : (27, 27, 14, 18, ...
Download structured grid of kitchen with velocity field. Use the ``split`` argument to extract all of the furniture in the kitchen.
Below is the the instruction that describes the task: ### Input: Download structured grid of kitchen with velocity field. Use the ``split`` argument to extract all of the furniture in the kitchen. ### Response: def download_kitchen(split=False): """Download structured grid of kitchen with velocity field. U...
def makeDirectoryFromAbsolutePath(absDirPath): """ Makes directory for the given directory path with default permissions. If the directory already exists, it is treated as success. absDirPath: absolute path of the directory to create. Returns: absDirPath arg Exceptions: OSError if directory ...
Makes directory for the given directory path with default permissions. If the directory already exists, it is treated as success. absDirPath: absolute path of the directory to create. Returns: absDirPath arg Exceptions: OSError if directory creation fails
Below is the the instruction that describes the task: ### Input: Makes directory for the given directory path with default permissions. If the directory already exists, it is treated as success. absDirPath: absolute path of the directory to create. Returns: absDirPath arg Exceptions: OSErr...
def connect(self, fun): """ Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- ...
Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- fun : callable T...
Below is the the instruction that describes the task: ### Input: Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. ...
def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8): ''' perform one-sided (causal) EMA (exponential moving average) smoothing and resampling to an even grid with n points. Does not do extrapolation, so we assume xolds[0] <= low && high <= xolds[-1]...
perform one-sided (causal) EMA (exponential moving average) smoothing and resampling to an even grid with n points. Does not do extrapolation, so we assume xolds[0] <= low && high <= xolds[-1] Arguments: xolds: array or list - x values of data. Needs to be sorted in ascending order yolds: arr...
Below is the the instruction that describes the task: ### Input: perform one-sided (causal) EMA (exponential moving average) smoothing and resampling to an even grid with n points. Does not do extrapolation, so we assume xolds[0] <= low && high <= xolds[-1] Arguments: xolds: array or list - x...