code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
async def serialize_properties(inputs: 'Inputs', property_deps: Dict[str, List['Resource']], input_transformer: Optional[Callable[[str], str]] = None) -> struct_pb2.Struct: """ Serializes an arbitrary Input bag into a Protobuf structure, keeping trac...
Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list of dependent resources in the `deps` list. Serializing properties is inherently async because it awaits any futures that are contained transitively within the input bag.
Below is the the instruction that describes the task: ### Input: Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list of dependent resources in the `deps` list. Serializing properties is inherently async because it awaits any futures that are contained transitively within t...
def JSON_NumpyArrayEncoder(obj): '''Define Specialize JSON encoder for numpy array''' if isinstance(obj, np.ndarray): return {'numpyArray': obj.tolist(), 'dtype': obj.dtype.__str__()} elif isinstance(obj, np.generic): return np.asscalar(obj) else: print type(obj) ...
Define Specialize JSON encoder for numpy array
Below is the the instruction that describes the task: ### Input: Define Specialize JSON encoder for numpy array ### Response: def JSON_NumpyArrayEncoder(obj): '''Define Specialize JSON encoder for numpy array''' if isinstance(obj, np.ndarray): return {'numpyArray': obj.tolist(), 'dt...
def find_intersections(x, a, b, direction='all'): """Calculate the best estimate of intersection. Calculates the best estimates of the intersection of two y-value data sets that share a common x-value set. Parameters ---------- x : array-like 1-dimensional array of numeric x-values ...
Calculate the best estimate of intersection. Calculates the best estimates of the intersection of two y-value data sets that share a common x-value set. Parameters ---------- x : array-like 1-dimensional array of numeric x-values a : array-like 1-dimensional array of y-values f...
Below is the the instruction that describes the task: ### Input: Calculate the best estimate of intersection. Calculates the best estimates of the intersection of two y-value data sets that share a common x-value set. Parameters ---------- x : array-like 1-dimensional array of numeric ...
def fold_text_string(self, prefix, hidden, **kwargs): """ :param str prefix: :param str hidden: :param kwargs: passed to :func:`fold_text` :rtype: str """ import io output_buf = io.StringIO() self.fold_text(prefix=prefix, hidden=hidden, file=output...
:param str prefix: :param str hidden: :param kwargs: passed to :func:`fold_text` :rtype: str
Below is the the instruction that describes the task: ### Input: :param str prefix: :param str hidden: :param kwargs: passed to :func:`fold_text` :rtype: str ### Response: def fold_text_string(self, prefix, hidden, **kwargs): """ :param str prefix: :param str hidden:...
def CO_ratio(self,ifig,ixaxis): """ plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either 'time' or 'model...
plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either 'time' or 'model' The default is 'model'
Below is the the instruction that describes the task: ### Input: plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either...
def _calc(count, last_count, start_time, max_count, speed_calc_cycles, q, last_speed, lock): """do the pre calculations in order to get TET, speed, TTG :param count: count ...
do the pre calculations in order to get TET, speed, TTG :param count: count :param last_count: count at the last call, allows to treat the case of no progress between sequential calls :param start_time: the time when start was triggered ...
Below is the the instruction that describes the task: ### Input: do the pre calculations in order to get TET, speed, TTG :param count: count :param last_count: count at the last call, allows to treat the case of no progress between sequential calls ...
def check_forbidden_filename(filename, destiny_os=os.name, restricted_names=restricted_names): ''' Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_en...
Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (or filesystem) or not :rtype: bool
Below is the the instruction that describes the task: ### Input: Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (o...
def handle_combined_input(args): """Check for cases where we have a combined input nested list. In these cases the CWL will be double nested: [[[rec_a], [rec_b]]] and we remove the outer nesting. """ cur_args = args[:] while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)): ...
Check for cases where we have a combined input nested list. In these cases the CWL will be double nested: [[[rec_a], [rec_b]]] and we remove the outer nesting.
Below is the the instruction that describes the task: ### Input: Check for cases where we have a combined input nested list. In these cases the CWL will be double nested: [[[rec_a], [rec_b]]] and we remove the outer nesting. ### Response: def handle_combined_input(args): """Check for cases where...
def get_filetypes(filelist, path=None, size=os.path.getsize): """ Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype) """ path = ...
Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype)
Below is the the instruction that describes the task: ### Input: Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype) ### Response: def g...
def sanitize_excel_sheet_name(sheet_name, replacement_text=""): """ Replace invalid characters for an Excel sheet name within the ``sheet_name`` with the ``replacement_text``. Invalid characters are as follows: |invalid_excel_sheet_chars|. The ``sheet_name`` truncate to 31 characters (max sh...
Replace invalid characters for an Excel sheet name within the ``sheet_name`` with the ``replacement_text``. Invalid characters are as follows: |invalid_excel_sheet_chars|. The ``sheet_name`` truncate to 31 characters (max sheet name length of Excel) from the head, if the length of the name is ex...
Below is the the instruction that describes the task: ### Input: Replace invalid characters for an Excel sheet name within the ``sheet_name`` with the ``replacement_text``. Invalid characters are as follows: |invalid_excel_sheet_chars|. The ``sheet_name`` truncate to 31 characters (max sheet nam...
def run(self, event, lambda_context): """Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. If metrics ex...
Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. If metrics execution option is enabled, custodian will generat...
Below is the the instruction that describes the task: ### Input: Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. ...
def _filter_matrix_rows(cls, matrix): '''matrix = output from _to_matrix''' indexes_to_keep = [] for i in range(len(matrix)): keep_row = False for element in matrix[i]: if element not in {'NA', 'no'}: keep_row = True ...
matrix = output from _to_matrix
Below is the the instruction that describes the task: ### Input: matrix = output from _to_matrix ### Response: def _filter_matrix_rows(cls, matrix): '''matrix = output from _to_matrix''' indexes_to_keep = [] for i in range(len(matrix)): keep_row = False for element ...
def getL4PredictedActiveCells(self): """ Returns the predicted active cells in each column in L4. """ predictedActive = [] for i in xrange(self.numColumns): region = self.network.regions["L4Column_" + str(i)] predictedActive.append( region.getOutputData("predictedActiveCells").no...
Returns the predicted active cells in each column in L4.
Below is the the instruction that describes the task: ### Input: Returns the predicted active cells in each column in L4. ### Response: def getL4PredictedActiveCells(self): """ Returns the predicted active cells in each column in L4. """ predictedActive = [] for i in xrange(self.numColumns): ...
def add_neighbours(self): """ Add all the pixels at max order in the neighbourhood of the moc """ time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order)) intervals_arr = self._interval_set._intervals intervals_arr[:, 0] = np.maximum(intervals_arr[:, 0] - time...
Add all the pixels at max order in the neighbourhood of the moc
Below is the the instruction that describes the task: ### Input: Add all the pixels at max order in the neighbourhood of the moc ### Response: def add_neighbours(self): """ Add all the pixels at max order in the neighbourhood of the moc """ time_delta = 1 << (2*(IntervalSet.HPY_MAX...
def get_token(self): """ Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file cont...
Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy cont...
Below is the the instruction that describes the task: ### Input: Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form ...
def compute_and_cache_missing_buckets(self, start_time, end_time, untrusted_time, force_recompute=False): """ Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to av...
Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. For any buckets where all events would have occurred before `untrusted_time`, cache the results. :param start_time: A datetim...
Below is the the instruction that describes the task: ### Input: Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. For any buckets where all events would have occurred before `untr...
def main(): """Entrypoint for ``lander`` executable.""" args = parse_args() config_logger(args) logger = structlog.get_logger(__name__) if args.show_version: # only print the version print_version() sys.exit(0) version = pkg_resources.get_distribution('lander').version ...
Entrypoint for ``lander`` executable.
Below is the the instruction that describes the task: ### Input: Entrypoint for ``lander`` executable. ### Response: def main(): """Entrypoint for ``lander`` executable.""" args = parse_args() config_logger(args) logger = structlog.get_logger(__name__) if args.show_version: # only prin...
def resolve_command(self, excmd): """Parse command and dispatch it (to schedulers for example) if necessary If the command is not global it will be executed. :param excmd: external command to handle :type excmd: alignak.external_command.ExternalCommand :return: result of command...
Parse command and dispatch it (to schedulers for example) if necessary If the command is not global it will be executed. :param excmd: external command to handle :type excmd: alignak.external_command.ExternalCommand :return: result of command parsing. None for an invalid command.
Below is the the instruction that describes the task: ### Input: Parse command and dispatch it (to schedulers for example) if necessary If the command is not global it will be executed. :param excmd: external command to handle :type excmd: alignak.external_command.ExternalCommand :r...
def scaled_pressure2_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' Barometer readings for 2nd barometer time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs :...
Barometer readings for 2nd barometer time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs : Absolute pressure (hectopascal) (float) press_diff : Differential pressure 1 (hectopascal) (float) ...
Below is the the instruction that describes the task: ### Input: Barometer readings for 2nd barometer time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs : Absolute pressure (hectopascal) (float) press_diff ...
def filter_leading_non_json_lines(buf): ''' used to avoid random output from SSH at the top of JSON output, like messages from tcagetattr, or where dropbear spews MOTD on every single command (which is nuts). need to filter anything which starts not with '{', '[', ', '=' or is an empty line. filter...
used to avoid random output from SSH at the top of JSON output, like messages from tcagetattr, or where dropbear spews MOTD on every single command (which is nuts). need to filter anything which starts not with '{', '[', ', '=' or is an empty line. filter only leading lines since multiline JSON is valid.
Below is the the instruction that describes the task: ### Input: used to avoid random output from SSH at the top of JSON output, like messages from tcagetattr, or where dropbear spews MOTD on every single command (which is nuts). need to filter anything which starts not with '{', '[', ', '=' or is an empty...
def json_to_class(cls, json_str): """ :type cls: T|type :type json_str: str :rtype: T """ obj_raw = json.loads(json_str) return deserialize(cls, obj_raw)
:type cls: T|type :type json_str: str :rtype: T
Below is the the instruction that describes the task: ### Input: :type cls: T|type :type json_str: str :rtype: T ### Response: def json_to_class(cls, json_str): """ :type cls: T|type :type json_str: str :rtype: T """ obj_raw = json.loads(json_str) return deserialize(cls, obj...
def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affi...
Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering.
Below is the the instruction that describes the task: ### Input: Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storin...
def process_config(config, config_data): """ Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the c...
Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the config_data. :param config_data: The configura...
Below is the the instruction that describes the task: ### Input: Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configura...
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None: """ Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema. :param shex: Schema """ self.pfx = None if shex is not None: if isinstance(shex, ShExJ.Schema): ...
Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema. :param shex: Schema
Below is the the instruction that describes the task: ### Input: Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema. :param shex: Schema ### Response: def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None: """ Set the schema to be used. S...
def load_default_templates(self): """Load the default templates""" for importer, modname, is_pkg in pkgutil.iter_modules(templates.__path__): self.register_template('.'.join((templates.__name__, modname)))
Load the default templates
Below is the the instruction that describes the task: ### Input: Load the default templates ### Response: def load_default_templates(self): """Load the default templates""" for importer, modname, is_pkg in pkgutil.iter_modules(templates.__path__): self.register_template('.'.join((templa...
def iter_stack_frames(frames=None): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. """ if not frames: frames = inspect.stack()[1:] for frame, lineno in ((f[0], f[2]) for f in r...
Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable.
Below is the the instruction that describes the task: ### Input: Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. ### Response: def iter_stack_frames(frames=None): """ Given an optional list of fram...
def get_ws_subscriptions(self, apiname): """Returns the websocket subscriptions""" try: return self.services_by_name\ .get(apiname)\ .get("subscriptions")\ .copy() except AttributeError: raise Exception(f"Couldn'...
Returns the websocket subscriptions
Below is the the instruction that describes the task: ### Input: Returns the websocket subscriptions ### Response: def get_ws_subscriptions(self, apiname): """Returns the websocket subscriptions""" try: return self.services_by_name\ .get(apiname)\ ...
def points(self): """ returns a pointer to the points as a numpy object """ vtk_data = self.GetPoints().GetData() arr = vtk_to_numpy(vtk_data) return vtki_ndarray(arr, vtk_data)
returns a pointer to the points as a numpy object
Below is the the instruction that describes the task: ### Input: returns a pointer to the points as a numpy object ### Response: def points(self): """ returns a pointer to the points as a numpy object """ vtk_data = self.GetPoints().GetData() arr = vtk_to_numpy(vtk_data) return vtki...
def addch(window, y, x, ch, attr): """ Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088 """ if sys.version_info[:3] == (3, 4, 0): y, x = x, y window.addch(y, x, ch, attr)
Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088
Below is the the instruction that describes the task: ### Input: Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088 ### Response: def addch(window, y, x, ch, attr): """ Curses addch() method that fixes a major bug in python 3.4. See h...
def impersonate(self, user, enterprise): """ Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation """ if not user or not enterprise: raise Val...
Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation
Below is the the instruction that describes the task: ### Input: Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation ### Response: def impersonate(self, user, enterprise): ...
def generate_token(self, *args): """ Convert a list of integers or strings, specified by ``*args``, into an encrypted, timestamped, and signed token. Note: strings may not contain any ``'|'`` characters, nor start with a ``'~'`` character as these are used as separators and integer indicators f...
Convert a list of integers or strings, specified by ``*args``, into an encrypted, timestamped, and signed token. Note: strings may not contain any ``'|'`` characters, nor start with a ``'~'`` character as these are used as separators and integer indicators for encoding. Example: :: ...
Below is the the instruction that describes the task: ### Input: Convert a list of integers or strings, specified by ``*args``, into an encrypted, timestamped, and signed token. Note: strings may not contain any ``'|'`` characters, nor start with a ``'~'`` character as these are used as separators ...
def _begin(self, connection, filterargs=(), escape=True): """ Begins an asynchronous search and returns the message id to retrieve the results. filterargs is an object that will be used for expansion of the filter string. If escape is True, values in filterargs will be escaped. ...
Begins an asynchronous search and returns the message id to retrieve the results. filterargs is an object that will be used for expansion of the filter string. If escape is True, values in filterargs will be escaped.
Below is the the instruction that describes the task: ### Input: Begins an asynchronous search and returns the message id to retrieve the results. filterargs is an object that will be used for expansion of the filter string. If escape is True, values in filterargs will be escaped. ### Respo...
def multi_segment(annotation, sr=22050, length=None, **kwargs): '''Sonify multi-level segmentations''' # Pentatonic scale, because why not PENT = [1, 32./27, 4./3, 3./2, 16./9] DURATION = 0.1 h_int, _ = hierarchy_flatten(annotation) if length is None: length = int(sr * (max(np.max(_) ...
Sonify multi-level segmentations
Below is the the instruction that describes the task: ### Input: Sonify multi-level segmentations ### Response: def multi_segment(annotation, sr=22050, length=None, **kwargs): '''Sonify multi-level segmentations''' # Pentatonic scale, because why not PENT = [1, 32./27, 4./3, 3./2, 16./9] DURATION ...
def merge(config): """Merge the current branch into master.""" repo = config.repo active_branch = repo.active_branch if active_branch.name == "master": error_out("You're already on the master branch.") if repo.is_dirty(): error_out( 'Repo is "dirty". ({})'.format( ...
Merge the current branch into master.
Below is the the instruction that describes the task: ### Input: Merge the current branch into master. ### Response: def merge(config): """Merge the current branch into master.""" repo = config.repo active_branch = repo.active_branch if active_branch.name == "master": error_out("You're alr...
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections...
Below is the the instruction that describes the task: ### Input: Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- secti...
def offset(self, position): """Offset of given position from stranded start of this locus. For example, if a Locus goes from 10..20 and is on the negative strand, then the offset of position 13 is 7, whereas if the Locus is on the positive strand, then the offset is 3. """ ...
Offset of given position from stranded start of this locus. For example, if a Locus goes from 10..20 and is on the negative strand, then the offset of position 13 is 7, whereas if the Locus is on the positive strand, then the offset is 3.
Below is the the instruction that describes the task: ### Input: Offset of given position from stranded start of this locus. For example, if a Locus goes from 10..20 and is on the negative strand, then the offset of position 13 is 7, whereas if the Locus is on the positive strand, then the ...
def _ConsumeAnyTypeUrl(self, tokenizer): """Consumes a google.protobuf.Any type URL and returns the type name.""" # Consume "type.googleapis.com/". tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() toke...
Consumes a google.protobuf.Any type URL and returns the type name.
Below is the the instruction that describes the task: ### Input: Consumes a google.protobuf.Any type URL and returns the type name. ### Response: def _ConsumeAnyTypeUrl(self, tokenizer): """Consumes a google.protobuf.Any type URL and returns the type name.""" # Consume "type.googleapis.com/". tokenizer...
def flattened_labels(self): """ Return a sequence of tuples, each containing the flattened hierarchy of category labels for a leaf category. Each tuple is in parent -> child order, e.g. ``('US', 'CA', 'San Francisco')``, with the leaf category appearing last. If this categories c...
Return a sequence of tuples, each containing the flattened hierarchy of category labels for a leaf category. Each tuple is in parent -> child order, e.g. ``('US', 'CA', 'San Francisco')``, with the leaf category appearing last. If this categories collection is non-hierarchical, each tupl...
Below is the the instruction that describes the task: ### Input: Return a sequence of tuples, each containing the flattened hierarchy of category labels for a leaf category. Each tuple is in parent -> child order, e.g. ``('US', 'CA', 'San Francisco')``, with the leaf category appearing last....
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float`...
The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int`
Below is the the instruction that describes the task: ### Input: The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: ...
def get_event_sort_key(self, event_type): """Return the process sort key""" # Process sort depending on alert type if event_type.startswith("MEM"): # Sort TOP process by memory_percent ret = 'memory_percent' elif event_type.startswith("CPU_IOWAIT"): # ...
Return the process sort key
Below is the the instruction that describes the task: ### Input: Return the process sort key ### Response: def get_event_sort_key(self, event_type): """Return the process sort key""" # Process sort depending on alert type if event_type.startswith("MEM"): # Sort TOP process by me...
def windchill(temperature, speed, face_level_winds=False, mask_undefined=True): r"""Calculate the Wind Chill Temperature Index (WCTI). Calculates WCTI from the current temperature and wind speed using the formula outlined by the FCM [FCMR192003]_. Specifically, these formulas assume that wind speed is...
r"""Calculate the Wind Chill Temperature Index (WCTI). Calculates WCTI from the current temperature and wind speed using the formula outlined by the FCM [FCMR192003]_. Specifically, these formulas assume that wind speed is measured at 10m. If, instead, the speeds are measured at face level, the winds...
Below is the the instruction that describes the task: ### Input: r"""Calculate the Wind Chill Temperature Index (WCTI). Calculates WCTI from the current temperature and wind speed using the formula outlined by the FCM [FCMR192003]_. Specifically, these formulas assume that wind speed is measured at ...
def _handle(self, msg): """ Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message` """ def handler_yielder(): for handler in self.handlers: yield handler def handle...
Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message`
Below is the the instruction that describes the task: ### Input: Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message` ### Response: def _handle(self, msg): """ Pass a received message to the registered handlers....
def shrink(script, iterations=1): """ Shrink (erode, reduce) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to shrink the selection. Layer stack: No impacts Me...
Shrink (erode, reduce) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to shrink the selection. Layer stack: No impacts MeshLab versions: 2016.12 1....
Below is the the instruction that describes the task: ### Input: Shrink (erode, reduce) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to shrink the selection. Layer stack:...
def scrub(data, units=False): """ For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed. """ units = [i.unit if hasattr(i, 'unit') else 1 for i in data] data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=...
For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed.
Below is the the instruction that describes the task: ### Input: For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed. ### Response: def scrub(data, units=False): """ For input data [w,f,e] or [w,f] returns the list with N...
def _as_dict(self, r): """Convert the record to a dictionary using field names as keys.""" d = dict() for i, f in enumerate(self._field_names): d[f] = r[i] if i < len(r) else None return d
Convert the record to a dictionary using field names as keys.
Below is the the instruction that describes the task: ### Input: Convert the record to a dictionary using field names as keys. ### Response: def _as_dict(self, r): """Convert the record to a dictionary using field names as keys.""" d = dict() for i, f in enumerate(self._field_names): ...
def init(): ''' Get an sqlite3 connection, and initialize the package database if necessary ''' if not os.path.exists(__opts__['spm_cache_dir']): log.debug('Creating SPM cache directory at %s', __opts__['spm_db']) os.makedirs(__opts__['spm_cache_dir']) if not os.path.exists(__opts__...
Get an sqlite3 connection, and initialize the package database if necessary
Below is the the instruction that describes the task: ### Input: Get an sqlite3 connection, and initialize the package database if necessary ### Response: def init(): ''' Get an sqlite3 connection, and initialize the package database if necessary ''' if not os.path.exists(__opts__['spm_cache_dir'])...
def get_row_dict(self, row_idx): """ Return a dictionary representation for a matrix row :param row_idx: which row :return: a dict of feature keys/values, not including ones which are the default value """ try: row = self._rows[row_idx] except TypeError: ...
Return a dictionary representation for a matrix row :param row_idx: which row :return: a dict of feature keys/values, not including ones which are the default value
Below is the the instruction that describes the task: ### Input: Return a dictionary representation for a matrix row :param row_idx: which row :return: a dict of feature keys/values, not including ones which are the default value ### Response: def get_row_dict(self, row_idx): """ Return a ...
def fdot(x, y): """Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3. """ xx = x.reshape(-1, x.shape[-1]) yy = y.reshape(y.shape[0], -1) xx = numpy.ascontiguousarray(xx) yy = numpy.ascontiguousarray(yy) r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1...
Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3.
Below is the the instruction that describes the task: ### Input: Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3. ### Response: def fdot(x, y): """Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3. """ xx = x.reshape(-1, x.shape[-1]) yy = y....
def getBriefAndDetailedRST(textRoot, node): ''' Given an input ``node``, return a tuple of strings where the first element of the return is the ``brief`` description and the second is the ``detailed`` description. .. todo:: actually document this ''' node_xml_contents = utils.nodeCompoundXM...
Given an input ``node``, return a tuple of strings where the first element of the return is the ``brief`` description and the second is the ``detailed`` description. .. todo:: actually document this
Below is the the instruction that describes the task: ### Input: Given an input ``node``, return a tuple of strings where the first element of the return is the ``brief`` description and the second is the ``detailed`` description. .. todo:: actually document this ### Response: def getBriefAndDetailedR...
def store_state(node, reaching, defined, stack): """Push the final state of the primal onto the stack for the adjoint. Python's scoping rules make it possible for variables to not be defined in certain blocks based on the control flow path taken at runtime. In order to make sure we don't try to push non-existi...
Push the final state of the primal onto the stack for the adjoint. Python's scoping rules make it possible for variables to not be defined in certain blocks based on the control flow path taken at runtime. In order to make sure we don't try to push non-existing variables onto the stack, we defined these variab...
Below is the the instruction that describes the task: ### Input: Push the final state of the primal onto the stack for the adjoint. Python's scoping rules make it possible for variables to not be defined in certain blocks based on the control flow path taken at runtime. In order to make sure we don't try to ...
def suspend_to_background(self, suspend_group=True): """ (Not thread safe -- to be called from inside the key bindings.) Suspend process. :param suspend_group: When true, suspend the whole process group. (This is the default, and probably what you want.) """ ...
(Not thread safe -- to be called from inside the key bindings.) Suspend process. :param suspend_group: When true, suspend the whole process group. (This is the default, and probably what you want.)
Below is the the instruction that describes the task: ### Input: (Not thread safe -- to be called from inside the key bindings.) Suspend process. :param suspend_group: When true, suspend the whole process group. (This is the default, and probably what you want.) ### Response: def suspe...
def load_hdf(cls, filename, path='', name=None): """ A class method to load a saved StarModel from an HDF5 file. File must have been created by a call to :func:`StarModel.save_hdf`. :param filename: H5 file to load. :param path: (optional) Path within H...
A class method to load a saved StarModel from an HDF5 file. File must have been created by a call to :func:`StarModel.save_hdf`. :param filename: H5 file to load. :param path: (optional) Path within HDF file. :return: :class:`StarModel` object.
Below is the the instruction that describes the task: ### Input: A class method to load a saved StarModel from an HDF5 file. File must have been created by a call to :func:`StarModel.save_hdf`. :param filename: H5 file to load. :param path: (optional) Path within H...
async def profile(self): """|coro| Gets the user's profile. .. note:: This only applies to non-bot accounts. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns...
|coro| Gets the user's profile. .. note:: This only applies to non-bot accounts. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns -------- :class:`Pr...
Below is the the instruction that describes the task: ### Input: |coro| Gets the user's profile. .. note:: This only applies to non-bot accounts. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the...
def fire_mixing(ys=None, FLs=None): # pragma: no cover ''' Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety: Fundamentals with Applications. 2E. Upper Saddle River, N.J: Prentice Hall, 2001. >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.0015]), FLs=[.012, .053, .031]) 0.02751...
Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety: Fundamentals with Applications. 2E. Upper Saddle River, N.J: Prentice Hall, 2001. >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.0015]), FLs=[.012, .053, .031]) 0.02751172136637643 >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.001...
Below is the the instruction that describes the task: ### Input: Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety: Fundamentals with Applications. 2E. Upper Saddle River, N.J: Prentice Hall, 2001. >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.0015]), FLs=[.012, .053, .031]) 0.0275...
def create_factor(self, tool, sources, sink, alignment_node=None): """ Creates a factor. Instantiates a single tool for all of the plates, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that var...
Creates a factor. Instantiates a single tool for all of the plates, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, an extra input stream should be used :param alignment_...
Below is the the instruction that describes the task: ### Input: Creates a factor. Instantiates a single tool for all of the plates, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, ...
def _set_pwm(self, raw_values): """ Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095). """ for i in range(len(self._pins)): self._device.set_pwm(self._pins[i], 0, raw_values[i])
Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095).
Below is the the instruction that describes the task: ### Input: Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095). ### Response: def _set_pwm(self, raw_values): """ Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4...
def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return "{} / {} ({}% completed) (~{} remaining)".format( current, total, int(current / total * 100), time_remaining)
Returns the progress ratio, percentage and time remaining.
Below is the the instruction that describes the task: ### Input: Returns the progress ratio, percentage and time remaining. ### Response: def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return "{} / {} ({}% compl...
def _set_trigger_mode(self, v, load=False): """ Setter method for trigger_mode, mapped from YANG variable /rbridge_id/event_handler/activate/name/trigger_mode (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_trigger_mode is considered as a private method...
Setter method for trigger_mode, mapped from YANG variable /rbridge_id/event_handler/activate/name/trigger_mode (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_trigger_mode is considered as a private method. Backends looking to populate this variable should ...
Below is the the instruction that describes the task: ### Input: Setter method for trigger_mode, mapped from YANG variable /rbridge_id/event_handler/activate/name/trigger_mode (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_trigger_mode is considered as a priva...
def _deconstruct_url(self, url: str) -> List[str]: """ Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern...
Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern :private:
Below is the the instruction that describes the task: ### Input: Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern ...
def clearScreen(cls): """Clear the screen""" if "win32" in sys.platform: os.system('cls') elif "linux" in sys.platform: os.system('clear') elif 'darwin' in sys.platform: os.system('clear') else: cit.err("No clearScreen for " + sys.p...
Clear the screen
Below is the the instruction that describes the task: ### Input: Clear the screen ### Response: def clearScreen(cls): """Clear the screen""" if "win32" in sys.platform: os.system('cls') elif "linux" in sys.platform: os.system('clear') elif 'darwin' in sys.pla...
def save_freesurfer_geometry(filename, obj, volume_info=None, create_stamp=None): ''' save_mgh(filename, obj) saves the given object to the given filename in the mgh format and returns the filename. All options that can be given to the to_mgh function can also be passed to this function; they are...
save_mgh(filename, obj) saves the given object to the given filename in the mgh format and returns the filename. All options that can be given to the to_mgh function can also be passed to this function; they are used to modify the object prior to exporting it.
Below is the the instruction that describes the task: ### Input: save_mgh(filename, obj) saves the given object to the given filename in the mgh format and returns the filename. All options that can be given to the to_mgh function can also be passed to this function; they are used to modify the objec...
def compile_graphql_to_gremlin(schema, graphql_string, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query...
Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to Gremlin, as a string type_equivalence_hints: optional dict of GraphQL...
Below is the the instruction that describes the task: ### Input: Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to Gremlin,...
def nms(dets, thresh): """ greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep """ x1 = dets[:, 0] y1 = dets[:, 1] x2...
greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep
Below is the the instruction that describes the task: ### Input: greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep ### Response: def n...
def external_dependencies(self): """ Return all the external images this Dockerfile will depend on These are images from self.dependent_images that aren't defined in this configuration. """ found = [] for dep in self.dependent_images: if isinstance(dep, six.s...
Return all the external images this Dockerfile will depend on These are images from self.dependent_images that aren't defined in this configuration.
Below is the the instruction that describes the task: ### Input: Return all the external images this Dockerfile will depend on These are images from self.dependent_images that aren't defined in this configuration. ### Response: def external_dependencies(self): """ Return all the external i...
def var(nums, mean_func=amean, ddof=0): r"""Calculate the variance. The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with mean :math:`\mu` and population :math:`N` is: :math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`. Cf. https://en.wikipedia.org/wiki/Variance Para...
r"""Calculate the variance. The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with mean :math:`\mu` and population :math:`N` is: :math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`. Cf. https://en.wikipedia.org/wiki/Variance Parameters ---------- nums : list ...
Below is the the instruction that describes the task: ### Input: r"""Calculate the variance. The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with mean :math:`\mu` and population :math:`N` is: :math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`. Cf. https://en.wikipedia.or...
def get_security_repository(self): """ Security repository """ from .repositories import SecurityRepository if not self.security_repo: self.security_repo = SecurityRepository(self.session) return self.security_repo
Security repository
Below is the the instruction that describes the task: ### Input: Security repository ### Response: def get_security_repository(self): """ Security repository """ from .repositories import SecurityRepository if not self.security_repo: self.security_repo = SecurityRepository(self...
def update_args(self, override_args): """Update the argument used to invoke the application Note that this will also update the dictionary of input and output files. Parameters ----------- override_args : dict Dictionary of arguments to override the current values ...
Update the argument used to invoke the application Note that this will also update the dictionary of input and output files. Parameters ----------- override_args : dict Dictionary of arguments to override the current values
Below is the the instruction that describes the task: ### Input: Update the argument used to invoke the application Note that this will also update the dictionary of input and output files. Parameters ----------- override_args : dict Dictionary of arguments to override...
def log_critical(msg, logger="TaskLogger"): """Log a CRITICAL message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged name : `str`, optional (default: "TaskLogger") Name used to retrieve the unique TaskLogger ...
Log a CRITICAL message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged name : `str`, optional (default: "TaskLogger") Name used to retrieve the unique TaskLogger Returns ------- logger : TaskLogger
Below is the the instruction that describes the task: ### Input: Log a CRITICAL message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged name : `str`, optional (default: "TaskLogger") Name used to retrieve the uniq...
def delete_model(self, model): """Ran when a model is being deleted.""" for mixin in self.post_processing_mixins: mixin.delete_model(model) super().delete_model(model)
Ran when a model is being deleted.
Below is the the instruction that describes the task: ### Input: Ran when a model is being deleted. ### Response: def delete_model(self, model): """Ran when a model is being deleted.""" for mixin in self.post_processing_mixins: mixin.delete_model(model) super().delete_model(mo...
def read_csv(filename): """Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` objects """ field_names = ('la...
Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` objects
Below is the the instruction that describes the task: ### Input: Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` ...
def idx_name_to_num(L): """ Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict: Modified metadata """ logger_jsons.info("enter idx_name_to_num") # Process the paleoData section if "paleoData" in L: L["paleoData"] = _export_section(L["paleoData"], ...
Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict: Modified metadata
Below is the the instruction that describes the task: ### Input: Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict: Modified metadata ### Response: def idx_name_to_num(L): """ Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict...
def _attach_handler_events(self, handler, events=None): """ Search handler for methods named after events, attaching to event handlers as applicable. :param object handler: Handler instance :param list events: List of event names to look for. If not specified, will do all known event na...
Search handler for methods named after events, attaching to event handlers as applicable. :param object handler: Handler instance :param list events: List of event names to look for. If not specified, will do all known event names.
Below is the the instruction that describes the task: ### Input: Search handler for methods named after events, attaching to event handlers as applicable. :param object handler: Handler instance :param list events: List of event names to look for. If not specified, will do all known event names. ##...
def filesize(self): """ Lazy evaluation of start and end of logfile. Returns None for stdin input currently. """ if self.from_stdin: return None if not self._filesize: self._calculate_bounds() return self._filesize
Lazy evaluation of start and end of logfile. Returns None for stdin input currently.
Below is the the instruction that describes the task: ### Input: Lazy evaluation of start and end of logfile. Returns None for stdin input currently. ### Response: def filesize(self): """ Lazy evaluation of start and end of logfile. Returns None for stdin input currently. ...
def make_dirs_if_dont_exist(path): """ Create directories in path if they do not exist """ if path[-1] not in ['/']: path += '/' path = os.path.dirname(path) if path != '': try: os.makedirs(path) except OSError: pass
Create directories in path if they do not exist
Below is the the instruction that describes the task: ### Input: Create directories in path if they do not exist ### Response: def make_dirs_if_dont_exist(path): """ Create directories in path if they do not exist """ if path[-1] not in ['/']: path += '/' path = os.path.dirname(path) if path != '':...
def roman_to_int(roman_string): """ Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer """ roman_string = roman_string.upper().strip() if "IIII" in roman_...
Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer
Below is the the instruction that describes the task: ### Input: Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer ### Response: def roman_to_int(roman_string): """...
def fill_heatmap(self): """Fills code heatmap and execution count dictionaries.""" for module_path, lineno, runtime in self.lines_without_stdlib: self._execution_count[module_path][lineno] += 1 self._heatmap[module_path][lineno] += runtime
Fills code heatmap and execution count dictionaries.
Below is the the instruction that describes the task: ### Input: Fills code heatmap and execution count dictionaries. ### Response: def fill_heatmap(self): """Fills code heatmap and execution count dictionaries.""" for module_path, lineno, runtime in self.lines_without_stdlib: self._exe...
def entry_point(): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: main("omego", items=[ (InstallCommand.NAME, InstallCommand), (UpgradeCommand.NAME, UpgradeCommand), (ConvertCommand.NAME, ConvertCommand), ...
External entry point which calls main() and if Stop is raised, calls sys.exit()
Below is the the instruction that describes the task: ### Input: External entry point which calls main() and if Stop is raised, calls sys.exit() ### Response: def entry_point(): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: main("omego"...
def __set_status(self, value): ''' Sets the status of the invoice. @param value:str ''' if value not in [INVOICE_DUE, INVOICE_PAID, INVOICE_CANCELED, INVOICE_IRRECOVERABLE]: raise ValueError("Invalid invoice status") self.__status = v...
Sets the status of the invoice. @param value:str
Below is the the instruction that describes the task: ### Input: Sets the status of the invoice. @param value:str ### Response: def __set_status(self, value): ''' Sets the status of the invoice. @param value:str ''' if value not in [INVOICE_DUE, INVOICE_PAID, INVOICE...
def _build_late_dispatcher(func_name): """Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that ...
Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that takes an 'obj' parameter, followed by *args and ...
Below is the the instruction that describes the task: ### Input: Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: ...
def get_pull_requests_by_project(self, project, search_criteria, max_comment_length=None, skip=None, top=None): """GetPullRequestsByProject. [Preview API] Retrieve all pull requests matching a specified criteria. :param str project: Project ID or project name :param :class:`<GitPullReque...
GetPullRequestsByProject. [Preview API] Retrieve all pull requests matching a specified criteria. :param str project: Project ID or project name :param :class:`<GitPullRequestSearchCriteria> <azure.devops.v5_1.git.models.GitPullRequestSearchCriteria>` search_criteria: Pull requests will be retur...
Below is the the instruction that describes the task: ### Input: GetPullRequestsByProject. [Preview API] Retrieve all pull requests matching a specified criteria. :param str project: Project ID or project name :param :class:`<GitPullRequestSearchCriteria> <azure.devops.v5_1.git.models.GitPul...
def write_files(dos, pdos, prefix=None, directory=None, zero_to_efermi=True): """Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. ...
Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. pdos (dict): The projected density of states. Formatted as a :obj:`dict` ...
Below is the the instruction that describes the task: ### Input: Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. pdos (dict): The...
def check_publish_block(self, block_header): """Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed. """ ...
Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed.
Below is the the instruction that describes the task: ### Input: Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed. ### ...
def _idForObject(self, defaultObject): """ Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int} """ identifier = self._allocateID() self._idsToObjects[identifier] = defaultObject return identifier
Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int}
Below is the the instruction that describes the task: ### Input: Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int} ### Response: def _idForObject(self, defaultObject): """ Generate an opaque identifier which can be used to talk about ...
def nextSunrise(date, pos): """ Returns the date of the next sunrise. """ jd = eph.nextSunrise(date.jd, pos.lat, pos.lon) return Datetime.fromJD(jd, date.utcoffset)
Returns the date of the next sunrise.
Below is the the instruction that describes the task: ### Input: Returns the date of the next sunrise. ### Response: def nextSunrise(date, pos): """ Returns the date of the next sunrise. """ jd = eph.nextSunrise(date.jd, pos.lat, pos.lon) return Datetime.fromJD(jd, date.utcoffset)
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
Check if a file exists and is non-empty.
Below is the the instruction that describes the task: ### Input: Check if a file exists and is non-empty. ### Response: def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: ...
def _get_row_sparse(self, arr_list, ctx, row_id): """ Get row_sparse data from row_sparse parameters based on row_id. """ # get row sparse params based on row ids if not isinstance(row_id, ndarray.NDArray): raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id...
Get row_sparse data from row_sparse parameters based on row_id.
Below is the the instruction that describes the task: ### Input: Get row_sparse data from row_sparse parameters based on row_id. ### Response: def _get_row_sparse(self, arr_list, ctx, row_id): """ Get row_sparse data from row_sparse parameters based on row_id. """ # get row sparse params based on r...
def set_primary_mgt(self, interface_id, auth_request=None, address=None): """ Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. F...
Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. For clusters, the primary heartbeat will NOT follow this change and should be set separately using :met...
Below is the the instruction that describes the task: ### Input: Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. For clusters, the primary heartbeat will N...
def user_exists(self, name): """Check if a given user exists.""" users = self.data['users'] for user in users: if user['name'] == name: return True return False
Check if a given user exists.
Below is the the instruction that describes the task: ### Input: Check if a given user exists. ### Response: def user_exists(self, name): """Check if a given user exists.""" users = self.data['users'] for user in users: if user['name'] == name: return True ...
def set_attr(self, **kwargs): """Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute. """ for key, value in kwargs.items(): if value is not None: if n...
Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute.
Below is the the instruction that describes the task: ### Input: Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute. ### Response: def set_attr(self, **kwargs): """Set the attribute of the...
def write_bytes(self, data: bytes, *, append=True): ''' write bytes into the file. ''' mode = 'ab' if append else 'wb' return self.write(data, mode=mode)
write bytes into the file.
Below is the the instruction that describes the task: ### Input: write bytes into the file. ### Response: def write_bytes(self, data: bytes, *, append=True): ''' write bytes into the file. ''' mode = 'ab' if append else 'wb' return self.write(data, mode=mode)
def list_items(queue): ''' List contents of a queue ''' itemstuple = _list_items(queue) items = [item[0] for item in itemstuple] return items
List contents of a queue
Below is the the instruction that describes the task: ### Input: List contents of a queue ### Response: def list_items(queue): ''' List contents of a queue ''' itemstuple = _list_items(queue) items = [item[0] for item in itemstuple] return items
def name2unicode(name): """Converts Adobe glyph names to Unicode numbers.""" if name in glyphname2unicode: return glyphname2unicode[name] m = STRIP_NAME.search(name) if not m: raise KeyError(name) return unichr(int(m.group(0)))
Converts Adobe glyph names to Unicode numbers.
Below is the the instruction that describes the task: ### Input: Converts Adobe glyph names to Unicode numbers. ### Response: def name2unicode(name): """Converts Adobe glyph names to Unicode numbers.""" if name in glyphname2unicode: return glyphname2unicode[name] m = STRIP_NAME.search(name) ...
def __set_cache(self, tokens): """ Sets the tokens cache. :param tokens: Completer tokens list. :type tokens: tuple or list """ if DefaultCompleter._DefaultCompleter__tokens.get(self.__language): return DefaultCompleter._DefaultCompleter__tokens[sel...
Sets the tokens cache. :param tokens: Completer tokens list. :type tokens: tuple or list
Below is the the instruction that describes the task: ### Input: Sets the tokens cache. :param tokens: Completer tokens list. :type tokens: tuple or list ### Response: def __set_cache(self, tokens): """ Sets the tokens cache. :param tokens: Completer tokens list. :...
def best_buy_3(self): """三日均價由下往上 """ return self.data.continuous(self.data.moving_average(self.data.price, 3)) == 1
三日均價由下往上
Below is the the instruction that describes the task: ### Input: 三日均價由下往上 ### Response: def best_buy_3(self): """三日均價由下往上 """ return self.data.continuous(self.data.moving_average(self.data.price, 3)) == 1
def highest(self): """Return the items with the higest score. If this ScoreSet is empty, returns None. """ scores = self.scores() if not scores: return None maxscore = max(map(score, scores)) return filter(lambda x: score(x) == maxscore, scores)
Return the items with the higest score. If this ScoreSet is empty, returns None.
Below is the the instruction that describes the task: ### Input: Return the items with the higest score. If this ScoreSet is empty, returns None. ### Response: def highest(self): """Return the items with the higest score. If this ScoreSet is empty, returns None. """ scores...
def _activate_thin_device(name, dm_id, size, pool): """ Provisions an LVM device-mapper thin device reflecting, DM device id 'dm_id' in the docker pool. """ table = '0 %d thin /dev/mapper/%s %s' % (int(size) // 512, pool, dm_id) cmd = ['dmsetup', 'create', name, '--table'...
Provisions an LVM device-mapper thin device reflecting, DM device id 'dm_id' in the docker pool.
Below is the the instruction that describes the task: ### Input: Provisions an LVM device-mapper thin device reflecting, DM device id 'dm_id' in the docker pool. ### Response: def _activate_thin_device(name, dm_id, size, pool): """ Provisions an LVM device-mapper thin device reflecting, ...
def _mock_imethodcall(self, methodname, namespace, response_params_rqd=None, **params): # pylint: disable=unused-argument """ Mocks the WBEMConnection._imethodcall() method. This mock calls methods within this class that fake the processing in a WBEM server (a...
Mocks the WBEMConnection._imethodcall() method. This mock calls methods within this class that fake the processing in a WBEM server (at the CIM Object level) for the varisous CIM/XML methods and return. Each function is named with the lower case method namd prepended with '_fak...
Below is the the instruction that describes the task: ### Input: Mocks the WBEMConnection._imethodcall() method. This mock calls methods within this class that fake the processing in a WBEM server (at the CIM Object level) for the varisous CIM/XML methods and return. Each function ...
def branches(): # type: () -> List[str] """ Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. """ out = shell.run( 'git branch', capture=True, never_pretend=True ).stdout.strip() return [x.strip('* \t\n...
Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo.
Below is the the instruction that describes the task: ### Input: Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. ### Response: def branches(): # type: () -> List[str] """ Return a list of branches in the current repo. Returns: ...
def _cleanup_label(label): """ Reformat the ALL CAPS OMIM labels to something more pleasant to read. This will: 1. remove the abbreviation suffixes 2. convert the roman numerals to integer numbers 3. make the text title case, except for suplied conjunctions...
Reformat the ALL CAPS OMIM labels to something more pleasant to read. This will: 1. remove the abbreviation suffixes 2. convert the roman numerals to integer numbers 3. make the text title case, except for suplied conjunctions/prepositions/articles :param label: ...
Below is the the instruction that describes the task: ### Input: Reformat the ALL CAPS OMIM labels to something more pleasant to read. This will: 1. remove the abbreviation suffixes 2. convert the roman numerals to integer numbers 3. make the text title case, except fo...
def tracktype(self, tracktype): """ When setting the track type, the valid parameters for this track type need to be set as well. """ self._tracktype = tracktype if tracktype is not None: if 'bed' in tracktype.lower(): tracktype = 'bigBed' ...
When setting the track type, the valid parameters for this track type need to be set as well.
Below is the the instruction that describes the task: ### Input: When setting the track type, the valid parameters for this track type need to be set as well. ### Response: def tracktype(self, tracktype): """ When setting the track type, the valid parameters for this track type need...