code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def decompress_messages(self, offmsgs): """ Decompress pre-defined compressed fields for each message. Msgs should be unpacked before this step. """ for offmsg in offmsgs: yield offmsg.message.key, self.decompress_fun(offmsg.message.value)
Decompress pre-defined compressed fields for each message. Msgs should be unpacked before this step.
Below is the the instruction that describes the task: ### Input: Decompress pre-defined compressed fields for each message. Msgs should be unpacked before this step. ### Response: def decompress_messages(self, offmsgs): """ Decompress pre-defined compressed fields for each message. ...
def add_file_to_archive(self, name: str) -> None: """ Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` par...
Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` params.add_file_to_archive("input_file") ``` which would...
Below is the the instruction that describes the task: ### Input: Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` para...
def stroke(self, *args): '''Set a stroke color, applying it to new paths. :param args: color in supported format ''' if args is not None: self._canvas.strokecolor = self.color(*args) return self._canvas.strokecolor
Set a stroke color, applying it to new paths. :param args: color in supported format
Below is the the instruction that describes the task: ### Input: Set a stroke color, applying it to new paths. :param args: color in supported format ### Response: def stroke(self, *args): '''Set a stroke color, applying it to new paths. :param args: color in supported format ''' ...
def support_zrangebylex(self): """ Returns True if zrangebylex is available. Checks are done in the client library (redis-py) AND the redis server. Result is cached, so done only one time. """ if not hasattr(self, '_support_zrangebylex'): try: ...
Returns True if zrangebylex is available. Checks are done in the client library (redis-py) AND the redis server. Result is cached, so done only one time.
Below is the the instruction that describes the task: ### Input: Returns True if zrangebylex is available. Checks are done in the client library (redis-py) AND the redis server. Result is cached, so done only one time. ### Response: def support_zrangebylex(self): """ Returns True if...
def get_all_pipelines(self): '''Return all pipelines as a list Returns: List[PipelineDefinition]: ''' pipelines = list(map(self.get_pipeline, self.pipeline_dict.keys())) # This does uniqueness check self._construct_solid_defs(pipelines) return pipeli...
Return all pipelines as a list Returns: List[PipelineDefinition]:
Below is the the instruction that describes the task: ### Input: Return all pipelines as a list Returns: List[PipelineDefinition]: ### Response: def get_all_pipelines(self): '''Return all pipelines as a list Returns: List[PipelineDefinition]: ''' p...
def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, self.channels_to_byte([self.channel]), self.timeout, self.status, self.led_status, self.blind_position, self.locked_inhibit_fo...
:return: bytes
Below is the the instruction that describes the task: ### Input: :return: bytes ### Response: def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, self.channels_to_byte([self.channel]), self.timeout, self.statu...
def list(cls, args): # pylint: disable=unused-argument """List all installed NApps and inform whether they are enabled.""" mgr = NAppsManager() # Add status napps = [napp + ('[ie]',) for napp in mgr.get_enabled()] napps += [napp + ('[i-]',) for napp in mgr.get_disabled()] ...
List all installed NApps and inform whether they are enabled.
Below is the the instruction that describes the task: ### Input: List all installed NApps and inform whether they are enabled. ### Response: def list(cls, args): # pylint: disable=unused-argument """List all installed NApps and inform whether they are enabled.""" mgr = NAppsManager() # Ad...
def align_to_other(self, other, mapping, self_root_pair, other_root_pair = None): ''' root atoms are atom which all other unmapped atoms will be mapped off of ''' if other_root_pair == None: other_root_pair = self_root_pair assert( len(self_root_pair) == len(other_ro...
root atoms are atom which all other unmapped atoms will be mapped off of
Below is the the instruction that describes the task: ### Input: root atoms are atom which all other unmapped atoms will be mapped off of ### Response: def align_to_other(self, other, mapping, self_root_pair, other_root_pair = None): ''' root atoms are atom which all other unmapped atoms will be ma...
def create(streamIds, **kwargs): """ Creates and loads data into a Confluence, which is a collection of River Streams. :param streamIds: (list) Each data id in this list is a list of strings: 1. river name 2. stream name 3. field name :param kwargs...
Creates and loads data into a Confluence, which is a collection of River Streams. :param streamIds: (list) Each data id in this list is a list of strings: 1. river name 2. stream name 3. field name :param kwargs: Passed into Confluence constructor :r...
Below is the the instruction that describes the task: ### Input: Creates and loads data into a Confluence, which is a collection of River Streams. :param streamIds: (list) Each data id in this list is a list of strings: 1. river name 2. stream name 3....
def marginalize(self, variables, inplace=True): """ Modifies the distribution with marginalized values. Parameters ---------- variables: iterator over any hashable object. List of variables over which marginalization is to be done. inplace: boolean ...
Modifies the distribution with marginalized values. Parameters ---------- variables: iterator over any hashable object. List of variables over which marginalization is to be done. inplace: boolean If inplace=True it will modify the distribution itself, ...
Below is the the instruction that describes the task: ### Input: Modifies the distribution with marginalized values. Parameters ---------- variables: iterator over any hashable object. List of variables over which marginalization is to be done. inplace: boolean ...
def copy_subrange_of_file(input_file, file_start, file_end, output_filehandle): """Copies the range (in bytes) between fileStart and fileEnd to the given output file handle. """ with open(input_file, 'r') as fileHandle: fileHandle.seek(file_start) data = fileHandle.read(file_end - file_s...
Copies the range (in bytes) between fileStart and fileEnd to the given output file handle.
Below is the the instruction that describes the task: ### Input: Copies the range (in bytes) between fileStart and fileEnd to the given output file handle. ### Response: def copy_subrange_of_file(input_file, file_start, file_end, output_filehandle): """Copies the range (in bytes) between fileStart and file...
def parse_config_for_selected_keys(content, keys): """ Parse a config from a magic cell body for selected config keys. For example, if 'content' is: config_item1: value1 config_item2: value2 config_item3: value3 and 'keys' are: [config_item1, config_item3] The results will be a tuple of 1. The p...
Parse a config from a magic cell body for selected config keys. For example, if 'content' is: config_item1: value1 config_item2: value2 config_item3: value3 and 'keys' are: [config_item1, config_item3] The results will be a tuple of 1. The parsed config items (dict): {config_item1: value1, config_...
Below is the the instruction that describes the task: ### Input: Parse a config from a magic cell body for selected config keys. For example, if 'content' is: config_item1: value1 config_item2: value2 config_item3: value3 and 'keys' are: [config_item1, config_item3] The results will be a tuple o...
def _which_ip_protocol(element): """ Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tuple(ipv4, ipv6) """ ...
Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tuple(ipv4, ipv6)
Below is the the instruction that describes the task: ### Input: Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tup...
def node_coord_in_direction(tile_id, direction): """ Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int """ tile_coord = tile_id_to_coord(tile_id) for node_coord ...
Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int
Below is the the instruction that describes the task: ### Input: Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int ### Response: def node_coord_in_direction(tile_id, direction)...
def check(cls): """Test to see if the running host is a RHEL installation. Checks for the presence of the "Red Hat Enterprise Linux" release string at the beginning of the NAME field in the `/etc/os-release` file and returns ``True`` if it is found, and ``False``...
Test to see if the running host is a RHEL installation. Checks for the presence of the "Red Hat Enterprise Linux" release string at the beginning of the NAME field in the `/etc/os-release` file and returns ``True`` if it is found, and ``False`` otherwise. :r...
Below is the the instruction that describes the task: ### Input: Test to see if the running host is a RHEL installation. Checks for the presence of the "Red Hat Enterprise Linux" release string at the beginning of the NAME field in the `/etc/os-release` file and returns ``True``...
def computeSlop(self, step, divisor): """Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop". """ bottom = step * math.floor(self.minValue / float(step) ...
Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop".
Below is the the instruction that describes the task: ### Input: Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop". ### Response: def computeSlop(self, step, divisor): ...
def p_generate_if_woelse(self, p): 'generate_if : IF LPAREN cond RPAREN gif_true_item' p[0] = IfStatement(p[3], p[5], None, lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
generate_if : IF LPAREN cond RPAREN gif_true_item
Below is the the instruction that describes the task: ### Input: generate_if : IF LPAREN cond RPAREN gif_true_item ### Response: def p_generate_if_woelse(self, p): 'generate_if : IF LPAREN cond RPAREN gif_true_item' p[0] = IfStatement(p[3], p[5], None, lineno=p.lineno(1)) p.set_lineno(0, p....
def addToTimeInv(self,*params): ''' Adds any number of parameters to time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_inv Returns ------- None ''' fo...
Adds any number of parameters to time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_inv Returns ------- None
Below is the the instruction that describes the task: ### Input: Adds any number of parameters to time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_inv Returns ------- None ### R...
def cli(ctx, organism="", sequence=""): """Get the features for an organism / sequence Output: A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.get_features(organism=organism, sequence=sequence)
Get the features for an organism / sequence Output: A standard apollo feature dictionary ({"features": [{...}]})
Below is the the instruction that describes the task: ### Input: Get the features for an organism / sequence Output: A standard apollo feature dictionary ({"features": [{...}]}) ### Response: def cli(ctx, organism="", sequence=""): """Get the features for an organism / sequence Output: A standard a...
def serialize(cls, obj, buf, lineLength, validate): """ Apple's Address Book is *really* weird with images, it expects base64 data to have very specific whitespace. It seems Address Book can handle PHOTO if it's not wrapped, so don't wrap it. """ if wacky_apple_photo_ser...
Apple's Address Book is *really* weird with images, it expects base64 data to have very specific whitespace. It seems Address Book can handle PHOTO if it's not wrapped, so don't wrap it.
Below is the the instruction that describes the task: ### Input: Apple's Address Book is *really* weird with images, it expects base64 data to have very specific whitespace. It seems Address Book can handle PHOTO if it's not wrapped, so don't wrap it. ### Response: def serialize(cls, obj, buf, lin...
def Size(self): """ Get the total size in bytes of the object. Returns: int: size. """ s = super(Block, self).Size() + GetVarSize(self.Transactions) return s
Get the total size in bytes of the object. Returns: int: size.
Below is the the instruction that describes the task: ### Input: Get the total size in bytes of the object. Returns: int: size. ### Response: def Size(self): """ Get the total size in bytes of the object. Returns: int: size. """ s = super(Bl...
def list_engines_by_priority(engines=None): """ Return a list of engines supported sorted by each priority. """ if engines is None: engines = ENGINES return sorted(engines, key=operator.methodcaller("priority"))
Return a list of engines supported sorted by each priority.
Below is the the instruction that describes the task: ### Input: Return a list of engines supported sorted by each priority. ### Response: def list_engines_by_priority(engines=None): """ Return a list of engines supported sorted by each priority. """ if engines is None: engines = ENGINES ...
def _queue_edge_tiles(self, dx, dy): """ Queue edge tiles and clear edge areas on buffer if needed :param dx: Edge along X axis to enqueue :param dy: Edge along Y axis to enqueue :return: None """ v = self._tile_view tw, th = self.data.tile_size self._til...
Queue edge tiles and clear edge areas on buffer if needed :param dx: Edge along X axis to enqueue :param dy: Edge along Y axis to enqueue :return: None
Below is the the instruction that describes the task: ### Input: Queue edge tiles and clear edge areas on buffer if needed :param dx: Edge along X axis to enqueue :param dy: Edge along Y axis to enqueue :return: None ### Response: def _queue_edge_tiles(self, dx, dy): """ Queue edge...
def get_heat_kernel(network_id): """Return the identifier of a heat kernel calculated for a given network. Parameters ---------- network_id : str The UUID of the network in NDEx. Returns ------- kernel_id : str The identifier of the heat kernel calculated for the given netw...
Return the identifier of a heat kernel calculated for a given network. Parameters ---------- network_id : str The UUID of the network in NDEx. Returns ------- kernel_id : str The identifier of the heat kernel calculated for the given network.
Below is the the instruction that describes the task: ### Input: Return the identifier of a heat kernel calculated for a given network. Parameters ---------- network_id : str The UUID of the network in NDEx. Returns ------- kernel_id : str The identifier of the heat kernel ...
def _CreateSingleValueCondition(self, value, operator): """Creates a single-value condition with the provided value and operator.""" if isinstance(value, str) or isinstance(value, unicode): value = '"%s"' % value return '%s %s %s' % (self._field, operator, value)
Creates a single-value condition with the provided value and operator.
Below is the the instruction that describes the task: ### Input: Creates a single-value condition with the provided value and operator. ### Response: def _CreateSingleValueCondition(self, value, operator): """Creates a single-value condition with the provided value and operator.""" if isinstance(value, str...
def onSelectRow(self, event): """ Highlight or unhighlight a row for possible deletion. """ grid = self.grid row = event.Row default = (255, 255, 255, 255) highlight = (191, 216, 216, 255) cell_color = grid.GetCellBackgroundColour(row, 0) attr = wx...
Highlight or unhighlight a row for possible deletion.
Below is the the instruction that describes the task: ### Input: Highlight or unhighlight a row for possible deletion. ### Response: def onSelectRow(self, event): """ Highlight or unhighlight a row for possible deletion. """ grid = self.grid row = event.Row default =...
def pad(self, data, block_size): """ :meth:`.WBlockPadding.pad` method implementation """ padding_symbol = self.padding_symbol() blocks_count = (len(data) // block_size) if (len(data) % block_size) != 0: blocks_count += 1 total_length = blocks_count * block_size return self._fill(data, total_length, ...
:meth:`.WBlockPadding.pad` method implementation
Below is the the instruction that describes the task: ### Input: :meth:`.WBlockPadding.pad` method implementation ### Response: def pad(self, data, block_size): """ :meth:`.WBlockPadding.pad` method implementation """ padding_symbol = self.padding_symbol() blocks_count = (len(data) // block_size) if (le...
def _to_unit_base(self, base_unit, values, unit, from_unit): """Return values in a given unit given the input from_unit.""" self._is_numeric(values) namespace = {'self': self, 'values': values} if not from_unit == base_unit: self.is_unit_acceptable(from_unit, True) ...
Return values in a given unit given the input from_unit.
Below is the the instruction that describes the task: ### Input: Return values in a given unit given the input from_unit. ### Response: def _to_unit_base(self, base_unit, values, unit, from_unit): """Return values in a given unit given the input from_unit.""" self._is_numeric(values) namesp...
def _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype): """Converts per_example_weights to a tensor and validates the shape.""" per_example_weights = tf.convert_to_tensor( per_example_weights, name='per_example_weights', dtype=dtype) if input_.get_shape().ndims: ...
Converts per_example_weights to a tensor and validates the shape.
Below is the the instruction that describes the task: ### Input: Converts per_example_weights to a tensor and validates the shape. ### Response: def _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype): """Converts per_example_weights to a tensor and validates the shape."""...
def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to retur...
Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to return something which evaluates to False. We ensure this method is called at least once regardless o...
Below is the the instruction that describes the task: ### Input: Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to return something which evaluates to...
def read_utf8_string(self, length): """ Reads a UTF-8 string from the stream. @rtype: C{unicode} """ s = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0] return s.decode('utf-8')
Reads a UTF-8 string from the stream. @rtype: C{unicode}
Below is the the instruction that describes the task: ### Input: Reads a UTF-8 string from the stream. @rtype: C{unicode} ### Response: def read_utf8_string(self, length): """ Reads a UTF-8 string from the stream. @rtype: C{unicode} """ s = struct.unpack("%s%ds" % ...
def timestamp_to_datetime(response): "Converts a unix timestamp to a Python datetime object" if not response: return None try: response = int(response) except ValueError: return None return datetime.datetime.fromtimestamp(response)
Converts a unix timestamp to a Python datetime object
Below is the the instruction that describes the task: ### Input: Converts a unix timestamp to a Python datetime object ### Response: def timestamp_to_datetime(response): "Converts a unix timestamp to a Python datetime object" if not response: return None try: response = int(response) ...
def listDatasets(self, dataset="", parent_dataset="", is_dataset_valid=1, release_version="", pset_hash="", app_name="", output_module_label="", global_tag="", processing_version=0, acquisition_era_name="", run_num=-1, physics_group_name="", logical_file_name="", primary_ds_name="", primary_ds_t...
API to list dataset(s) in DBS * You can use ANY combination of these parameters in this API * In absence of parameters, all valid datasets known to the DBS instance will be returned :param dataset: Full dataset (path) of the dataset. :type dataset: str :param parent_dataset: Fu...
Below is the the instruction that describes the task: ### Input: API to list dataset(s) in DBS * You can use ANY combination of these parameters in this API * In absence of parameters, all valid datasets known to the DBS instance will be returned :param dataset: Full dataset (path) of the ...
def joint_sfs_folded_scaled(ac1, ac2, n1=None, n2=None): """Compute the joint folded site frequency spectrum between two populations, scaled such that a constant value is expected across the spectrum for neutral variation, constant population size and unrelated populations. Parameters ---------...
Compute the joint folded site frequency spectrum between two populations, scaled such that a constant value is expected across the spectrum for neutral variation, constant population size and unrelated populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, 2) Allel...
Below is the the instruction that describes the task: ### Input: Compute the joint folded site frequency spectrum between two populations, scaled such that a constant value is expected across the spectrum for neutral variation, constant population size and unrelated populations. Parameters ----...
def create_document(self, data, throw_on_exists=False): """ Creates a new document in the remote and locally cached database, using the data provided. If an _id is included in the data then depending on that _id either a :class:`~cloudant.document.Document` or a :class:`~cloudan...
Creates a new document in the remote and locally cached database, using the data provided. If an _id is included in the data then depending on that _id either a :class:`~cloudant.document.Document` or a :class:`~cloudant.design_document.DesignDocument` object will be added to the locall...
Below is the the instruction that describes the task: ### Input: Creates a new document in the remote and locally cached database, using the data provided. If an _id is included in the data then depending on that _id either a :class:`~cloudant.document.Document` or a :class:`~cloudant.desig...
def increase_by_changes(self, changes_amount, ratio): """Increase version by amount of changes :param changes_amount: Number of changes done :param ratio: Ratio changes :return: Increases version accordingly to changes """ increases = round(changes_amount * ratio) ...
Increase version by amount of changes :param changes_amount: Number of changes done :param ratio: Ratio changes :return: Increases version accordingly to changes
Below is the the instruction that describes the task: ### Input: Increase version by amount of changes :param changes_amount: Number of changes done :param ratio: Ratio changes :return: Increases version accordingly to changes ### Response: def increase_by_changes(self, changes_amount, rat...
def get_conn(): ''' Return a conn object for the passed VM data ''' driver = get_driver(Provider.GCE) provider = get_configured_provider() project = config.get_cloud_config_value('project', provider, __opts__) email = config.get_cloud_config_value( 'service_account_email_address', ...
Return a conn object for the passed VM data
Below is the the instruction that describes the task: ### Input: Return a conn object for the passed VM data ### Response: def get_conn(): ''' Return a conn object for the passed VM data ''' driver = get_driver(Provider.GCE) provider = get_configured_provider() project = config.get_cloud_co...
def create(self, friendly_name, code_length=values.unset, lookup_enabled=values.unset, skip_sms_to_landlines=values.unset, dtmf_input_required=values.unset, tts_name=values.unset, psd2_enabled=values.unset): """ Create a new ServiceInstance :param un...
Create a new ServiceInstance :param unicode friendly_name: A string to describe the verification service :param unicode code_length: The length of the verification code to generate :param bool lookup_enabled: Whether to perform a lookup with each verification :param bool skip_sms_to_lan...
Below is the the instruction that describes the task: ### Input: Create a new ServiceInstance :param unicode friendly_name: A string to describe the verification service :param unicode code_length: The length of the verification code to generate :param bool lookup_enabled: Whether to perfor...
def finish(self, blueprint, documents): """Finish a list of pre-assembled documents""" # Reset the blueprint blueprint.reset() # Finish the documents finished = [] for document in documents: finished.append(blueprint.finish(document)) return finishe...
Finish a list of pre-assembled documents
Below is the the instruction that describes the task: ### Input: Finish a list of pre-assembled documents ### Response: def finish(self, blueprint, documents): """Finish a list of pre-assembled documents""" # Reset the blueprint blueprint.reset() # Finish the documents fin...
def solve(self): """Run the ACE calculational loop.""" self._initialize() while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS: print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}' ''.format(self._outer_iters, self._last_outer_er...
Run the ACE calculational loop.
Below is the the instruction that describes the task: ### Input: Run the ACE calculational loop. ### Response: def solve(self): """Run the ACE calculational loop.""" self._initialize() while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS: print('* Starting ...
def show_list(self, the_list, cur_p=''): ''' List of the user collections. ''' current_page_num = int(cur_p) if cur_p else 1 current_page_num = 1 if current_page_num < 1 else current_page_num num_of_cat = MCollect.count_of_user(self.userinfo.uid) page_num = int(...
List of the user collections.
Below is the the instruction that describes the task: ### Input: List of the user collections. ### Response: def show_list(self, the_list, cur_p=''): ''' List of the user collections. ''' current_page_num = int(cur_p) if cur_p else 1 current_page_num = 1 if current_page_num...
def operations(self): """Instance depends on the API version: * 2018-03-31: :class:`Operations<azure.mgmt.containerservice.v2018_03_31.operations.Operations>` * 2018-08-01-preview: :class:`Operations<azure.mgmt.containerservice.v2018_08_01_preview.operations.Operations>` * 2019...
Instance depends on the API version: * 2018-03-31: :class:`Operations<azure.mgmt.containerservice.v2018_03_31.operations.Operations>` * 2018-08-01-preview: :class:`Operations<azure.mgmt.containerservice.v2018_08_01_preview.operations.Operations>` * 2019-02-01: :class:`Operations<azure....
Below is the the instruction that describes the task: ### Input: Instance depends on the API version: * 2018-03-31: :class:`Operations<azure.mgmt.containerservice.v2018_03_31.operations.Operations>` * 2018-08-01-preview: :class:`Operations<azure.mgmt.containerservice.v2018_08_01_preview.opera...
def backend_notification(self, event=None, parameters=None): """The Alignak backend raises an event to the Alignak arbiter ----- Possible events are: - creation, for a realm or an host creation - deletion, for a realm or an host deletion Calls the reload configuration fu...
The Alignak backend raises an event to the Alignak arbiter ----- Possible events are: - creation, for a realm or an host creation - deletion, for a realm or an host deletion Calls the reload configuration function if event is creation or deletion Else, nothing for the m...
Below is the the instruction that describes the task: ### Input: The Alignak backend raises an event to the Alignak arbiter ----- Possible events are: - creation, for a realm or an host creation - deletion, for a realm or an host deletion Calls the reload configuration funct...
def encompasses(self, span): """ Returns true if the given span fits inside this one """ if isinstance(span, list): return [sp for sp in span if self._encompasses(sp)] return self._encompasses(span)
Returns true if the given span fits inside this one
Below is the the instruction that describes the task: ### Input: Returns true if the given span fits inside this one ### Response: def encompasses(self, span): """ Returns true if the given span fits inside this one """ if isinstance(span, list): return [sp for sp in spa...
def add_bool_option(self, *args, **kwargs): """ Add a boolean option. @keyword help: Option description. """ dest = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") self.parser.add_option(dest=dest, action="store_true", default=False, ...
Add a boolean option. @keyword help: Option description.
Below is the the instruction that describes the task: ### Input: Add a boolean option. @keyword help: Option description. ### Response: def add_bool_option(self, *args, **kwargs): """ Add a boolean option. @keyword help: Option description. """ dest = [o for o in a...
def sample_lonlat(self, n): """ Sample 2D distribution of points in lon, lat """ # From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form # However, Martin et al. (2009) use PA theta "from North to East" # Definition of phi (position angle) is offset by pi/4 ...
Sample 2D distribution of points in lon, lat
Below is the the instruction that describes the task: ### Input: Sample 2D distribution of points in lon, lat ### Response: def sample_lonlat(self, n): """ Sample 2D distribution of points in lon, lat """ # From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form # ...
def destroy(name, call=None): ''' destroy a machine by name :param name: name given to the machine :param call: call value in this case is 'action' :return: array of booleans , true if successfully stopped and true if successfully removed CLI Example: .. code-block:: bash ...
destroy a machine by name :param name: name given to the machine :param call: call value in this case is 'action' :return: array of booleans , true if successfully stopped and true if successfully removed CLI Example: .. code-block:: bash salt-cloud -d vm_name
Below is the the instruction that describes the task: ### Input: destroy a machine by name :param name: name given to the machine :param call: call value in this case is 'action' :return: array of booleans , true if successfully stopped and true if successfully removed CLI Example: ...
def put_sync(self, **kwargs): ''' PUT: puts data into the Firebase. Requires the 'point' parameter as a keyworded argument. ''' self.amust(("point", "data"), kwargs) response = requests.put(self.url_correct(kwargs["point"], kwargs.get("aut...
PUT: puts data into the Firebase. Requires the 'point' parameter as a keyworded argument.
Below is the the instruction that describes the task: ### Input: PUT: puts data into the Firebase. Requires the 'point' parameter as a keyworded argument. ### Response: def put_sync(self, **kwargs): ''' PUT: puts data into the Firebase. Requires the 'point' parameter as a keyworde...
def configure_audit_decorator(graph): """ Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ... """ include_request_body = int(graph.config.audit.include_request_body) include_response_body = int(graph.config.audit.include_res...
Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ...
Below is the the instruction that describes the task: ### Input: Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ... ### Response: def configure_audit_decorator(graph): """ Configure the audit decorator. Example Usage: ...
def tnr(y, z): """True negative rate `tn / (tn + fp)` """ tp, tn, fp, fn = contingency_table(y, z) return tn / (tn + fp)
True negative rate `tn / (tn + fp)`
Below is the the instruction that describes the task: ### Input: True negative rate `tn / (tn + fp)` ### Response: def tnr(y, z): """True negative rate `tn / (tn + fp)` """ tp, tn, fp, fn = contingency_table(y, z) return tn / (tn + fp)
def _flush(self): """ Flush metadata to the backing file :return: """ with open(self.metadata_file, 'w') as f: json.dump(self.metadata, f)
Flush metadata to the backing file :return:
Below is the the instruction that describes the task: ### Input: Flush metadata to the backing file :return: ### Response: def _flush(self): """ Flush metadata to the backing file :return: """ with open(self.metadata_file, 'w') as f: json.dump(self.metada...
def _scan_smaller(self, seq, threshold=''): """ m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans The sequence is smaller than the PSSM. Are there good matches to regions of the PSSM? """ ll = self.ll #Shortcut for Log-likelih...
m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans The sequence is smaller than the PSSM. Are there good matches to regions of the PSSM?
Below is the the instruction that describes the task: ### Input: m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans The sequence is smaller than the PSSM. Are there good matches to regions of the PSSM? ### Response: def _scan_smaller(self, seq, threshold...
def is_logon(self, verify=False): """ Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The `ver...
Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The `verify` parameter can be used to verify the validity ...
Below is the the instruction that describes the task: ### Input: Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logg...
def _schedule(self): '''Schedule check function.''' if self._running: _logger.debug('Schedule check function.') self._call_later_handle = self._event_loop.call_later( self._timeout, self._check)
Schedule check function.
Below is the the instruction that describes the task: ### Input: Schedule check function. ### Response: def _schedule(self): '''Schedule check function.''' if self._running: _logger.debug('Schedule check function.') self._call_later_handle = self._event_loop.call_later( ...
def make_and_return_path_from_path_and_folder_names(path, folder_names): """ For a given path, create a directory structure composed of a set of folders and return the path to the \ inner-most folder. For example, if path='/path/to/folders', and folder_names=['folder1', 'folder2'], the directory created wi...
For a given path, create a directory structure composed of a set of folders and return the path to the \ inner-most folder. For example, if path='/path/to/folders', and folder_names=['folder1', 'folder2'], the directory created will be '/path/to/folders/folder1/folder2/' and the returned path will be '/pat...
Below is the the instruction that describes the task: ### Input: For a given path, create a directory structure composed of a set of folders and return the path to the \ inner-most folder. For example, if path='/path/to/folders', and folder_names=['folder1', 'folder2'], the directory created will be '/...
def block(broker): """Path: /sys/block directories starting with . or ram or dm- or loop""" remove = (".", "ram", "dm-", "loop") tmp = "/dev/%s" return[(tmp % f) for f in os.listdir("/sys/block") if not f.startswith(remove)]
Path: /sys/block directories starting with . or ram or dm- or loop
Below is the the instruction that describes the task: ### Input: Path: /sys/block directories starting with . or ram or dm- or loop ### Response: def block(broker): """Path: /sys/block directories starting with . or ram or dm- or loop""" remove = (".", "ram", "dm-", "loop") tmp = "/dev/%s" ...
def get_text_for_html(html_content): ''' Take the HTML content (from, for example, an email) and construct a simple plain text version of that content (for example, for inclusion in a multipart email message). ''' soup = BeautifulSoup(html_content) # kill all script and style elem...
Take the HTML content (from, for example, an email) and construct a simple plain text version of that content (for example, for inclusion in a multipart email message).
Below is the the instruction that describes the task: ### Input: Take the HTML content (from, for example, an email) and construct a simple plain text version of that content (for example, for inclusion in a multipart email message). ### Response: def get_text_for_html(html_content): ''' Take t...
def small_doc(obj, indent="", max_width=80): """ Finds a useful small doc representation of an object. Parameters ---------- obj : Any object, which the documentation representation should be taken from. indent : Result indentation string to be insert in front of all lines. max_width : Each l...
Finds a useful small doc representation of an object. Parameters ---------- obj : Any object, which the documentation representation should be taken from. indent : Result indentation string to be insert in front of all lines. max_width : Each line of the result may have at most this length. Re...
Below is the the instruction that describes the task: ### Input: Finds a useful small doc representation of an object. Parameters ---------- obj : Any object, which the documentation representation should be taken from. indent : Result indentation string to be insert in front of all lines. max_wi...
def add_genelist(self, list_id, gene_ids, case_obj=None): """Create a new gene list and optionally link to cases.""" new_genelist = GeneList(list_id=list_id) new_genelist.gene_ids = gene_ids if case_obj: new_genelist.cases.append(case_obj) self.session.add(new_geneli...
Create a new gene list and optionally link to cases.
Below is the the instruction that describes the task: ### Input: Create a new gene list and optionally link to cases. ### Response: def add_genelist(self, list_id, gene_ids, case_obj=None): """Create a new gene list and optionally link to cases.""" new_genelist = GeneList(list_id=list_id) n...
def _lockstep_fcn(values): """ Wrapper to ensure that all processes execute together """ numrequired, fcn, args = values with _process_lock: _numdone.value += 1 # yep this is an ugly busy loop, do something better please # when we care about the performance of this call and not just the ...
Wrapper to ensure that all processes execute together
Below is the the instruction that describes the task: ### Input: Wrapper to ensure that all processes execute together ### Response: def _lockstep_fcn(values): """ Wrapper to ensure that all processes execute together """ numrequired, fcn, args = values with _process_lock: _numdone.value += 1 ...
def init_app(self, app, entry_point_group='invenio_queues.queues'): """Flask application initialization.""" self.init_config(app) app.extensions['invenio-queues'] = _InvenioQueuesState( app, app.config['QUEUES_CONNECTION_POOL'], entry_point_group=entry_point_g...
Flask application initialization.
Below is the the instruction that describes the task: ### Input: Flask application initialization. ### Response: def init_app(self, app, entry_point_group='invenio_queues.queues'): """Flask application initialization.""" self.init_config(app) app.extensions['invenio-queues'] = _InvenioQueue...
def get_dropout(x, rate=0.0, init=True): """Dropout x with dropout_rate = rate. Apply zero dropout during init or prediction time. Args: x: 4-D Tensor, shape=(NHWC). rate: Dropout rate. init: Initialization. Returns: x: activations after dropout. """ if init or rate == 0: return x re...
Dropout x with dropout_rate = rate. Apply zero dropout during init or prediction time. Args: x: 4-D Tensor, shape=(NHWC). rate: Dropout rate. init: Initialization. Returns: x: activations after dropout.
Below is the the instruction that describes the task: ### Input: Dropout x with dropout_rate = rate. Apply zero dropout during init or prediction time. Args: x: 4-D Tensor, shape=(NHWC). rate: Dropout rate. init: Initialization. Returns: x: activations after dropout. ### Response: def get_d...
async def serviceQueues(self, limit=None) -> int: """ Service at most `limit` messages from the inBox. :param limit: the maximum number of messages to service :return: the number of messages successfully processed """ return await self.inBoxRouter.handleAll(self.filterM...
Service at most `limit` messages from the inBox. :param limit: the maximum number of messages to service :return: the number of messages successfully processed
Below is the the instruction that describes the task: ### Input: Service at most `limit` messages from the inBox. :param limit: the maximum number of messages to service :return: the number of messages successfully processed ### Response: async def serviceQueues(self, limit=None) -> int: "...
def add_subtrack(self, subtrack): """ Add a child :class:`Track`. """ self.add_child(subtrack) self.subtracks.append(subtrack)
Add a child :class:`Track`.
Below is the the instruction that describes the task: ### Input: Add a child :class:`Track`. ### Response: def add_subtrack(self, subtrack): """ Add a child :class:`Track`. """ self.add_child(subtrack) self.subtracks.append(subtrack)
def ProcessMessage(self, message): """Processes a stats response from the client.""" self.ProcessResponse(message.source.Basename(), message.payload)
Processes a stats response from the client.
Below is the the instruction that describes the task: ### Input: Processes a stats response from the client. ### Response: def ProcessMessage(self, message): """Processes a stats response from the client.""" self.ProcessResponse(message.source.Basename(), message.payload)
def append(self, item): """ Try to add an item to this element. If the item is of the wrong type, and if this element has a sub-type, then try to create such a sub-type and insert the item into that, instead. This happens recursively, so (in python-markup): L ...
Try to add an item to this element. If the item is of the wrong type, and if this element has a sub-type, then try to create such a sub-type and insert the item into that, instead. This happens recursively, so (in python-markup): L [ u'Foo' ] actually creates: ...
Below is the the instruction that describes the task: ### Input: Try to add an item to this element. If the item is of the wrong type, and if this element has a sub-type, then try to create such a sub-type and insert the item into that, instead. This happens recursively, so (in pyt...
def printHelp(script): """Print Help Prints out the arguments needs to run the script Returns: None """ print 'Reconsider cli script copyright 2016 OuroborosCoding' print '' print script + ' --source=localhost:28015 --destination=somedomain.com:28015' print script + ' --destination=somedomain.com:28015 --d...
Print Help Prints out the arguments needs to run the script Returns: None
Below is the the instruction that describes the task: ### Input: Print Help Prints out the arguments needs to run the script Returns: None ### Response: def printHelp(script): """Print Help Prints out the arguments needs to run the script Returns: None """ print 'Reconsider cli script copyright 201...
def links(self) -> _Links: """All found links on page, in as–is form. Only works for Atom feeds.""" return list(set(x.text for x in self.xpath('//link')))
All found links on page, in as–is form. Only works for Atom feeds.
Below is the the instruction that describes the task: ### Input: All found links on page, in as–is form. Only works for Atom feeds. ### Response: def links(self) -> _Links: """All found links on page, in as–is form. Only works for Atom feeds.""" return list(set(x.text for x in self.xpath('//link'...
def find_event_with_outgoing_edges(self, event_name, desired_relations): """Gets a list of event nodes with the specified event_name and outgoing edges annotated with each of the specified relations. Parameters ---------- event_name : str Look for event nodes with th...
Gets a list of event nodes with the specified event_name and outgoing edges annotated with each of the specified relations. Parameters ---------- event_name : str Look for event nodes with this name desired_relations : list[str] Look for event nodes with ...
Below is the the instruction that describes the task: ### Input: Gets a list of event nodes with the specified event_name and outgoing edges annotated with each of the specified relations. Parameters ---------- event_name : str Look for event nodes with this name ...
def usn_v4_record(header, record): """Extracts USN V4 record information.""" length, major_version, minor_version = header fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size) raise NotImplementedError('Not implemented')
Extracts USN V4 record information.
Below is the the instruction that describes the task: ### Input: Extracts USN V4 record information. ### Response: def usn_v4_record(header, record): """Extracts USN V4 record information.""" length, major_version, minor_version = header fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size) r...
def __remove_dir(self, ftp, remote_path): """ Helper function to perform delete operation on the remote server :param ftp: SFTP handle to perform delete operation(s) :param remote_path: Remote path to remove """ # Iterate over the remote path and perform remove operation...
Helper function to perform delete operation on the remote server :param ftp: SFTP handle to perform delete operation(s) :param remote_path: Remote path to remove
Below is the the instruction that describes the task: ### Input: Helper function to perform delete operation on the remote server :param ftp: SFTP handle to perform delete operation(s) :param remote_path: Remote path to remove ### Response: def __remove_dir(self, ftp, remote_path): """ ...
def GET(self, courseid, taskid, isLTI): """ GET request """ username = self.user_manager.session_username() # Fetch the course try: course = self.course_factory.get_course(courseid) except exceptions.CourseNotFoundException as ex: raise web.notfound(str(e...
GET request
Below is the the instruction that describes the task: ### Input: GET request ### Response: def GET(self, courseid, taskid, isLTI): """ GET request """ username = self.user_manager.session_username() # Fetch the course try: course = self.course_factory.get_course(coursei...
def retrieve_element_or_default(self, location, default=None): """ Args: location: default: Returns: """ loc_descriptor = self._get_location_descriptor(location) # find node node = None try: node = sel...
Args: location: default: Returns:
Below is the the instruction that describes the task: ### Input: Args: location: default: Returns: ### Response: def retrieve_element_or_default(self, location, default=None): """ Args: location: default: R...
def get_record(self, record): """ Reads a dom xml element in oaidc format and returns the bibrecord object """ self.document = record rec = create_record() language = self._get_language() if language and language != 'en': record_add_field(rec, '041', subfi...
Reads a dom xml element in oaidc format and returns the bibrecord object
Below is the the instruction that describes the task: ### Input: Reads a dom xml element in oaidc format and returns the bibrecord object ### Response: def get_record(self, record): """ Reads a dom xml element in oaidc format and returns the bibrecord object """ self.documen...
def QDS_StockDayWarpper(func): """ 日线QDS装饰器 """ def warpper(*args, **kwargs): data = func(*args, **kwargs) if isinstance(data.index, pd.MultiIndex): return QA_DataStruct_Stock_day(data) else: return QA_DataStruct_Stock_day( data.assign(d...
日线QDS装饰器
Below is the the instruction that describes the task: ### Input: 日线QDS装饰器 ### Response: def QDS_StockDayWarpper(func): """ 日线QDS装饰器 """ def warpper(*args, **kwargs): data = func(*args, **kwargs) if isinstance(data.index, pd.MultiIndex): return QA_DataStruct_Stock_day(...
def loop_tk(kernel): """Start a kernel with the Tk event loop.""" import Tkinter doi = kernel.do_one_iteration # Tk uses milliseconds poll_interval = int(1000*kernel._poll_interval) # For Tkinter, we create a Tk object and call its withdraw method. class Timer(object): def __init__(...
Start a kernel with the Tk event loop.
Below is the the instruction that describes the task: ### Input: Start a kernel with the Tk event loop. ### Response: def loop_tk(kernel): """Start a kernel with the Tk event loop.""" import Tkinter doi = kernel.do_one_iteration # Tk uses milliseconds poll_interval = int(1000*kernel._poll_inte...
def moving_average(self, data, days): """ 計算移動平均數 :rtype: 序列 舊→新 """ result = [] data = data[:] for dummy in range(len(data) - int(days) + 1): result.append(round(sum(data[-days:]) / days, 2)) data.pop() result.reverse() return...
計算移動平均數 :rtype: 序列 舊→新
Below is the the instruction that describes the task: ### Input: 計算移動平均數 :rtype: 序列 舊→新 ### Response: def moving_average(self, data, days): """ 計算移動平均數 :rtype: 序列 舊→新 """ result = [] data = data[:] for dummy in range(len(data) - int(days) + 1): ...
def interval_timer(interval, func, *args, **kwargs): '''Interval timer function. Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708 ''' stopped = Event() def loop(): while not stopped.wait(interval): # the first call is after interval ...
Interval timer function. Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
Below is the the instruction that describes the task: ### Input: Interval timer function. Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708 ### Response: def interval_timer(interval, func, *args, **kwargs): '''Interval timer function. Taken from: http://s...
def download_bhavcopy(self, d): """returns bhavcopy as csv file.""" # ex_url = "https://www.nseindia.com/content/historical/EQUITIES/2011/NOV/cm08NOV2011bhav.csv.zip" url = self.get_bhavcopy_url(d) filename = self.get_bhavcopy_filename(d) # response = requests.get(url, headers=se...
returns bhavcopy as csv file.
Below is the the instruction that describes the task: ### Input: returns bhavcopy as csv file. ### Response: def download_bhavcopy(self, d): """returns bhavcopy as csv file.""" # ex_url = "https://www.nseindia.com/content/historical/EQUITIES/2011/NOV/cm08NOV2011bhav.csv.zip" url = self.get_...
def reorder(self, dst_order, arr, src_order=None): """Reorder the output array to match that needed by the viewer.""" if dst_order is None: dst_order = self.viewer.rgb_order if src_order is None: src_order = self.rgb_order if src_order != dst_order: ar...
Reorder the output array to match that needed by the viewer.
Below is the the instruction that describes the task: ### Input: Reorder the output array to match that needed by the viewer. ### Response: def reorder(self, dst_order, arr, src_order=None): """Reorder the output array to match that needed by the viewer.""" if dst_order is None: dst_ord...
def fromTFExample(bytestr): """Deserializes a TFExample from a byte string""" example = tf.train.Example() example.ParseFromString(bytestr) return example
Deserializes a TFExample from a byte string
Below is the the instruction that describes the task: ### Input: Deserializes a TFExample from a byte string ### Response: def fromTFExample(bytestr): """Deserializes a TFExample from a byte string""" example = tf.train.Example() example.ParseFromString(bytestr) return example
def read_and_save_data(info_df, raw_dir, sep=";", force_raw=False, force_cellpy=False, export_cycles=False, shifted_cycles=False, export_raw=True, export_ica=False, save=True, use_cellpy_stat_file=False, p...
Reads and saves cell data defined by the info-DataFrame. The function iterates through the ``info_df`` and loads data from the runs. It saves individual data for each run (if selected), as well as returns a list of ``cellpy`` summary DataFrames, a list of the indexes (one for each run; same as used as ...
Below is the the instruction that describes the task: ### Input: Reads and saves cell data defined by the info-DataFrame. The function iterates through the ``info_df`` and loads data from the runs. It saves individual data for each run (if selected), as well as returns a list of ``cellpy`` summary Data...
def _process_response(cls, response): """ Examine the response and raise an error is something is off """ if len(response) != 1: raise BadResponseError("Malformed response: {}".format(response)) stats = list(itervalues(response))[0] if not len(stats): ...
Examine the response and raise an error is something is off
Below is the the instruction that describes the task: ### Input: Examine the response and raise an error is something is off ### Response: def _process_response(cls, response): """ Examine the response and raise an error is something is off """ if len(response) != 1: rai...
def try_pull_image_from_registry(self, image_name, image_tag): """ Tries to pull a image with the tag ``image_tag`` from registry set by ``use_registry_name``. After the image is pulled, it's tagged with ``image_name``:``image_tag`` so lookup can be made locally next time. :retu...
Tries to pull a image with the tag ``image_tag`` from registry set by ``use_registry_name``. After the image is pulled, it's tagged with ``image_name``:``image_tag`` so lookup can be made locally next time. :return: A :class:`Image <docker.models.images.Image>` instance if the image exists, ``N...
Below is the the instruction that describes the task: ### Input: Tries to pull a image with the tag ``image_tag`` from registry set by ``use_registry_name``. After the image is pulled, it's tagged with ``image_name``:``image_tag`` so lookup can be made locally next time. :return: A :class:`...
def transaction_start(self, name): """ start a transaction this will increment transaction semaphore and pass it to _transaction_start() """ if not name: raise ValueError("Transaction name cannot be empty") #uid = id(self) self.transaction_count ...
start a transaction this will increment transaction semaphore and pass it to _transaction_start()
Below is the the instruction that describes the task: ### Input: start a transaction this will increment transaction semaphore and pass it to _transaction_start() ### Response: def transaction_start(self, name): """ start a transaction this will increment transaction semaphore and...
def close(self): """ Close the node process. """ if self._closed: return False log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name, name=self.name, ...
Close the node process.
Below is the the instruction that describes the task: ### Input: Close the node process. ### Response: def close(self): """ Close the node process. """ if self._closed: return False log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.mod...
def __taint_store(self, instr): """Taint STM instruction. """ # Get memory address. op2_val = self.__emu.read_operand(instr.operands[2]) # Get taint information. op0_size = instr.operands[0].size op0_taint = self.get_operand_taint(instr.operands[0]) # Pr...
Taint STM instruction.
Below is the the instruction that describes the task: ### Input: Taint STM instruction. ### Response: def __taint_store(self, instr): """Taint STM instruction. """ # Get memory address. op2_val = self.__emu.read_operand(instr.operands[2]) # Get taint information. op...
def add_reaction_constraints(model, reactions, Constraint): """ Add the stoichiometric coefficients as constraints. Parameters ---------- model : optlang.Model The transposed stoichiometric matrix representation. reactions : iterable Container of `cobra.Reaction` instances. ...
Add the stoichiometric coefficients as constraints. Parameters ---------- model : optlang.Model The transposed stoichiometric matrix representation. reactions : iterable Container of `cobra.Reaction` instances. Constraint : optlang.Constraint The constraint class for the spe...
Below is the the instruction that describes the task: ### Input: Add the stoichiometric coefficients as constraints. Parameters ---------- model : optlang.Model The transposed stoichiometric matrix representation. reactions : iterable Container of `cobra.Reaction` instances. Con...
def check(call_fct): """ Decorator for optionable __call__ method It check the given option values """ # wrap the method @wraps(call_fct) def checked_call(self, *args, **kwargs): self.set_options_values(kwargs, parse=False, strict=True) options_val...
Decorator for optionable __call__ method It check the given option values
Below is the the instruction that describes the task: ### Input: Decorator for optionable __call__ method It check the given option values ### Response: def check(call_fct): """ Decorator for optionable __call__ method It check the given option values """ # wrap the method ...
def wait_for_edge(channel, trigger, timeout=-1): """ This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :p...
This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param trigger: The event to detect, one of: :py:attr:`GPIO.RIS...
Below is the the instruction that describes the task: ### Input: This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`)...
def indices(self, fit): """return the set of indices to be reevaluated for noise measurement. Given the first values are the earliest, this is a useful policy also with a time changing objective. """ ## meta_parameters.noise_reeval_multiplier == 1.0 lam_reev = 1...
return the set of indices to be reevaluated for noise measurement. Given the first values are the earliest, this is a useful policy also with a time changing objective.
Below is the the instruction that describes the task: ### Input: return the set of indices to be reevaluated for noise measurement. Given the first values are the earliest, this is a useful policy also with a time changing objective. ### Response: def indices(self, fit): """return ...
def information_gain(reference_beats, estimated_beats, bins=41): """Get the information gain - K-L divergence of the beat error histogram to a uniform histogram Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> referen...
Get the information gain - K-L divergence of the beat error histogram to a uniform histogram Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> reference_beats = mir_eval.beat.trim_beats(reference_beats) >>> estimated_beats = mir_eval.io.load_events('estimated....
Below is the the instruction that describes the task: ### Input: Get the information gain - K-L divergence of the beat error histogram to a uniform histogram Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> reference_beats = mir_eval.beat.trim_beats(reference...
def fill_n_todo(self): """ Calculate and record the number of edge pixels left to do on each tile """ left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_chunks): self.n_todo.ravel()[i] = np.sum([left....
Calculate and record the number of edge pixels left to do on each tile
Below is the the instruction that describes the task: ### Input: Calculate and record the number of edge pixels left to do on each tile ### Response: def fill_n_todo(self): """ Calculate and record the number of edge pixels left to do on each tile """ left = self.left right ...
def _load(self): """ Load editable settings from the database and return them as a dict. Delete any settings from the database that are no longer registered, and emit a warning if there are settings that are defined in both settings.py and the database. """ from y...
Load editable settings from the database and return them as a dict. Delete any settings from the database that are no longer registered, and emit a warning if there are settings that are defined in both settings.py and the database.
Below is the the instruction that describes the task: ### Input: Load editable settings from the database and return them as a dict. Delete any settings from the database that are no longer registered, and emit a warning if there are settings that are defined in both settings.py and the data...
def fit_radius_from_potentials(z, SampleFreq, Damping, HistBins=100, show_fig=False): """ Fits the dynamical potential to the Steady State Potential by varying the Radius. z : ndarray Position data SampleFreq : float frequency at which the position data was sampled ...
Fits the dynamical potential to the Steady State Potential by varying the Radius. z : ndarray Position data SampleFreq : float frequency at which the position data was sampled Damping : float value of damping (in radians/second) HistBins : int number of...
Below is the the instruction that describes the task: ### Input: Fits the dynamical potential to the Steady State Potential by varying the Radius. z : ndarray Position data SampleFreq : float frequency at which the position data was sampled Damping : float valu...
def grid_stack_for_simulation(cls, shape, pixel_scale, psf_shape, sub_grid_size=2): """Setup a grid-stack of grid_stack for simulating an image of a strong lens, whereby the grid's use \ padded-grid_stack to ensure that the PSF blurring in the simulation routine (*ccd.PrepatoryImage.simulate*) \ ...
Setup a grid-stack of grid_stack for simulating an image of a strong lens, whereby the grid's use \ padded-grid_stack to ensure that the PSF blurring in the simulation routine (*ccd.PrepatoryImage.simulate*) \ is not degraded due to edge effects. Parameters ----------- shape : (...
Below is the the instruction that describes the task: ### Input: Setup a grid-stack of grid_stack for simulating an image of a strong lens, whereby the grid's use \ padded-grid_stack to ensure that the PSF blurring in the simulation routine (*ccd.PrepatoryImage.simulate*) \ is not degraded due to ed...
def listFileParentsByLumi(self, block_name='', logical_file_name=[]): """ required parameter: block_name returns: [{child_parent_id_list: [(cid1, pid1), (cid2, pid2), ... (cidn, pidn)]}] """ #self.logger.debug("lfn %s, block_name %s" % (logical_file_name, block_name)) if...
required parameter: block_name returns: [{child_parent_id_list: [(cid1, pid1), (cid2, pid2), ... (cidn, pidn)]}]
Below is the the instruction that describes the task: ### Input: required parameter: block_name returns: [{child_parent_id_list: [(cid1, pid1), (cid2, pid2), ... (cidn, pidn)]}] ### Response: def listFileParentsByLumi(self, block_name='', logical_file_name=[]): """ required parameter: bloc...
def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, ...
Returns the user and group that the disk images should be owned by
Below is the the instruction that describes the task: ### Input: Returns the user and group that the disk images should be owned by ### Response: def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_c...
def parse_comments_for_file(filename): """ Return a list of all parsed comments in a file. Mostly for testing & interactive use. """ return [parse_comment(strip_stars(comment), next_line) for comment, next_line in get_doc_comments(read_file(filename))]
Return a list of all parsed comments in a file. Mostly for testing & interactive use.
Below is the the instruction that describes the task: ### Input: Return a list of all parsed comments in a file. Mostly for testing & interactive use. ### Response: def parse_comments_for_file(filename): """ Return a list of all parsed comments in a file. Mostly for testing & interactive use. ...
def get_one_ping_per_client(pings): """ Returns a single ping for each client in the RDD. THIS METHOD IS NOT RECOMMENDED: The ping to be returned is essentially selected at random. It is also expensive as it requires data to be shuffled around. It should be run only after extracting a subset with ...
Returns a single ping for each client in the RDD. THIS METHOD IS NOT RECOMMENDED: The ping to be returned is essentially selected at random. It is also expensive as it requires data to be shuffled around. It should be run only after extracting a subset with get_pings_properties.
Below is the the instruction that describes the task: ### Input: Returns a single ping for each client in the RDD. THIS METHOD IS NOT RECOMMENDED: The ping to be returned is essentially selected at random. It is also expensive as it requires data to be shuffled around. It should be run only after extra...