code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def os_requires_version(ostack_release, pkg): """ Decorator for hook to specify minimum supported release """ def wrap(f): @wraps(f) def wrapped_f(*args): if os_release(pkg) < ostack_release: raise Exception("This hook is not supported on releases" ...
Decorator for hook to specify minimum supported release
Below is the the instruction that describes the task: ### Input: Decorator for hook to specify minimum supported release ### Response: def os_requires_version(ostack_release, pkg): """ Decorator for hook to specify minimum supported release """ def wrap(f): @wraps(f) def wrapped_f(*...
def patch_modules(): """Patch modules to work better with :meth:`ExampleRunner.invoke`. ``subprocess.call` output is redirected to ``click.echo`` so it shows up in the example output. """ old_call = subprocess.call def dummy_call(*args, **kwargs): with tempfile.TemporaryFile("wb+") as ...
Patch modules to work better with :meth:`ExampleRunner.invoke`. ``subprocess.call` output is redirected to ``click.echo`` so it shows up in the example output.
Below is the the instruction that describes the task: ### Input: Patch modules to work better with :meth:`ExampleRunner.invoke`. ``subprocess.call` output is redirected to ``click.echo`` so it shows up in the example output. ### Response: def patch_modules(): """Patch modules to work better with :meth...
def compile_insert(self, query, values): """ Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str ...
Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str
Below is the the instruction that describes the task: ### Input: Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: s...
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} ...
Get the select options for the model selector :return:
Below is the the instruction that describes the task: ### Input: Get the select options for the model selector :return: ### Response: def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label',...
def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt...
Plot the result of the simulation once it's been intialized
Below is the the instruction that describes the task: ### Input: Plot the result of the simulation once it's been intialized ### Response: def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.alrea...
def evolve_genomes(rng, pop, params, recorder=None): """ Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`...
Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`fwdpy11.DiploidPopulation` :param params: simulation paramete...
Below is the the instruction that describes the task: ### Input: Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :cla...
def setField(self, new_value): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.field_strength = self.field_strength._replace( ...
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
Below is the the instruction that describes the task: ### Input: Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. ### Response: def setField(self, new_value): """...
def derive_key(self, derivation_method, derivation_length, derivation_data=None, key_material=None, hash_algorithm=None, salt=None, iteration_count=None, encryption_alg...
Derive key data using a variety of key derivation functions. Args: derivation_method (DerivationMethod): An enumeration specifying the key derivation method to use. Required. derivation_length (int): An integer specifying the size of the derived key data ...
Below is the the instruction that describes the task: ### Input: Derive key data using a variety of key derivation functions. Args: derivation_method (DerivationMethod): An enumeration specifying the key derivation method to use. Required. derivation_length (int): An...
def event(self, event): """Reimplementation of QWidget.event The widget is closed, when the window is deactivated. The widget is closed after the set interval if the mouse leaves the widget. The timer is stops when the mouse enters the widget before the interval ends. On show, t...
Reimplementation of QWidget.event The widget is closed, when the window is deactivated. The widget is closed after the set interval if the mouse leaves the widget. The timer is stops when the mouse enters the widget before the interval ends. On show, the added widgets are rendered for t...
Below is the the instruction that describes the task: ### Input: Reimplementation of QWidget.event The widget is closed, when the window is deactivated. The widget is closed after the set interval if the mouse leaves the widget. The timer is stops when the mouse enters the widget before the...
def prune(containers=False, networks=False, images=False, build=False, volumes=False, system=None, **filters): ''' .. versionadded:: 2019.2.0 Prune Docker's various subsystems .. note:: This requires docker-py version 2.1.0 or later. containers : False If ``True``, prune...
.. versionadded:: 2019.2.0 Prune Docker's various subsystems .. note:: This requires docker-py version 2.1.0 or later. containers : False If ``True``, prunes stopped containers (documentation__) .. __: https://docs.docker.com/engine/reference/commandline/container_prune/#filterin...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2019.2.0 Prune Docker's various subsystems .. note:: This requires docker-py version 2.1.0 or later. containers : False If ``True``, prunes stopped containers (documentation__) .. __: https://d...
def get_int(self, key: str) -> Optional[int]: """ Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :retur...
Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :return: The configuration key's value, or None if one does not exist. ...
Below is the the instruction that describes the task: ### Input: Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :re...
def draw(self, time: float, frametime: float, target: moderngl.Framebuffer): """ Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. ...
Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. frametime (float): The time the previous frame used to render in seconds. target ...
Below is the the instruction that describes the task: ### Input: Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. frametime (float): The t...
def create_ipsec_tunnel(cls, name, local_endpoint, remote_endpoint, preshared_key=None, monitoring_group=None, vpn_profile=None, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ The VPN tunnel type neg...
The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :p...
Below is the the instruction that describes the task: ### Input: The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing. :param str name: name of VPN :param TunnelEndpoint local_e...
def container_file_get(name, src, dst, overwrite=False, mode=None, uid=None, gid=None, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Get a file from a container name : Name of the container src : The source file or directory...
Get a file from a container name : Name of the container src : The source file or directory dst : The destination file or directory mode : Set file mode to octal number uid : Set file uid (owner) gid : Set file gid (group) remote_addr : ...
Below is the the instruction that describes the task: ### Input: Get a file from a container name : Name of the container src : The source file or directory dst : The destination file or directory mode : Set file mode to octal number uid : Set file ui...
def execute(self): """ Execute a bundle of operations """ self.bitshares.blocking = "head" r = self.bitshares.txbuffer.broadcast() self.bitshares.blocking = False return r
Execute a bundle of operations
Below is the the instruction that describes the task: ### Input: Execute a bundle of operations ### Response: def execute(self): """ Execute a bundle of operations """ self.bitshares.blocking = "head" r = self.bitshares.txbuffer.broadcast() self.bitshares.blocking = False ...
def _pdf(self, x, dist, cache): """Probability density function.""" return evaluation.evaluate_density( dist, numpy.arcsinh(x), cache=cache)/numpy.sqrt(1+x*x)
Probability density function.
Below is the the instruction that describes the task: ### Input: Probability density function. ### Response: def _pdf(self, x, dist, cache): """Probability density function.""" return evaluation.evaluate_density( dist, numpy.arcsinh(x), cache=cache)/numpy.sqrt(1+x*x)
def _validate(self, request): """Validate an L{HTTPRequest} before executing it. The following conditions are checked: - The request contains all the generic parameters. - The action specified in the request is a supported one. - The signature mechanism is a supported one. ...
Validate an L{HTTPRequest} before executing it. The following conditions are checked: - The request contains all the generic parameters. - The action specified in the request is a supported one. - The signature mechanism is a supported one. - The provided signature matches the ...
Below is the the instruction that describes the task: ### Input: Validate an L{HTTPRequest} before executing it. The following conditions are checked: - The request contains all the generic parameters. - The action specified in the request is a supported one. - The signature mechan...
def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001, solver=None): """Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff. Parameters ---------- model : co...
Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff. Parameters ---------- model : cobra.Model The cobra model to assess production capacity for reaction : reaction identifier or cobra.Reac...
Below is the the instruction that describes the task: ### Input: Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff. Parameters ---------- model : cobra.Model The cobra model to assess prod...
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
Read a dictionary of strings from a file
Below is the the instruction that describes the task: ### Input: Read a dictionary of strings from a file ### Response: def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for l...
def __remove_alias(type_): """ Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type """ if isinstance(type_, cpptypes.declarated_t) and \ isinstance(type_.declaration, typedef.typedef_t): return __remove...
Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type
Below is the the instruction that describes the task: ### Input: Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type ### Response: def __remove_alias(type_): """ Implementation detail. Args: type_ (type_t): type ...
def _imported_symbol(import_path): """Resolve a dotted path into a symbol, and return that. For example... >>> _imported_symbol('django.db.models.Model') <class 'django.db.models.base.Model'> Raise ImportError if there's no such module, AttributeError if no such symbol. """ module_na...
Resolve a dotted path into a symbol, and return that. For example... >>> _imported_symbol('django.db.models.Model') <class 'django.db.models.base.Model'> Raise ImportError if there's no such module, AttributeError if no such symbol.
Below is the the instruction that describes the task: ### Input: Resolve a dotted path into a symbol, and return that. For example... >>> _imported_symbol('django.db.models.Model') <class 'django.db.models.base.Model'> Raise ImportError if there's no such module, AttributeError if no such sym...
def chromedriver_element_center_patch(): """ Patch move_to_element on ActionChains to work around a bug present in Chromedriver 2.14 to 2.20. Calling this function multiple times in the same process will install the patch once, and just once. """ patch_name = "_selenic_chromedriver_element...
Patch move_to_element on ActionChains to work around a bug present in Chromedriver 2.14 to 2.20. Calling this function multiple times in the same process will install the patch once, and just once.
Below is the the instruction that describes the task: ### Input: Patch move_to_element on ActionChains to work around a bug present in Chromedriver 2.14 to 2.20. Calling this function multiple times in the same process will install the patch once, and just once. ### Response: def chromedriver_element_...
def _redistribute_builder(self, afi='ipv4', source=None): """Build BGP redistribute method. Do not use this method directly. You probably want ``redistribute``. Args: source (str): Source for redistributing. (connected) afi (str): Address family to configure. (ipv4, ip...
Build BGP redistribute method. Do not use this method directly. You probably want ``redistribute``. Args: source (str): Source for redistributing. (connected) afi (str): Address family to configure. (ipv4, ipv6) Returns: Method to redistribute desired sour...
Below is the the instruction that describes the task: ### Input: Build BGP redistribute method. Do not use this method directly. You probably want ``redistribute``. Args: source (str): Source for redistributing. (connected) afi (str): Address family to configure. (ipv4, ip...
def as_money(self, number, **options): """Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the symbol, precision,...
Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the symbol, precision, thousand / decimal separators and format ...
Below is the the instruction that describes the task: ### Input: Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the...
def _apply_serial_port(serial_device_spec, key, operation='add'): ''' Returns a vim.vm.device.VirtualSerialPort representing a serial port component serial_device_spec Serial device properties key Unique key of the device operation Add or edit the given device .. ...
Returns a vim.vm.device.VirtualSerialPort representing a serial port component serial_device_spec Serial device properties key Unique key of the device operation Add or edit the given device .. code-block:: bash serial_ports: adapter: 'Serial port 1' ...
Below is the the instruction that describes the task: ### Input: Returns a vim.vm.device.VirtualSerialPort representing a serial port component serial_device_spec Serial device properties key Unique key of the device operation Add or edit the given device .. code-bloc...
def _get_repeat_masker_header(pairwise_alignment): """generate header string of repeatmasker formated repr of self.""" res = "" res += str(pairwise_alignment.meta[ALIG_SCORE_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_SUBS_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_S...
generate header string of repeatmasker formated repr of self.
Below is the the instruction that describes the task: ### Input: generate header string of repeatmasker formated repr of self. ### Response: def _get_repeat_masker_header(pairwise_alignment): """generate header string of repeatmasker formated repr of self.""" res = "" res += str(pairwise_alignment.meta[ALIG_...
def window_cauchy(N, alpha=3): r"""Cauchy tapering window :param int N: window length :param float alpha: parameter of the poisson window .. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2} .. plot:: :width: 80% :include-source: from spectrum import window_v...
r"""Cauchy tapering window :param int N: window length :param float alpha: parameter of the poisson window .. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2} .. plot:: :width: 80% :include-source: from spectrum import window_visu window_visu(64, 'cauchy...
Below is the the instruction that describes the task: ### Input: r"""Cauchy tapering window :param int N: window length :param float alpha: parameter of the poisson window .. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2} .. plot:: :width: 80% :include-source: ...
def docpie(doc, argv=None, help=True, version=None, stdopt=True, attachopt=True, attachvalue=True, helpstyle='python', auto2dashes=True, name=None, case_sensitive=False, optionsfirst=False, appearedonly=False, namedoptions=False, extra=None): """ Parse `arg...
Parse `argv` based on command-line interface described in `doc`. `docpie` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, commands, which could be [optional], (required), (mutually | exclusive) or repeat...
Below is the the instruction that describes the task: ### Input: Parse `argv` based on command-line interface described in `doc`. `docpie` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, commands, which ...
def rfind(self, bs, start=None, end=None, bytealigned=None): """Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is foun...
Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit positi...
Below is the the instruction that describes the task: ### Input: Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. ...
def url(**attributes): """Parses an URL and validates its attributes.""" def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netloc: raise ValueError("'{0}' is not a valid URL".format(value)) for name, schema in attributes.items(): ...
Parses an URL and validates its attributes.
Below is the the instruction that describes the task: ### Input: Parses an URL and validates its attributes. ### Response: def url(**attributes): """Parses an URL and validates its attributes.""" def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netl...
def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths): """Build char embedding network for the QA model.""" max_char_length = self.cfg.max_char_length inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids), self.cfg.dropout, is_train...
Build char embedding network for the QA model.
Below is the the instruction that describes the task: ### Input: Build char embedding network for the QA model. ### Response: def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths): """Build char embedding network for the QA model.""" max_char_length = self.cfg.max_char...
def _repair(record: Dict[str, Any]) -> Dict[str, Any]: """Repair a corrupted IterationRecord with a specific known issue.""" output_records = record.get("output_records") if record.get("_type", None) == "IterationRecord" and output_records is not None: birdsite_record = output_records.get("birdsite"...
Repair a corrupted IterationRecord with a specific known issue.
Below is the the instruction that describes the task: ### Input: Repair a corrupted IterationRecord with a specific known issue. ### Response: def _repair(record: Dict[str, Any]) -> Dict[str, Any]: """Repair a corrupted IterationRecord with a specific known issue.""" output_records = record.get("output_rec...
def load(self, wishlist, calibration=None, resolution=None, polarization=None, level=None, generate=True, unload=True, **kwargs): """Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` ob...
Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` objects with every parameter specified or they can not provide certain parameters and the "best" parameter will be chosen. For example, if a dataset is a...
Below is the the instruction that describes the task: ### Input: Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` objects with every parameter specified or they can not provide certain parameters and the "b...
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ ...
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
Below is the the instruction that describes the task: ### Input: Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component ### Response: def g...
def __extractProperties(self): """ 2015-06-04: removed sparql 1.1 queries 2015-06-03: analogous to get classes # instantiate properties making sure duplicates are pruned # but the most specific rdftype is kept # eg OWL:ObjectProperty over RDF:property """ ...
2015-06-04: removed sparql 1.1 queries 2015-06-03: analogous to get classes # instantiate properties making sure duplicates are pruned # but the most specific rdftype is kept # eg OWL:ObjectProperty over RDF:property
Below is the the instruction that describes the task: ### Input: 2015-06-04: removed sparql 1.1 queries 2015-06-03: analogous to get classes # instantiate properties making sure duplicates are pruned # but the most specific rdftype is kept # eg OWL:ObjectProperty over RDF:property #...
def decode(self, key): """ Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised ...
Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised if this is not the case...
Below is the the instruction that describes the task: ### Input: Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ...
def get_minimum(self): ''' Return (t1, t2, value) triple where the value is the minimal one. ''' return (self._min_value_t1, self._min_value_t2, self._min_value, self._min_value_data)
Return (t1, t2, value) triple where the value is the minimal one.
Below is the the instruction that describes the task: ### Input: Return (t1, t2, value) triple where the value is the minimal one. ### Response: def get_minimum(self): ''' Return (t1, t2, value) triple where the value is the minimal one. ''' return (self._min...
def get_requests_request_name(self, request_name): """GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>` """ query_parameters = {} if request_nam...
GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>`
Below is the the instruction that describes the task: ### Input: GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>` ### Response: def get_requests_request_name(self, reques...
def do_GET(self): # check here request header to identify the type of req, if http or ws # if this is a ws req, instance a ws handler, add it to App's ws list, return if "Upgrade" in self.headers: if self.headers['Upgrade'] == 'websocket': #passing arguments to websoc...
Handler for the GET requests.
Below is the the instruction that describes the task: ### Input: Handler for the GET requests. ### Response: def do_GET(self): # check here request header to identify the type of req, if http or ws # if this is a ws req, instance a ws handler, add it to App's ws list, return if "Upgrade" in...
def get_SZ(self, psd, geometry): """ Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. """ if (self._S_table is None) or (self._Z_table is None): raise AttributeError( ...
Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices.
Below is the the instruction that describes the task: ### Input: Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. ### Response: def get_SZ(self, psd, geometry): """ Compute the scattering matrices for the g...
def setReturnParameter(self, name, type, namespace=None, element_type=0): """Set the return parameter description for the call info.""" parameter = ParameterInfo(name, type, namespace, element_type) self.retval = parameter return parameter
Set the return parameter description for the call info.
Below is the the instruction that describes the task: ### Input: Set the return parameter description for the call info. ### Response: def setReturnParameter(self, name, type, namespace=None, element_type=0): """Set the return parameter description for the call info.""" parameter = ParameterInfo(na...
def get_string(self, key): """Get a string from all_options""" # Massive hack, lol if key.startswith("lambda."): key = "lambda.items.{0}".format(key[7:]) if key.startswith("apigateway."): key = "apigateway.items.{0}".format(key[11:]) # Make sure key is i...
Get a string from all_options
Below is the the instruction that describes the task: ### Input: Get a string from all_options ### Response: def get_string(self, key): """Get a string from all_options""" # Massive hack, lol if key.startswith("lambda."): key = "lambda.items.{0}".format(key[7:]) if key....
def get_works(self): """Returns a list of the names of all works in the corpus. :rtype: `list` of `str` """ return [os.path.split(filepath)[1] for filepath in glob.glob(os.path.join(self._path, '*')) if os.path.isdir(filepath)]
Returns a list of the names of all works in the corpus. :rtype: `list` of `str`
Below is the the instruction that describes the task: ### Input: Returns a list of the names of all works in the corpus. :rtype: `list` of `str` ### Response: def get_works(self): """Returns a list of the names of all works in the corpus. :rtype: `list` of `str` """ retur...
def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None): """Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualiz...
Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualize. T_points_world : autolab_core.RigidTransform Pose of points, specified as a transformation from point frame to world f...
Below is the the instruction that describes the task: ### Input: Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualize. T_points_world : autolab_core.RigidTransform Pose...
def end_day_to_datetime(end_day, config): """ Convert a given end day to its proper datetime. This is non trivial because of variable ``day_start``. We want to make sure that even if an 'end day' is specified the actual point in time may reach into the following day. Args: end (datetim...
Convert a given end day to its proper datetime. This is non trivial because of variable ``day_start``. We want to make sure that even if an 'end day' is specified the actual point in time may reach into the following day. Args: end (datetime.date): Raw end date that is to be adjusted. ...
Below is the the instruction that describes the task: ### Input: Convert a given end day to its proper datetime. This is non trivial because of variable ``day_start``. We want to make sure that even if an 'end day' is specified the actual point in time may reach into the following day. Args: ...
def mark_in_progress(self, rr_id: str, rr_size: int) -> None: """ Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build """ try: makedirs(join(self._dir_tai...
Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build
Below is the the instruction that describes the task: ### Input: Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build ### Response: def mark_in_progress(self, rr_id: str, rr_size: int) -> None: ...
def commit_config(self): """ Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() ...
Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.commit_config() dev.close...
Below is the the instruction that describes the task: ### Input: Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() de...
def set_property(self, name, value): """set_property(property_name: str, value: object) Set property *property_name* to *value*. """ if not hasattr(self.props, name): raise TypeError("Unknown property: %r" % name) setattr(self.props, name, value)
set_property(property_name: str, value: object) Set property *property_name* to *value*.
Below is the the instruction that describes the task: ### Input: set_property(property_name: str, value: object) Set property *property_name* to *value*. ### Response: def set_property(self, name, value): """set_property(property_name: str, value: object) Set property *property_name* to *...
def equation(self): """Mix-in class that returns matrix rows for mscreen condition. Mscreen condition applied at each control point separately (so not like in ditch). Returns matrix part (nunknowns,neq) Returns rhs part (nunknowns) """ mat = np.zeros((self.nunknowns, self...
Mix-in class that returns matrix rows for mscreen condition. Mscreen condition applied at each control point separately (so not like in ditch). Returns matrix part (nunknowns,neq) Returns rhs part (nunknowns)
Below is the the instruction that describes the task: ### Input: Mix-in class that returns matrix rows for mscreen condition. Mscreen condition applied at each control point separately (so not like in ditch). Returns matrix part (nunknowns,neq) Returns rhs part (nunknowns) ### Response: def...
def transformToNative(obj): """ Turn obj.value into a datetime.timedelta. """ if obj.isNative: return obj obj.isNative = True obj.value=obj.value if obj.value == '': return obj else: deltalist=stringToDurations(obj.value...
Turn obj.value into a datetime.timedelta.
Below is the the instruction that describes the task: ### Input: Turn obj.value into a datetime.timedelta. ### Response: def transformToNative(obj): """ Turn obj.value into a datetime.timedelta. """ if obj.isNative: return obj obj.isNative = True obj.valu...
def euclidean_distances(a, b, squared=False, to_numpy=True): """ Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray...
Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n, f) first matrix b : np.ndarray (m, f) second mat...
Below is the the instruction that describes the task: ### Input: Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n,...
def extract_formats(config_handle): """Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``. """ configurations...
Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``.
Below is the the instruction that describes the task: ### Input: Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``. #...
def make_placeholders(seq, start=1): """ Generate placeholders for the given sequence. """ if len(seq) == 0: raise ValueError('Sequence must have at least one element.') param_style = Context.current().param_style placeholders = None if isinstance(seq, dict): if param_style i...
Generate placeholders for the given sequence.
Below is the the instruction that describes the task: ### Input: Generate placeholders for the given sequence. ### Response: def make_placeholders(seq, start=1): """ Generate placeholders for the given sequence. """ if len(seq) == 0: raise ValueError('Sequence must have at least one element...
def exists(name, path=None): ''' Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name ''' _exists = name in ls_(path...
Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name
Below is the the instruction that describes the task: ### Input: Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name ### Respons...
def get_deposit_address(self, currency): """Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') :returns: Api...
Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') :returns: ApiResponse .. code:: python { ...
Below is the the instruction that describes the task: ### Input: Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') ...
def make_update(model, docs, optimizer, drop=0.0, objective="L2"): """Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss. """ predictions, backpr...
Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss.
Below is the the instruction that describes the task: ### Input: Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss. ### Response: def make_update(model...
def worker_failed(): """Fail worker. Used by bots only for now.""" participant_id = request.args.get("participant_id") if not participant_id: return error_response( error_type="bad request", error_text="participantId parameter is required" ) try: _worker_failed(parti...
Fail worker. Used by bots only for now.
Below is the the instruction that describes the task: ### Input: Fail worker. Used by bots only for now. ### Response: def worker_failed(): """Fail worker. Used by bots only for now.""" participant_id = request.args.get("participant_id") if not participant_id: return error_response( ...
def VerifyGitkitToken(self, jwt): """Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise. """ certs = self.rpc_helper.GetPublicCert() crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days parsed =...
Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise.
Below is the the instruction that describes the task: ### Input: Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise. ### Response: def VerifyGitkitToken(self, jwt): """Verifies a Gitkit token string. A...
def cnst_A0(self, X, Xf=None): r"""Compute :math:`A_0 \mathbf{x}` component of ADMM problem constraint. """ # This calculation involves non-negligible computational cost # when Xf is None (i.e. the function is not being applied to # self.X). if Xf is None: ...
r"""Compute :math:`A_0 \mathbf{x}` component of ADMM problem constraint.
Below is the the instruction that describes the task: ### Input: r"""Compute :math:`A_0 \mathbf{x}` component of ADMM problem constraint. ### Response: def cnst_A0(self, X, Xf=None): r"""Compute :math:`A_0 \mathbf{x}` component of ADMM problem constraint. """ # This calcula...
def to_global(s): """ Format a global variable name. """ if s.startswith('GPSTime'): s = 'Gps' + s[3:] if '_' in s: s = "".join([i.capitalize() for i in s.split("_")]) return s[0].lower() + s[1:]
Format a global variable name.
Below is the the instruction that describes the task: ### Input: Format a global variable name. ### Response: def to_global(s): """ Format a global variable name. """ if s.startswith('GPSTime'): s = 'Gps' + s[3:] if '_' in s: s = "".join([i.capitalize() for i in s.split("_")]) return s[0].lowe...
def parse_datetime(value: Union[datetime, StrIntFloat]) -> datetime: """ Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input i...
Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Raise ValueError if the input isn'...
Below is the the instruction that describes the task: ### Input: Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well forma...
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get = self.config.getdefault errors = [] adderror = errors.append if not get('app', 'title', ''): ...
Ensure the spec file is 'correct'.
Below is the the instruction that describes the task: ### Input: Ensure the spec file is 'correct'. ### Response: def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get =...
def extendManager(mixinClass): ''' Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte...
Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte = django.utils.timezone.now()).order...
Below is the the instruction that describes the task: ### Input: Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): r...
def get_deployments(self, prefix=""): """ This endpoint lists all deployments. https://www.nomadproject.io/docs/http/deployments.html optional_arguments: - prefix, (default "") Specifies a string to filter deployments on based on an index prefix. Th...
This endpoint lists all deployments. https://www.nomadproject.io/docs/http/deployments.html optional_arguments: - prefix, (default "") Specifies a string to filter deployments on based on an index prefix. This is specified as a querystring parameter. ...
Below is the the instruction that describes the task: ### Input: This endpoint lists all deployments. https://www.nomadproject.io/docs/http/deployments.html optional_arguments: - prefix, (default "") Specifies a string to filter deployments on based on an index prefix. ...
def readbdfv1(filename, bdfext='.bdf', bhfext='.bhf'): """Read bdf file (Bessy Data Format v1) Input ----- filename: string the name of the file Output ------ the BDF structure in a dict Notes ----- This is an adaptation of the bdf_read.m macro of Sylvio Haas. """ ...
Read bdf file (Bessy Data Format v1) Input ----- filename: string the name of the file Output ------ the BDF structure in a dict Notes ----- This is an adaptation of the bdf_read.m macro of Sylvio Haas.
Below is the the instruction that describes the task: ### Input: Read bdf file (Bessy Data Format v1) Input ----- filename: string the name of the file Output ------ the BDF structure in a dict Notes ----- This is an adaptation of the bdf_read.m macro of Sylvio Haas. #...
def rewrite_paths(self, local_path, remote_path): """ Rewrite references to `local_path` with `remote_path` in job inputs. """ self.__rewrite_command_line(local_path, remote_path) self.__rewrite_config_files(local_path, remote_path)
Rewrite references to `local_path` with `remote_path` in job inputs.
Below is the the instruction that describes the task: ### Input: Rewrite references to `local_path` with `remote_path` in job inputs. ### Response: def rewrite_paths(self, local_path, remote_path): """ Rewrite references to `local_path` with `remote_path` in job inputs. """ self._...
def call_at_most_every(seconds, count=1): """Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window. """ def decorator(func): try: call_history = getattr(func, '_call_...
Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window.
Below is the the instruction that describes the task: ### Input: Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window. ### Response: def call_at_most_every(seconds, count=1): ...
def delete_agent(self, agent_id): """Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. """ # Raises an error when agent_id is ...
Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict.
Below is the the instruction that describes the task: ### Input: Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. ### Response: def ...
def file_copy(src=None, dest=None): ''' Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'device_name' junos.fil...
Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt
Below is the the instruction that describes the task: ### Input: Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'd...
def init(): """ Initializes the preprocessor """ global OUTPUT global INCLUDED global CURRENT_DIR global ENABLED global INCLUDEPATH global IFDEFS global ID_TABLE global CURRENT_FILE global_.FILENAME = '(stdin)' OUTPUT = '' INCLUDED = {} CURRENT_DIR = '' pwd =...
Initializes the preprocessor
Below is the the instruction that describes the task: ### Input: Initializes the preprocessor ### Response: def init(): """ Initializes the preprocessor """ global OUTPUT global INCLUDED global CURRENT_DIR global ENABLED global INCLUDEPATH global IFDEFS global ID_TABLE globa...
def read(self): """ Read a given file path and return its content. :return: The content of the given file path. :rtype: str """ try: with open(self.file, "r", encoding="utf-8") as file: # We open and read a file. # We get the...
Read a given file path and return its content. :return: The content of the given file path. :rtype: str
Below is the the instruction that describes the task: ### Input: Read a given file path and return its content. :return: The content of the given file path. :rtype: str ### Response: def read(self): """ Read a given file path and return its content. :return: The content of...
def _load_file_from_gcs(gcs_file_path, credentials=None): """Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string. ""...
Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string.
Below is the the instruction that describes the task: ### Input: Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string...
def _binary(space,const,name1,name2): """ reduce the domain of variable name1 to be two-consistent (arc-consistent) with this constraint, i.e. remove those values for the variable name1, for which no values for name2 exist such that this pair is consistent with the constraint returns True if th...
reduce the domain of variable name1 to be two-consistent (arc-consistent) with this constraint, i.e. remove those values for the variable name1, for which no values for name2 exist such that this pair is consistent with the constraint returns True if the domain of name1 was modified
Below is the the instruction that describes the task: ### Input: reduce the domain of variable name1 to be two-consistent (arc-consistent) with this constraint, i.e. remove those values for the variable name1, for which no values for name2 exist such that this pair is consistent with the constraint ...
def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten() weibull_samples = np.array([sp.stats.weibull_min.rvs(sel...
Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable
Below is the the instruction that describes the task: ### Input: Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable ### Response: def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations conditi...
def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'websub_self_url': stack.top.websub_self_url, 'websub_hub_url': stack.top.websub_hub_url,...
Calling this with your flask app as argument is required for the publisher decorator to work.
Below is the the instruction that describes the task: ### Input: Calling this with your flask app as argument is required for the publisher decorator to work. ### Response: def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """...
def validate(self, data): """ Validated data using defined regex. :param data: data to be validated :return: return validated data. """ e = self._error try: if self._pattern.search(data): return data else: r...
Validated data using defined regex. :param data: data to be validated :return: return validated data.
Below is the the instruction that describes the task: ### Input: Validated data using defined regex. :param data: data to be validated :return: return validated data. ### Response: def validate(self, data): """ Validated data using defined regex. :param data: data to be vali...
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vkey. http://video.sina.com/ """ url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey type, ext, size = url_info(url) print_info(site_info, title, 'flv', size) ...
Downloads a Sina video by its unique vkey. http://video.sina.com/
Below is the the instruction that describes the task: ### Input: Downloads a Sina video by its unique vkey. http://video.sina.com/ ### Response: def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vkey. http://video.sina.com/...
def normalize_uri_result(uri): """ Normalize a URI (And return a URIResult) """ ref = uri_reference(uri).normalize() return ref._replace( authority=normalize_uri_authority(ref), query=normalize_uri_query(ref), path=normalize_uri_path(ref), )
Normalize a URI (And return a URIResult)
Below is the the instruction that describes the task: ### Input: Normalize a URI (And return a URIResult) ### Response: def normalize_uri_result(uri): """ Normalize a URI (And return a URIResult) """ ref = uri_reference(uri).normalize() return ref._replace( authority=normalize_uri_aut...
def _recv_callback(self, msg): """ Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String. """ m2req = MongrelRequest.parse(msg[0]) MongrelConnection(m2req, self._sending_stream, self.request_callback, ...
Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String.
Below is the the instruction that describes the task: ### Input: Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String. ### Response: def _recv_callback(self, msg): """ Method is called when there is a message coming from a Mon...
def iter_chain(cur): """Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain. """ select = "SELECT nodes FROM chain" for node...
Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain.
Below is the the instruction that describes the task: ### Input: Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain. ### Response: def ...
def distance_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234 """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return No...
If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234
Below is the the instruction that describes the task: ### Input: If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234 ### Response: def distance_to_nearest_place(feature, parent): """If the impact layer has a dis...
def _import_matplotlib(): """Import matplotlib safely.""" # make sure that the Agg backend is set before importing any # matplotlib import matplotlib matplotlib.use('agg') matplotlib_backend = matplotlib.get_backend().lower() if matplotlib_backend != 'agg': raise ValueError( ...
Import matplotlib safely.
Below is the the instruction that describes the task: ### Input: Import matplotlib safely. ### Response: def _import_matplotlib(): """Import matplotlib safely.""" # make sure that the Agg backend is set before importing any # matplotlib import matplotlib matplotlib.use('agg') matplotlib_bac...
def _structure_set(self, obj, cl): """Convert an iterable into a potentially generic set.""" if is_bare(cl) or cl.__args__[0] is Any: return set(obj) else: elem_type = cl.__args__[0] return { self._structure_func.dispatch(elem_type)(e, elem_typ...
Convert an iterable into a potentially generic set.
Below is the the instruction that describes the task: ### Input: Convert an iterable into a potentially generic set. ### Response: def _structure_set(self, obj, cl): """Convert an iterable into a potentially generic set.""" if is_bare(cl) or cl.__args__[0] is Any: return set(obj) ...
def send_metrics_to_cloudwatch(self, rule, metric, dimensions): """ Send metrics to CloudWatch for the given dimensions """ timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp) self.log.debug( "CloudWatch: Attempting to publish metric: %s to %s " ...
Send metrics to CloudWatch for the given dimensions
Below is the the instruction that describes the task: ### Input: Send metrics to CloudWatch for the given dimensions ### Response: def send_metrics_to_cloudwatch(self, rule, metric, dimensions): """ Send metrics to CloudWatch for the given dimensions """ timestamp = datetime.date...
def run_query(self, query, new_line=True): """Runs *query*.""" if (self.destructive_warning and confirm_destructive_query(query) is False): message = 'Wise choice. Command execution stopped.' click.echo(message) return results = self.sqlexecut...
Runs *query*.
Below is the the instruction that describes the task: ### Input: Runs *query*. ### Response: def run_query(self, query, new_line=True): """Runs *query*.""" if (self.destructive_warning and confirm_destructive_query(query) is False): message = 'Wise choice. Command execut...
def awsRetry(f): """ This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto """ @wraps(f) def wrapper(*args, **kwargs): for attempt in retry(delays=truncExpBackoff(), timeout=...
This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto
Below is the the instruction that describes the task: ### Input: This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto ### Response: def awsRetry(f): """ This decorator retries the wrapped function if aws throws unexpe...
def read_remote(self): '''Send a message back to the server (in contrast to the local user output channel).''' coded_line = self.inout.read_msg() if isinstance(coded_line, bytes): coded_line = coded_line.decode("utf-8") control = coded_line[0] remote_line = co...
Send a message back to the server (in contrast to the local user output channel).
Below is the the instruction that describes the task: ### Input: Send a message back to the server (in contrast to the local user output channel). ### Response: def read_remote(self): '''Send a message back to the server (in contrast to the local user output channel).''' coded_line ...
def parse_ref(self, field: Field) -> str: """ Parse the reference type for nested fields, if any. """ ref_name = type_name(name_for(field.schema)) return f"#/definitions/{ref_name}"
Parse the reference type for nested fields, if any.
Below is the the instruction that describes the task: ### Input: Parse the reference type for nested fields, if any. ### Response: def parse_ref(self, field: Field) -> str: """ Parse the reference type for nested fields, if any. """ ref_name = type_name(name_for(field.schema)) ...
def decompose(self, frequency, window=None, periodic=False): '''Use STL to decompose the time series into seasonal, trend, and residual components.''' R = LazyImport.rpy2() if periodic: window = 'periodic' elif window is None: window = frequency ti...
Use STL to decompose the time series into seasonal, trend, and residual components.
Below is the the instruction that describes the task: ### Input: Use STL to decompose the time series into seasonal, trend, and residual components. ### Response: def decompose(self, frequency, window=None, periodic=False): '''Use STL to decompose the time series into seasonal, trend, and r...
def update_database(self, instance_id, database_id, ddl_statements, project_id=None, operation_id=None): """ Updates DDL of a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. ...
Updates DDL of a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner. :type database_id: str :param ddl_statements: The string list c...
Below is the the instruction that describes the task: ### Input: Updates DDL of a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner. :t...
def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """ cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d' cub_version_str = 'Current release: v1.6.4 (12/06/2016)' cub_zip_file = 'cub.zip' cub_zip_dir = ...
Downloads and installs cub into mb_inc_path
Below is the the instruction that describes the task: ### Input: Downloads and installs cub into mb_inc_path ### Response: def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """ cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3...
def library_directories(self) -> typing.List[str]: """ The list of directories to all of the library locations """ def listify(value): return [value] if isinstance(value, str) else list(value) # If this is a project running remotely remove external library # ...
The list of directories to all of the library locations
Below is the the instruction that describes the task: ### Input: The list of directories to all of the library locations ### Response: def library_directories(self) -> typing.List[str]: """ The list of directories to all of the library locations """ def listify(value): r...
def cmd(send, _, args): """Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command} """ adminlist = [] for admin in args['db'].query(Permissions).order_by(Permissions.nick).all(): if admin.registered: adminlist.append("%s (V)" % admin.n...
Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command}
Below is the the instruction that describes the task: ### Input: Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command} ### Response: def cmd(send, _, args): """Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {comman...
def parse_plotCoverage(self): """Find plotCoverage output. Both stdout and --outRawCounts""" self.deeptools_plotCoverageStdout = dict() for f in self.find_log_files('deeptools/plotCoverageStdout'): parsed_data = self.parsePlotCoverageStdout(f) for k, v in parsed_data.item...
Find plotCoverage output. Both stdout and --outRawCounts
Below is the the instruction that describes the task: ### Input: Find plotCoverage output. Both stdout and --outRawCounts ### Response: def parse_plotCoverage(self): """Find plotCoverage output. Both stdout and --outRawCounts""" self.deeptools_plotCoverageStdout = dict() for f in self.find_...
def unassign_agent_from_resource(self, agent_id, resource_id): """Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not ...
Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not found or ``agent_id`` not assigned to ``resource_id`` ...
Below is the the instruction that describes the task: ### Input: Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not found...
def parse_config(options): """ Get settings from config file. """ if os.path.exists(options.config): config = ConfigParser.ConfigParser() try: config.read(options.config) except Exception, err: if not options.quiet: sys.stderr.write("ERROR...
Get settings from config file.
Below is the the instruction that describes the task: ### Input: Get settings from config file. ### Response: def parse_config(options): """ Get settings from config file. """ if os.path.exists(options.config): config = ConfigParser.ConfigParser() try: config.read(optio...
def camel_2_snake(name): "Converts CamelCase to camel_case" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Converts CamelCase to camel_case
Below is the the instruction that describes the task: ### Input: Converts CamelCase to camel_case ### Response: def camel_2_snake(name): "Converts CamelCase to camel_case" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def list(self, **params): """ Retrieve all sources Returns all lead sources available to the user according to the parameters provided :calls: ``get /lead_sources`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style...
Retrieve all sources Returns all lead sources available to the user according to the parameters provided :calls: ``get /lead_sources`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which represent collection of LeadSou...
Below is the the instruction that describes the task: ### Input: Retrieve all sources Returns all lead sources available to the user according to the parameters provided :calls: ``get /lead_sources`` :param dict params: (optional) Search options. :return: List of dictionaries that ...
def _select_best_remaining_qubit(self, prog_qubit): """ Select the best remaining hardware qubit for the next program qubit. """ reliab_store = {} for hw_qubit in self.available_hw_qubits: reliab = 1 for n in self.prog_graph.neighbors(prog_qubit): ...
Select the best remaining hardware qubit for the next program qubit.
Below is the the instruction that describes the task: ### Input: Select the best remaining hardware qubit for the next program qubit. ### Response: def _select_best_remaining_qubit(self, prog_qubit): """ Select the best remaining hardware qubit for the next program qubit. """ reliab...
def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_va...
Generate the initial security hash from self.content_object and a (unix) timestamp.
Below is the the instruction that describes the task: ### Input: Generate the initial security hash from self.content_object and a (unix) timestamp. ### Response: def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix)...