code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def upload(self, payload=None, content_type=None): """ Upload the archive at `path` with content type `content_type` returns (int): upload status code """ # platform - prefer the value passed in to func over config payload = payload or self.config.payload ...
Upload the archive at `path` with content type `content_type` returns (int): upload status code
Below is the the instruction that describes the task: ### Input: Upload the archive at `path` with content type `content_type` returns (int): upload status code ### Response: def upload(self, payload=None, content_type=None): """ Upload the archive at `path` with content type `conte...
def normalizeInternalObjectType(value, cls, name): """ Normalizes an internal object type. * **value** must be a instance of **cls**. * Returned value is the same type as the input value. """ if not isinstance(value, cls): raise TypeError("%s must be a %s instance, not %s." ...
Normalizes an internal object type. * **value** must be a instance of **cls**. * Returned value is the same type as the input value.
Below is the the instruction that describes the task: ### Input: Normalizes an internal object type. * **value** must be a instance of **cls**. * Returned value is the same type as the input value. ### Response: def normalizeInternalObjectType(value, cls, name): """ Normalizes an internal object t...
def mergeNewMSBWT(mergedDir, inputBwtDirs, numProcs, logger): ''' This function will take a list of input BWTs (compressed or not) and merge them into a single BWT @param mergedFN - the destination for the final merged MSBWT @param inputBWTFN1 - the fn of the first BWT to merge @param inputBWTFN2 - ...
This function will take a list of input BWTs (compressed or not) and merge them into a single BWT @param mergedFN - the destination for the final merged MSBWT @param inputBWTFN1 - the fn of the first BWT to merge @param inputBWTFN2 - the fn of the second BWT to merge @param numProcs - number of processe...
Below is the the instruction that describes the task: ### Input: This function will take a list of input BWTs (compressed or not) and merge them into a single BWT @param mergedFN - the destination for the final merged MSBWT @param inputBWTFN1 - the fn of the first BWT to merge @param inputBWTFN2 - the f...
def long_description(*filenames): """Provide a long description.""" res = [''] for filename in filenames: with open(filename) as fp: for line in fp: res.append(' ' + line) res.append('') res.append('\n') return EMPTYSTRING.join(res)
Provide a long description.
Below is the the instruction that describes the task: ### Input: Provide a long description. ### Response: def long_description(*filenames): """Provide a long description.""" res = [''] for filename in filenames: with open(filename) as fp: for line in fp: res.append(...
def _StatusUpdateThreadMain(self): """Main function of the status update thread.""" while self._status_update_active: # Make a local copy of the PIDs in case the dict is changed by # the main thread. for pid in list(self._process_information_per_pid.keys()): self._CheckStatusAnalysisPr...
Main function of the status update thread.
Below is the the instruction that describes the task: ### Input: Main function of the status update thread. ### Response: def _StatusUpdateThreadMain(self): """Main function of the status update thread.""" while self._status_update_active: # Make a local copy of the PIDs in case the dict is changed b...
def transpose(self, name=None, activate_final=None): """Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining i...
Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining if the activation and batch normalization, if turned ...
Below is the the instruction that describes the task: ### Input: Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean dete...
def oplog_thread_join(self): """Stops all the OplogThreads """ LOG.info("MongoConnector: Stopping all OplogThreads") for thread in self.shard_set.values(): thread.join()
Stops all the OplogThreads
Below is the the instruction that describes the task: ### Input: Stops all the OplogThreads ### Response: def oplog_thread_join(self): """Stops all the OplogThreads """ LOG.info("MongoConnector: Stopping all OplogThreads") for thread in self.shard_set.values(): thread.jo...
def query(self, watch_key, time_indices=None, slicing=None, mapping=None): """Query tensor store for a given watch_key. Args: watch_key: The watch key to query. time_indices: A numpy-style slicing string for time indices. E.g., `-1`, `:-2`, `[...
Query tensor store for a given watch_key. Args: watch_key: The watch key to query. time_indices: A numpy-style slicing string for time indices. E.g., `-1`, `:-2`, `[::2]`. If not provided (`None`), will use -1. slicing: A numpy-style slicing string for individual time steps. mapping...
Below is the the instruction that describes the task: ### Input: Query tensor store for a given watch_key. Args: watch_key: The watch key to query. time_indices: A numpy-style slicing string for time indices. E.g., `-1`, `:-2`, `[::2]`. If not provided (`None`), will use -1. slicing: ...
def stream_mapred(self, inputs, query, timeout): """ Streams a MapReduce query as (phase, data) pairs. This is a generator method which should be iterated over. The caller should explicitly close the returned iterator, either using :func:`contextlib.closing` or calling ``close()...
Streams a MapReduce query as (phase, data) pairs. This is a generator method which should be iterated over. The caller should explicitly close the returned iterator, either using :func:`contextlib.closing` or calling ``close()`` explicitly. Consuming the entire iterator will also close ...
Below is the the instruction that describes the task: ### Input: Streams a MapReduce query as (phase, data) pairs. This is a generator method which should be iterated over. The caller should explicitly close the returned iterator, either using :func:`contextlib.closing` or calling ``close()...
def get_vartype(data): """Infer the type of a variable (technically a Series). The types supported are split in standard types and special types. Standard types: * Categorical (`TYPE_CAT`): the default type if no other one can be determined * Numerical (`TYPE_NUM`): if it contains numbers ...
Infer the type of a variable (technically a Series). The types supported are split in standard types and special types. Standard types: * Categorical (`TYPE_CAT`): the default type if no other one can be determined * Numerical (`TYPE_NUM`): if it contains numbers * Boolean (`TYPE_BOOL`...
Below is the the instruction that describes the task: ### Input: Infer the type of a variable (technically a Series). The types supported are split in standard types and special types. Standard types: * Categorical (`TYPE_CAT`): the default type if no other one can be determined * Numerica...
def disconnect(self, device): """Disconnect using protocol specific method.""" # self.device.ctrl.sendcontrol(']') # self.device.ctrl.sendline('quit') self.log("TELNET disconnect") try: self.device.ctrl.send(chr(4)) except OSError: self.log("Protoc...
Disconnect using protocol specific method.
Below is the the instruction that describes the task: ### Input: Disconnect using protocol specific method. ### Response: def disconnect(self, device): """Disconnect using protocol specific method.""" # self.device.ctrl.sendcontrol(']') # self.device.ctrl.sendline('quit') self.log("...
def kill(self): """ Send SIGKILL to the task's process. """ logger.info('Sending SIGKILL to task {0}'.format(self.name)) if hasattr(self, 'remote_client') and self.remote_client is not None: self.kill_sent = True self.remote_client.close() return if no...
Send SIGKILL to the task's process.
Below is the the instruction that describes the task: ### Input: Send SIGKILL to the task's process. ### Response: def kill(self): """ Send SIGKILL to the task's process. """ logger.info('Sending SIGKILL to task {0}'.format(self.name)) if hasattr(self, 'remote_client') and self.remote_clien...
def _wait_output(popen, is_slow): """Returns `True` if we can get output of the command in the `settings.wait_command` time. Command will be killed if it wasn't finished in the time. :type popen: Popen :rtype: bool """ proc = Process(popen.pid) try: proc.wait(settings.wait_slo...
Returns `True` if we can get output of the command in the `settings.wait_command` time. Command will be killed if it wasn't finished in the time. :type popen: Popen :rtype: bool
Below is the the instruction that describes the task: ### Input: Returns `True` if we can get output of the command in the `settings.wait_command` time. Command will be killed if it wasn't finished in the time. :type popen: Popen :rtype: bool ### Response: def _wait_output(popen, is_slow): ""...
def create_switch(type, settings, pin): """Create a switch. Args: type: (str): type of the switch [A,B,C,D] settings (str): a comma separted list pin (int): wiringPi pin Returns: switch """ switch = None if type == "A": group, device = settings.split(",") switch = p...
Create a switch. Args: type: (str): type of the switch [A,B,C,D] settings (str): a comma separted list pin (int): wiringPi pin Returns: switch
Below is the the instruction that describes the task: ### Input: Create a switch. Args: type: (str): type of the switch [A,B,C,D] settings (str): a comma separted list pin (int): wiringPi pin Returns: switch ### Response: def create_switch(type, settings, pin): """Create ...
def delete_collection_namespaced_replica_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, p...
delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_replica_set(namesp...
Below is the the instruction that describes the task: ### Input: delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
def parse_or_die(self, args=None): """Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a :exc:`KwargvError` is raised, printing the exception text. Returns *self* for convenience. """ from .cli import die try: return self.parse(args) ...
Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a :exc:`KwargvError` is raised, printing the exception text. Returns *self* for convenience.
Below is the the instruction that describes the task: ### Input: Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a :exc:`KwargvError` is raised, printing the exception text. Returns *self* for convenience. ### Response: def parse_or_die(self, args=None): """Like :meth:`...
def copy(input, **params): """ Copies input or input's selected fields :param input: :param params: :return: input """ PARAM_FIELDS = 'fields' def filter_fields(obj, fields): return {k:v for k,v in obj.items() if k in fields} if PARAM_FIELDS in params: fields = para...
Copies input or input's selected fields :param input: :param params: :return: input
Below is the the instruction that describes the task: ### Input: Copies input or input's selected fields :param input: :param params: :return: input ### Response: def copy(input, **params): """ Copies input or input's selected fields :param input: :param params: :return: input "...
def fs_obj_query_info(self, path, follow_symlinks): """Queries information about a file system object (file, directory, etc) in the guest. in path of type str Path to the file system object to gather information about. Guest path style. in follow_symlinks of typ...
Queries information about a file system object (file, directory, etc) in the guest. in path of type str Path to the file system object to gather information about. Guest path style. in follow_symlinks of type bool Information about symbolic links is returned...
Below is the the instruction that describes the task: ### Input: Queries information about a file system object (file, directory, etc) in the guest. in path of type str Path to the file system object to gather information about. Guest path style. in follow_symlinks ...
def convert_values(args_list): """convert_value in bulk. :param args_list: list of value, source, target currency pairs :return: map of converted values """ rate_map = get_rates(map(itemgetter(1, 2), args_list)) value_map = {} for value, source, target in args_list: args = (value, ...
convert_value in bulk. :param args_list: list of value, source, target currency pairs :return: map of converted values
Below is the the instruction that describes the task: ### Input: convert_value in bulk. :param args_list: list of value, source, target currency pairs :return: map of converted values ### Response: def convert_values(args_list): """convert_value in bulk. :param args_list: list of value, source, ...
def explain_weights_dfs(estimator, **kwargs): # type: (...) -> Dict[str, pd.DataFrame] """ Explain weights and export them to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_weights`. ...
Explain weights and export them to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_weights`. Weights of all features are exported by default.
Below is the the instruction that describes the task: ### Input: Explain weights and export them to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_weights`. Weights of all features are e...
def zeq_magic(meas_file='measurements.txt', spec_file='',crd='s',input_dir_path='.', angle=0, n_plots=5, save_plots=True, fmt="svg", interactive=False, specimen="", samp_file='samples.txt', contribution=None,fignum=1): """ zeq_magic makes zijderveld and equal area plots for magic for...
zeq_magic makes zijderveld and equal area plots for magic formatted measurements files. Parameters ---------- meas_file : str input measurement file spec_file : str input specimen interpretation file samp_file : str input sample orientations file crd : str coordin...
Below is the the instruction that describes the task: ### Input: zeq_magic makes zijderveld and equal area plots for magic formatted measurements files. Parameters ---------- meas_file : str input measurement file spec_file : str input specimen interpretation file samp_file : str...
def update(self, dist): """ Adds the given distribution's counts to the current distribution. """ assert isinstance(dist, DDist) for k, c in iteritems(dist.counts): self.counts[k] += c self.total += dist.total
Adds the given distribution's counts to the current distribution.
Below is the the instruction that describes the task: ### Input: Adds the given distribution's counts to the current distribution. ### Response: def update(self, dist): """ Adds the given distribution's counts to the current distribution. """ assert isinstance(dist, DDist) f...
def reftag_to_cls(fn): """ decorator that checks function arguments for `concrete` and `resource` and will properly set them to class references if a string (reftag) is passed as the value """ names, _, _, values = inspect.getargspec(fn) @wraps(fn) def wrapped(*args, **kwargs): i...
decorator that checks function arguments for `concrete` and `resource` and will properly set them to class references if a string (reftag) is passed as the value
Below is the the instruction that describes the task: ### Input: decorator that checks function arguments for `concrete` and `resource` and will properly set them to class references if a string (reftag) is passed as the value ### Response: def reftag_to_cls(fn): """ decorator that checks function ...
def predict_proba(self, p): """ Calculate the calibrated probabilities Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be calibrated using calibration map Returns ------- y_prob_cal : array-like of shape...
Calculate the calibrated probabilities Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be calibrated using calibration map Returns ------- y_prob_cal : array-like of shape = [n_samples, 1] Predicted ...
Below is the the instruction that describes the task: ### Input: Calculate the calibrated probabilities Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be calibrated using calibration map Returns ------- y_p...
def setup_scrollarea(self): """Setup the scrollarea that will contain the FigureThumbnails.""" self.view = QWidget() self.scene = QGridLayout(self.view) self.scene.setColumnStretch(0, 100) self.scene.setColumnStretch(2, 100) self.scrollarea = QScrollArea() self....
Setup the scrollarea that will contain the FigureThumbnails.
Below is the the instruction that describes the task: ### Input: Setup the scrollarea that will contain the FigureThumbnails. ### Response: def setup_scrollarea(self): """Setup the scrollarea that will contain the FigureThumbnails.""" self.view = QWidget() self.scene = QGridLayout(self.vie...
def handle(self, *args, **options): """ Making it happen. """ logger.info("Build started") # Set options self.set_options(*args, **options) # Get the build directory ready if not options.get("keep_build_dir"): self.init_build_dir() #...
Making it happen.
Below is the the instruction that describes the task: ### Input: Making it happen. ### Response: def handle(self, *args, **options): """ Making it happen. """ logger.info("Build started") # Set options self.set_options(*args, **options) # Get the build dire...
def read_data(archive, arc_type, day, stachans, length=86400): """ Function to read the appropriate data from an archive for a day. :type archive: str :param archive: The archive source - if arc_type is seishub, this should be a url, if the arc_type is FDSN then this can be either a url...
Function to read the appropriate data from an archive for a day. :type archive: str :param archive: The archive source - if arc_type is seishub, this should be a url, if the arc_type is FDSN then this can be either a url or a known obspy client. If arc_type is day_vols, then this is th...
Below is the the instruction that describes the task: ### Input: Function to read the appropriate data from an archive for a day. :type archive: str :param archive: The archive source - if arc_type is seishub, this should be a url, if the arc_type is FDSN then this can be either a url or a ...
def append(self, tweet): """Add a tweet to the end of the list.""" c = self.connection.cursor() last_tweet = c.execute("SELECT tweet from tweetlist where label='last_tweet'").next()[0] c.execute("INSERT INTO tweets(message, previous_tweet, next_tweet) VALUES (?,?,NULL)", (tweet, last_...
Add a tweet to the end of the list.
Below is the the instruction that describes the task: ### Input: Add a tweet to the end of the list. ### Response: def append(self, tweet): """Add a tweet to the end of the list.""" c = self.connection.cursor() last_tweet = c.execute("SELECT tweet from tweetlist where label='last_tweet'")....
def verify(self, message, pubkey, rnum, snum): """ Verify the signature for message m, pubkey Y, signature (r,s) r = xcoord(R) verify that : G*m+Y*r=R*s this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k } G*m+G*x*r = G*k*(m+x*r)/k -> G*(m+x*r) = G*(...
Verify the signature for message m, pubkey Y, signature (r,s) r = xcoord(R) verify that : G*m+Y*r=R*s this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k } G*m+G*x*r = G*k*(m+x*r)/k -> G*(m+x*r) = G*(m+x*r) several ways to do the verification: r =...
Below is the the instruction that describes the task: ### Input: Verify the signature for message m, pubkey Y, signature (r,s) r = xcoord(R) verify that : G*m+Y*r=R*s this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k } G*m+G*x*r = G*k*(m+x*r)/k -> G*(m+x*r) = G...
def bound_bboxes(bboxes): """ Finds the minimal bbox that contains all given bboxes """ group_x0 = min(map(lambda l: l[x0], bboxes)) group_y0 = min(map(lambda l: l[y0], bboxes)) group_x1 = max(map(lambda l: l[x1], bboxes)) group_y1 = max(map(lambda l: l[y1], bboxes)) return (group_x0, gr...
Finds the minimal bbox that contains all given bboxes
Below is the the instruction that describes the task: ### Input: Finds the minimal bbox that contains all given bboxes ### Response: def bound_bboxes(bboxes): """ Finds the minimal bbox that contains all given bboxes """ group_x0 = min(map(lambda l: l[x0], bboxes)) group_y0 = min(map(lambda l: ...
def SegmentMax(a, ids): """ Segmented max op. """ func = lambda idxs: np.amax(a[idxs], axis=0) return seg_map(func, a, ids),
Segmented max op.
Below is the the instruction that describes the task: ### Input: Segmented max op. ### Response: def SegmentMax(a, ids): """ Segmented max op. """ func = lambda idxs: np.amax(a[idxs], axis=0) return seg_map(func, a, ids),
def load_data(self, grid_method="gamma", num_samples=1000, condition_threshold=0.5, zero_inflate=False, percentile=None): """ Reads the track forecasts and converts them to grid point values based on random sampling. Args: grid_method: "gamma" by default ...
Reads the track forecasts and converts them to grid point values based on random sampling. Args: grid_method: "gamma" by default num_samples: Number of samples drawn from predicted pdf condition_threshold: Objects are not written to the grid if condition model probability is...
Below is the the instruction that describes the task: ### Input: Reads the track forecasts and converts them to grid point values based on random sampling. Args: grid_method: "gamma" by default num_samples: Number of samples drawn from predicted pdf condition_threshold: ...
def hex_2_rgb(self, color): """ convert a hex color to rgb """ if not self.RE_HEX.match(color): color = "#FFF" if len(color) == 7: return (int(color[i : i + 2], 16) / 255 for i in [1, 3, 5]) return (int(c, 16) / 15 for c in color)
convert a hex color to rgb
Below is the the instruction that describes the task: ### Input: convert a hex color to rgb ### Response: def hex_2_rgb(self, color): """ convert a hex color to rgb """ if not self.RE_HEX.match(color): color = "#FFF" if len(color) == 7: return (int(co...
def apply_activation( books, x, activation, activation_args=(), activation_kwargs=None): """Returns activation(x, *activation_args, **activation_kwargs). This applies the given activation and adds useful summaries specific to the activation. Args: books: The bookkeeper. x: The tens...
Returns activation(x, *activation_args, **activation_kwargs). This applies the given activation and adds useful summaries specific to the activation. Args: books: The bookkeeper. x: The tensor to apply activation to. activation: An activation function. activation_args: Optional additional argume...
Below is the the instruction that describes the task: ### Input: Returns activation(x, *activation_args, **activation_kwargs). This applies the given activation and adds useful summaries specific to the activation. Args: books: The bookkeeper. x: The tensor to apply activation to. activation: An...
def create_array(self, json): """Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. """ result = Array(json['sys']) result.total = json['total'] result.skip = json['skip'] result.limit = json['limit'] resu...
Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance.
Below is the the instruction that describes the task: ### Input: Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. ### Response: def create_array(self, json): """Create :class:`.resources.Array` from JSON. :param json: JSON dict. ...
def _get_erase_command(self, drive, pattern): """Return the command arguments based on the pattern. Erase command examples: 1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=overwrite unrestricted=off forced" 2) Zeros: "ssacli ctrl slot=0 pd 1I:1...
Return the command arguments based on the pattern. Erase command examples: 1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=overwrite unrestricted=off forced" 2) Zeros: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=zero forc...
Below is the the instruction that describes the task: ### Input: Return the command arguments based on the pattern. Erase command examples: 1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=overwrite unrestricted=off forced" 2) Zeros: "ssacli ctrl sl...
def _GetIdentifierFromPath(self, parser_mediator): """Extracts a container or a graph ID from a JSON file's path. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. Returns: str: container or graph identifier...
Extracts a container or a graph ID from a JSON file's path. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. Returns: str: container or graph identifier.
Below is the the instruction that describes the task: ### Input: Extracts a container or a graph ID from a JSON file's path. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. Returns: str: container or graph...
def exists_locked(filepath: str) -> Tuple[bool, bool]: """ Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.ca...
Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/.
Below is the the instruction that describes the task: ### Input: Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www....
def __calculate_dataset_difference(self, amount_clusters): """! @brief Calculate distance from each point to each cluster center. """ dataset_differences = numpy.zeros((amount_clusters, len(self.__pointer_data))) for index_center in range(amount_clusters): if ...
! @brief Calculate distance from each point to each cluster center.
Below is the the instruction that describes the task: ### Input: ! @brief Calculate distance from each point to each cluster center. ### Response: def __calculate_dataset_difference(self, amount_clusters): """! @brief Calculate distance from each point to each cluster center. ...
def analysis_provenance_details_simplified_extractor( impact_report, component_metadata): """Extracting simplified version of provenance details of layers. This extractor will produce provenance details which will be displayed in the main report. :param impact_report: the impact report that ac...
Extracting simplified version of provenance details of layers. This extractor will produce provenance details which will be displayed in the main report. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.im...
Below is the the instruction that describes the task: ### Input: Extracting simplified version of provenance details of layers. This extractor will produce provenance details which will be displayed in the main report. :param impact_report: the impact report that acts as a proxy to fetch all t...
def decode_response(content: bytes) -> set: """ adb response text -> device set """ content = content[4:].decode(config.ENCODING) if '\t' not in content and '\n' not in content: return set() connected_devices = set() device_list = [i for i in content.split('\n') if i] for each_device in...
adb response text -> device set
Below is the the instruction that describes the task: ### Input: adb response text -> device set ### Response: def decode_response(content: bytes) -> set: """ adb response text -> device set """ content = content[4:].decode(config.ENCODING) if '\t' not in content and '\n' not in content: return...
def get_files(client, bucket, prefix=''): """Lists files/objects on a bucket. TODO: docstring""" bucket = client.get_bucket(bucket) files = list(bucket.list_blobs(prefix=prefix)) return files
Lists files/objects on a bucket. TODO: docstring
Below is the the instruction that describes the task: ### Input: Lists files/objects on a bucket. TODO: docstring ### Response: def get_files(client, bucket, prefix=''): """Lists files/objects on a bucket. TODO: docstring""" bucket = client.get_bucket(bucket) files = list(bucket.list_...
def build_config(config_file=get_system_config_directory()): """ Construct the config object from necessary elements. """ config = Config(config_file, allow_no_value=True) application_versions = find_applications_on_system() # Add found versions to config if they don't exist. Versions fo...
Construct the config object from necessary elements.
Below is the the instruction that describes the task: ### Input: Construct the config object from necessary elements. ### Response: def build_config(config_file=get_system_config_directory()): """ Construct the config object from necessary elements. """ config = Config(config_file, allow_no_val...
def commit(self, offset=None, limit=None, dryrun=False): """ Start the rsync download """ self.stream.command = "rsync -avRK --files-from={path} {source} {destination}" self.stream.append_tasks_to_streamlets(offset=offset, limit=limit) self.stream.commit_streamlets() self.stream...
Start the rsync download
Below is the the instruction that describes the task: ### Input: Start the rsync download ### Response: def commit(self, offset=None, limit=None, dryrun=False): """ Start the rsync download """ self.stream.command = "rsync -avRK --files-from={path} {source} {destination}" self.stream.appen...
def _record_sort_by_indicators(record): """Sort the fields inside the record by indicators.""" for tag, fields in record.items(): record[tag] = _fields_sort_by_indicators(fields)
Sort the fields inside the record by indicators.
Below is the the instruction that describes the task: ### Input: Sort the fields inside the record by indicators. ### Response: def _record_sort_by_indicators(record): """Sort the fields inside the record by indicators.""" for tag, fields in record.items(): record[tag] = _fields_sort_by_indicators(...
def main(): "Process CLI arguments and call appropriate functions." try: args = docopt.docopt(__doc__, version=__about__.__version__) except docopt.DocoptExit: if len(sys.argv) > 1: print(f"{Fore.RED}Invalid command syntax, " f"check help:{Fore.RESET}\n") ...
Process CLI arguments and call appropriate functions.
Below is the the instruction that describes the task: ### Input: Process CLI arguments and call appropriate functions. ### Response: def main(): "Process CLI arguments and call appropriate functions." try: args = docopt.docopt(__doc__, version=__about__.__version__) except docopt.DocoptExit: ...
def findSector(self,x,y): ''' Finds the quadrilateral "sector" for each (x,y) point in the input. Only called as a subroutine of _evaluate(). Parameters ---------- x : np.array Values whose sector should be found. y : np.array Values whose...
Finds the quadrilateral "sector" for each (x,y) point in the input. Only called as a subroutine of _evaluate(). Parameters ---------- x : np.array Values whose sector should be found. y : np.array Values whose sector should be found. Should be same size ...
Below is the the instruction that describes the task: ### Input: Finds the quadrilateral "sector" for each (x,y) point in the input. Only called as a subroutine of _evaluate(). Parameters ---------- x : np.array Values whose sector should be found. y : np.array ...
def fo_pct_by_zone(self): """ Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` """ bz = self.by_zone return { t: { z: bz[t][z]['won']/(1.0*bz[t][z]['total']) if bz[t][z]['t...
Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }``
Below is the the instruction that describes the task: ### Input: Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` ### Response: def fo_pct_by_zone(self): """ Get the by team face-off win % by zone. Format is ...
def sub_path(self, path): """ If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`. """ if not self.regular_expression: return self.new_path return re.sub(self.old_path, self.new_path, path)
If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`.
Below is the the instruction that describes the task: ### Input: If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`. ### Response: def sub_path(self, path): """ If this redirect is a regular expression, it will return a r...
def check_terminate(self): """ Returns a Bool of whether to terminate. Checks whether a satisfactory minimum has been found or whether too many iterations have occurred. """ if not self._has_run: return False else: #1-3. errtol, paramtol, ...
Returns a Bool of whether to terminate. Checks whether a satisfactory minimum has been found or whether too many iterations have occurred.
Below is the the instruction that describes the task: ### Input: Returns a Bool of whether to terminate. Checks whether a satisfactory minimum has been found or whether too many iterations have occurred. ### Response: def check_terminate(self): """ Returns a Bool of whether to term...
def add(self,dist): """Add `dist` if we ``can_add()`` it and it isn't already added""" if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key,[]) if dist not in dists: dists.append(dist) if dist.key in self._cache: ...
Add `dist` if we ``can_add()`` it and it isn't already added
Below is the the instruction that describes the task: ### Input: Add `dist` if we ``can_add()`` it and it isn't already added ### Response: def add(self,dist): """Add `dist` if we ``can_add()`` it and it isn't already added""" if self.can_add(dist) and dist.has_version(): dists = self._...
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ if not os.path.isdir(replacement): os.makedirs(replacement) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir =...
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
Below is the the instruction that describes the task: ### Input: Monkey-patch tempfile.tempdir with replacement, ensuring it exists ### Response: def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ if not os.path.isdir(replacement): os....
def get_tracks(self, catalog, cache=True): """Get the tracks for a song given a catalog. Args: catalog (str): a string representing the catalog whose track you want to retrieve. Returns: A list of Track dicts. Example: >>> s ...
Get the tracks for a song given a catalog. Args: catalog (str): a string representing the catalog whose track you want to retrieve. Returns: A list of Track dicts. Example: >>> s = song.Song('SOWDASQ12A6310F24F') >>> s.ge...
Below is the the instruction that describes the task: ### Input: Get the tracks for a song given a catalog. Args: catalog (str): a string representing the catalog whose track you want to retrieve. Returns: A list of Track dicts. Example: ...
def collect(self, name, arr): """Callback function for collecting layer output NDArrays.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArrayHandle) arr = NDArray(handle, writable=False).co...
Callback function for collecting layer output NDArrays.
Below is the the instruction that describes the task: ### Input: Callback function for collecting layer output NDArrays. ### Response: def collect(self, name, arr): """Callback function for collecting layer output NDArrays.""" name = py_str(name) if self.include_layer is not None and not se...
def mergecn(args): """ %prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another. """ p = OptionParser(mergecn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: ...
%prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another.
Below is the the instruction that describes the task: ### Input: %prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another. ### Response: def mergecn(args): """ %prog mergecn FACE.csv Co...
def add_event(self, event): """ Adds an IEvent event to this command set. :param event: an event instance to be added """ self._events.append(event) self._events_by_name[event.get_name] = event
Adds an IEvent event to this command set. :param event: an event instance to be added
Below is the the instruction that describes the task: ### Input: Adds an IEvent event to this command set. :param event: an event instance to be added ### Response: def add_event(self, event): """ Adds an IEvent event to this command set. :param event: an event ins...
def declare_func(self, id_, lineno, type_=None): """ Declares a function in the current scope. Checks whether the id exist or not (error if exists). And creates the entry at the symbol table. """ if not self.check_class(id_, 'function', lineno): entry = self.get_entry...
Declares a function in the current scope. Checks whether the id exist or not (error if exists). And creates the entry at the symbol table.
Below is the the instruction that describes the task: ### Input: Declares a function in the current scope. Checks whether the id exist or not (error if exists). And creates the entry at the symbol table. ### Response: def declare_func(self, id_, lineno, type_=None): """ Declares a function ...
def with_tz(request): """ Get the time with TZ enabled """ dt = datetime.now() t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') c = RequestContext(request) response = t.render(c) return HttpResponse(response)
Get the time with TZ enabled
Below is the the instruction that describes the task: ### Input: Get the time with TZ enabled ### Response: def with_tz(request): """ Get the time with TZ enabled """ dt = datetime.now() t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{%...
def place_new_order(self, stock, price, qty, direction, order_type): """Place an order for a stock. https://starfighter.readme.io/docs/place-new-order """ url_fragment = 'venues/{venue}/stocks/{stock}/orders'.format( venue=self.venue, stock=stock, ) ...
Place an order for a stock. https://starfighter.readme.io/docs/place-new-order
Below is the the instruction that describes the task: ### Input: Place an order for a stock. https://starfighter.readme.io/docs/place-new-order ### Response: def place_new_order(self, stock, price, qty, direction, order_type): """Place an order for a stock. https://starfighter.readme.io/d...
def pretty(price, currency, *, abbrev=True, trim=True): """ return format price with symbol. Example format(100, 'USD') return '$100' pretty(price, currency, abbrev=True, trim=False) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. currency...
return format price with symbol. Example format(100, 'USD') return '$100' pretty(price, currency, abbrev=True, trim=False) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. currency code is placed behind value trim: True: trim float value ...
Below is the the instruction that describes the task: ### Input: return format price with symbol. Example format(100, 'USD') return '$100' pretty(price, currency, abbrev=True, trim=False) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. ...
def _recv_ack(self, method_frame): '''Receive an ack from the broker.''' if self._ack_listener: delivery_tag = method_frame.args.read_longlong() multiple = method_frame.args.read_bit() if multiple: while self._last_ack_id < delivery_tag: ...
Receive an ack from the broker.
Below is the the instruction that describes the task: ### Input: Receive an ack from the broker. ### Response: def _recv_ack(self, method_frame): '''Receive an ack from the broker.''' if self._ack_listener: delivery_tag = method_frame.args.read_longlong() multiple = method_f...
def bbox(self): """BBox""" return self.left, self.top, self.right, self.bottom
BBox
Below is the the instruction that describes the task: ### Input: BBox ### Response: def bbox(self): """BBox""" return self.left, self.top, self.right, self.bottom
def inverse(d): """ reverse the k:v pairs """ output = {} for k, v in unwrap(d).items(): output[v] = output.get(v, []) output[v].append(k) return output
reverse the k:v pairs
Below is the the instruction that describes the task: ### Input: reverse the k:v pairs ### Response: def inverse(d): """ reverse the k:v pairs """ output = {} for k, v in unwrap(d).items(): output[v] = output.get(v, []) output[v].append(k) return output
def del_object_from_parent(self): """ Delete object from parent object. """ if self.parent: self.parent.objects.pop(self.ref)
Delete object from parent object.
Below is the the instruction that describes the task: ### Input: Delete object from parent object. ### Response: def del_object_from_parent(self): """ Delete object from parent object. """ if self.parent: self.parent.objects.pop(self.ref)
def parse_post(self, response): ''' 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content = json.loads(response.body.decode(), encoding='UTF-8') post = response....
根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
Below is the the instruction that describes the task: ### Input: 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ### Response: def parse_post(self, response): ''' 根据 :meth:`.ZhihuDailySp...
def _call_and_store(getter_func, data, field_name, error_store, index=None): """Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. :param callable getter_func: Function for getting the serialized/deserialized value from ``data``. :param data: The d...
Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. :param callable getter_func: Function for getting the serialized/deserialized value from ``data``. :param data: The data passed to ``getter_func``. :param str field_name: Field name. :param...
Below is the the instruction that describes the task: ### Input: Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. :param callable getter_func: Function for getting the serialized/deserialized value from ``data``. :param data: The data passed to ``get...
def fetchall(self): """Fetch all rows.""" result = self.query.result() return [row.values() for row in result]
Fetch all rows.
Below is the the instruction that describes the task: ### Input: Fetch all rows. ### Response: def fetchall(self): """Fetch all rows.""" result = self.query.result() return [row.values() for row in result]
async def start(request): """ Begins the session manager for factory calibration, if a session is not already in progress, or if the "force" key is specified in the request. To force, use the following body: { "force": true } :return: The current session ID token or an error message ...
Begins the session manager for factory calibration, if a session is not already in progress, or if the "force" key is specified in the request. To force, use the following body: { "force": true } :return: The current session ID token or an error message
Below is the the instruction that describes the task: ### Input: Begins the session manager for factory calibration, if a session is not already in progress, or if the "force" key is specified in the request. To force, use the following body: { "force": true } :return: The current session ...
def parse(self, data): """Returns a list of path template segments parsed from data. Args: data: A path template string. Returns: A list of _Segment. """ self.binding_var_count = 0 self.segment_count = 0 segments = self.parser.parse(data)...
Returns a list of path template segments parsed from data. Args: data: A path template string. Returns: A list of _Segment.
Below is the the instruction that describes the task: ### Input: Returns a list of path template segments parsed from data. Args: data: A path template string. Returns: A list of _Segment. ### Response: def parse(self, data): """Returns a list of path template segme...
def get_client(client_id): """Load the client. Needed for grant_type client_credentials. Add support for OAuth client_credentials access type, with user inactivation support. :param client_id: The client ID. :returns: The client instance or ``None``. """ client = Client.query.get(clie...
Load the client. Needed for grant_type client_credentials. Add support for OAuth client_credentials access type, with user inactivation support. :param client_id: The client ID. :returns: The client instance or ``None``.
Below is the the instruction that describes the task: ### Input: Load the client. Needed for grant_type client_credentials. Add support for OAuth client_credentials access type, with user inactivation support. :param client_id: The client ID. :returns: The client instance or ``None``. ### Res...
def getMechanismName(self): """Return the authentication mechanism name.""" if self._server_side: mech = self._authenticator.current_mech return mech.getMechanismName() if mech else None else: return getattr(self._authenticator, 'authMech', None)
Return the authentication mechanism name.
Below is the the instruction that describes the task: ### Input: Return the authentication mechanism name. ### Response: def getMechanismName(self): """Return the authentication mechanism name.""" if self._server_side: mech = self._authenticator.current_mech return mech.getM...
def write_object_array(f, data, options): """ Writes an array of objects recursively. Writes the elements of the given object array recursively in the HDF5 Group ``options.group_for_references`` and returns an ``h5py.Reference`` array to all the elements. Parameters ---------- f : h5py.Fil...
Writes an array of objects recursively. Writes the elements of the given object array recursively in the HDF5 Group ``options.group_for_references`` and returns an ``h5py.Reference`` array to all the elements. Parameters ---------- f : h5py.File The HDF5 file handle that is open. d...
Below is the the instruction that describes the task: ### Input: Writes an array of objects recursively. Writes the elements of the given object array recursively in the HDF5 Group ``options.group_for_references`` and returns an ``h5py.Reference`` array to all the elements. Parameters --------...
def train(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None): """Blocking version of train_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
Blocking version of train_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value.
Below is the the instruction that describes the task: ### Input: Blocking version of train_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. ### Response: def train(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None): ...
def validate_arg_values(ast, bo): """Recursively validate arg (NSArg and StrArg) values Check that NSArgs are found in BELbio API and match appropriate entity_type. Check that StrArgs match their value - either default namespace or regex string Generate a WARNING if not. Args: bo: bel obj...
Recursively validate arg (NSArg and StrArg) values Check that NSArgs are found in BELbio API and match appropriate entity_type. Check that StrArgs match their value - either default namespace or regex string Generate a WARNING if not. Args: bo: bel object Returns: bel object
Below is the the instruction that describes the task: ### Input: Recursively validate arg (NSArg and StrArg) values Check that NSArgs are found in BELbio API and match appropriate entity_type. Check that StrArgs match their value - either default namespace or regex string Generate a WARNING if not. ...
def get_num_sig(self, alpha=0.05): """Print the number of significant results using various metrics.""" # Get the number of significant GO terms ctr = cx.Counter() flds = set(['FDR', 'Bonferroni', 'Benjamini', 'PValue']) for ntd in self.nts: for fld in flds: ...
Print the number of significant results using various metrics.
Below is the the instruction that describes the task: ### Input: Print the number of significant results using various metrics. ### Response: def get_num_sig(self, alpha=0.05): """Print the number of significant results using various metrics.""" # Get the number of significant GO terms ctr ...
def limit(self, limit): """ Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. """ params = join_params(self.parameters, {"limit": limit}) return self.__class__(**params)
Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts.
Below is the the instruction that describes the task: ### Input: Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. ### Response: def limit(self, limit): """ Set absolute limit on number of images to return, or set to None to return ...
def _gettype(self): ''' Return current type of this struct :returns: a typedef object (e.g. nstruct) ''' current = self lastname = getattr(current._parser, 'typedef', None) while hasattr(current, '_sub'): current = current._sub ...
Return current type of this struct :returns: a typedef object (e.g. nstruct)
Below is the the instruction that describes the task: ### Input: Return current type of this struct :returns: a typedef object (e.g. nstruct) ### Response: def _gettype(self): ''' Return current type of this struct :returns: a typedef object (e.g. nstruct) ...
def wo_resp(self, resp): """ can override for other style """ if self._data is not None: resp['res'] = self.to_str(self._data) return self.wo_json(resp)
can override for other style
Below is the the instruction that describes the task: ### Input: can override for other style ### Response: def wo_resp(self, resp): """ can override for other style """ if self._data is not None: resp['res'] = self.to_str(self._data) return self.wo_json(resp)
def set_attrs(self, username, attrs): """ set user attributes""" ldap_client = self._bind() tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise UserDoesntExist(username, self.backend_name) dn = self._byte_p2(tmp[0]) old_attrs = tmp[1...
set user attributes
Below is the the instruction that describes the task: ### Input: set user attributes ### Response: def set_attrs(self, username, attrs): """ set user attributes""" ldap_client = self._bind() tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise U...
def to_graph_tool(self): '''Converts this Graph object to a graph_tool-compatible object. Requires the graph_tool library. Note that the internal ordering of graph_tool seems to be column-major.''' # Import here to avoid ImportErrors when graph_tool isn't available. import graph_tool gt = graph_...
Converts this Graph object to a graph_tool-compatible object. Requires the graph_tool library. Note that the internal ordering of graph_tool seems to be column-major.
Below is the the instruction that describes the task: ### Input: Converts this Graph object to a graph_tool-compatible object. Requires the graph_tool library. Note that the internal ordering of graph_tool seems to be column-major. ### Response: def to_graph_tool(self): '''Converts this Graph object to...
def rfdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0): """ Distributed version of tree_distance.rfdist Parameters: two valid newick strings and a boolean """ tree_a = Tree(newick_string_a) tree_b = Tree(newick_string_b) return treedist.rfdist(tree_...
Distributed version of tree_distance.rfdist Parameters: two valid newick strings and a boolean
Below is the the instruction that describes the task: ### Input: Distributed version of tree_distance.rfdist Parameters: two valid newick strings and a boolean ### Response: def rfdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0): """ Distributed version of tre...
def sanitize(s, strict=True): """ Sanitize a string. Spaces are converted to underscore; if strict=True they are then removed. Parameters ---------- s : str String to sanitize strict : bool If True, only alphanumeric characters are allowed. If False, a limited set ...
Sanitize a string. Spaces are converted to underscore; if strict=True they are then removed. Parameters ---------- s : str String to sanitize strict : bool If True, only alphanumeric characters are allowed. If False, a limited set of additional characters (-._) will be all...
Below is the the instruction that describes the task: ### Input: Sanitize a string. Spaces are converted to underscore; if strict=True they are then removed. Parameters ---------- s : str String to sanitize strict : bool If True, only alphanumeric characters are allowed. If Fa...
def permutation_entropy(x, n, tau): """Compute Permutation Entropy of a given time series x, specified by permutation order n and embedding lag tau. Parameters ---------- x list a time series n integer Permutation order tau integer Embed...
Compute Permutation Entropy of a given time series x, specified by permutation order n and embedding lag tau. Parameters ---------- x list a time series n integer Permutation order tau integer Embedding lag Returns ---------- P...
Below is the the instruction that describes the task: ### Input: Compute Permutation Entropy of a given time series x, specified by permutation order n and embedding lag tau. Parameters ---------- x list a time series n integer Permutation order tau ...
def load_sampleset(self, f, name): '''Read the sampleset from using the HDF5 format. Name is usually in {train, test}.''' self.encoder_x = np.array(f[name + '_encoder_x']) self.decoder_x = np.array(f[name + '_decoder_x']) self.decoder_y = np.array(f[name + '_decoder_y'])
Read the sampleset from using the HDF5 format. Name is usually in {train, test}.
Below is the the instruction that describes the task: ### Input: Read the sampleset from using the HDF5 format. Name is usually in {train, test}. ### Response: def load_sampleset(self, f, name): '''Read the sampleset from using the HDF5 format. Name is usually in {train, test}.''' self.encoder_x = ...
def setParentAnalysisRequest(self, value): """Sets a parent analysis request, making the current a partition """ self.Schema().getField("ParentAnalysisRequest").set(self, value) if not value: noLongerProvides(self, IAnalysisRequestPartition) else: alsoProv...
Sets a parent analysis request, making the current a partition
Below is the the instruction that describes the task: ### Input: Sets a parent analysis request, making the current a partition ### Response: def setParentAnalysisRequest(self, value): """Sets a parent analysis request, making the current a partition """ self.Schema().getField("ParentAnalys...
def fill(self, *args): """ Apply a solid fill to your chart args are of the form <fill type>,<fill style>,... fill type must be one of c,bg,a fill style must be one of s,lg,ls the rest of the args refer to the particular style APIPARAM: chf """ a,b...
Apply a solid fill to your chart args are of the form <fill type>,<fill style>,... fill type must be one of c,bg,a fill style must be one of s,lg,ls the rest of the args refer to the particular style APIPARAM: chf
Below is the the instruction that describes the task: ### Input: Apply a solid fill to your chart args are of the form <fill type>,<fill style>,... fill type must be one of c,bg,a fill style must be one of s,lg,ls the rest of the args refer to the particular style APIPARAM: c...
def get_img_attrs(self, style=None, **kwargs): """ Get an attribute list (src, srcset, style, et al) for the image. style -- an optional list of CSS style fragments Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x'] """ add = {} if '...
Get an attribute list (src, srcset, style, et al) for the image. style -- an optional list of CSS style fragments Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x']
Below is the the instruction that describes the task: ### Input: Get an attribute list (src, srcset, style, et al) for the image. style -- an optional list of CSS style fragments Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x'] ### Response: def get_img_attrs...
def get_by_index(self, i): """Look up a gene set by its index. Parameters ---------- i: int The index of the gene set. Returns ------- GeneSet The gene set. Raises ------ ValueError If the given index ...
Look up a gene set by its index. Parameters ---------- i: int The index of the gene set. Returns ------- GeneSet The gene set. Raises ------ ValueError If the given index is out of bounds.
Below is the the instruction that describes the task: ### Input: Look up a gene set by its index. Parameters ---------- i: int The index of the gene set. Returns ------- GeneSet The gene set. Raises ------ ValueError ...
def getLabel(self): """Returns symbolic path to this MIB variable. Meaning a sequence of symbolic identifications for each of parent MIB objects in MIB tree. Returns ------- tuple sequence of names of nodes in a MIB tree from the top of the tree ...
Returns symbolic path to this MIB variable. Meaning a sequence of symbolic identifications for each of parent MIB objects in MIB tree. Returns ------- tuple sequence of names of nodes in a MIB tree from the top of the tree towards this MIB variable. ...
Below is the the instruction that describes the task: ### Input: Returns symbolic path to this MIB variable. Meaning a sequence of symbolic identifications for each of parent MIB objects in MIB tree. Returns ------- tuple sequence of names of nodes in a MIB tree...
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
initialize visit variables and statistics
Below is the the instruction that describes the task: ### Input: initialize visit variables and statistics ### Response: def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=...
def _check_for_fail_message(self, transport, exc_info, timeout): # pylint: disable=no-self-use """Check for a 'FAIL' message from transport. This method always raises, if 'FAIL' was read, it will raise an AdbRemoteError with the message, otherwise it will raise based on exc_info, which should be a tup...
Check for a 'FAIL' message from transport. This method always raises, if 'FAIL' was read, it will raise an AdbRemoteError with the message, otherwise it will raise based on exc_info, which should be a tuple as per sys.exc_info(). Args: transport: Transport from which to read for a 'FAIL' message...
Below is the the instruction that describes the task: ### Input: Check for a 'FAIL' message from transport. This method always raises, if 'FAIL' was read, it will raise an AdbRemoteError with the message, otherwise it will raise based on exc_info, which should be a tuple as per sys.exc_info(). Arg...
def config_parse(files=None, config=None, config_profile=".fissconfig", **kwargs): ''' Read initial configuration state, from named config files; store this state within a config dictionary (which may be nested) whose keys may also be referenced as attributes (safely, defaulting to None if unset). A ...
Read initial configuration state, from named config files; store this state within a config dictionary (which may be nested) whose keys may also be referenced as attributes (safely, defaulting to None if unset). A config object may be passed in, as a way of accumulating or overwriting configuration sta...
Below is the the instruction that describes the task: ### Input: Read initial configuration state, from named config files; store this state within a config dictionary (which may be nested) whose keys may also be referenced as attributes (safely, defaulting to None if unset). A config object may be pas...
def get_design_document(self, ddoc_id): """ Retrieves a design document. If a design document exists remotely then that content is wrapped in a DesignDocument object and returned to the caller. Otherwise a "shell" DesignDocument object is returned. :param str ddoc_id: Design d...
Retrieves a design document. If a design document exists remotely then that content is wrapped in a DesignDocument object and returned to the caller. Otherwise a "shell" DesignDocument object is returned. :param str ddoc_id: Design document id :returns: A DesignDocument instance, if ...
Below is the the instruction that describes the task: ### Input: Retrieves a design document. If a design document exists remotely then that content is wrapped in a DesignDocument object and returned to the caller. Otherwise a "shell" DesignDocument object is returned. :param str ddoc_id:...
def profiling(self): """A generator which profiles then broadcasts the result. Implement sleeping loop using this:: def profile_periodically(self): for __ in self.profiling(): time.sleep(self.interval) """ self._log_profiler_started() ...
A generator which profiles then broadcasts the result. Implement sleeping loop using this:: def profile_periodically(self): for __ in self.profiling(): time.sleep(self.interval)
Below is the the instruction that describes the task: ### Input: A generator which profiles then broadcasts the result. Implement sleeping loop using this:: def profile_periodically(self): for __ in self.profiling(): time.sleep(self.interval) ### Response: def...
def get_plan(self, nodes=None): """ Retrieve a plan, e.g. a list of fixtures to be loaded sorted on dependency. :param list nodes: list of nodes to be loaded. :return: """ if nodes: plan = self.graph.resolve_nodes(nodes) else: plan...
Retrieve a plan, e.g. a list of fixtures to be loaded sorted on dependency. :param list nodes: list of nodes to be loaded. :return:
Below is the the instruction that describes the task: ### Input: Retrieve a plan, e.g. a list of fixtures to be loaded sorted on dependency. :param list nodes: list of nodes to be loaded. :return: ### Response: def get_plan(self, nodes=None): """ Retrieve a plan, e.g. a lis...
def to_ufo_paths(self, ufo_glyph, layer): """Draw .glyphs paths onto a pen.""" pen = ufo_glyph.getPointPen() for path in layer.paths: # the list is changed below, otherwise you can't draw more than once # per session. nodes = list(path.nodes) for node in nodes: s...
Draw .glyphs paths onto a pen.
Below is the the instruction that describes the task: ### Input: Draw .glyphs paths onto a pen. ### Response: def to_ufo_paths(self, ufo_glyph, layer): """Draw .glyphs paths onto a pen.""" pen = ufo_glyph.getPointPen() for path in layer.paths: # the list is changed below, otherwise you can't d...
def get(self,path): """ permet de récupérer une config Args: path (String): Nom d'une config Returns: type: String la valeur de la config ou None """ path = path.upper() if path in self._configCache: re...
permet de récupérer une config Args: path (String): Nom d'une config Returns: type: String la valeur de la config ou None
Below is the the instruction that describes the task: ### Input: permet de récupérer une config Args: path (String): Nom d'une config Returns: type: String la valeur de la config ou None ### Response: def get(self,path): """ permet d...
def work_cancel(self, hash): """ Stop generating **work** for block .. enable_control required :param hash: Hash to stop generating work for :type hash: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.work_cancel( ... hash="718CC2121C3E641059B...
Stop generating **work** for block .. enable_control required :param hash: Hash to stop generating work for :type hash: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.work_cancel( ... hash="718CC2121C3E641059BC1C2CFC45666C99E8AE922F7A807B7D07B62C995D79E2" ...
Below is the the instruction that describes the task: ### Input: Stop generating **work** for block .. enable_control required :param hash: Hash to stop generating work for :type hash: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.work_cancel( ... hash=...
def new(self): """ The new value present in the event. """ ori = self.original.action if isinstance(ori, ( types.ChannelAdminLogEventActionChangeAbout, types.ChannelAdminLogEventActionChangeTitle, types.ChannelAdminLogEventActionCha...
The new value present in the event.
Below is the the instruction that describes the task: ### Input: The new value present in the event. ### Response: def new(self): """ The new value present in the event. """ ori = self.original.action if isinstance(ori, ( types.ChannelAdminLogEventActionChang...
def add_namespace_uri(self, ns_uri, prefix=None, schema_location=None): """Adds a new namespace to this set, optionally with a prefix and schema location URI. If the namespace already exists, the given prefix and schema location are merged with the existing entry: * If non-N...
Adds a new namespace to this set, optionally with a prefix and schema location URI. If the namespace already exists, the given prefix and schema location are merged with the existing entry: * If non-None, ``prefix`` is added to the set. The preferred prefix is not m...
Below is the the instruction that describes the task: ### Input: Adds a new namespace to this set, optionally with a prefix and schema location URI. If the namespace already exists, the given prefix and schema location are merged with the existing entry: * If non-None, ``prefix`...