code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. """ ...
Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior.
Below is the the instruction that describes the task: ### Input: Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior...
def _set_fortygigabitethernet(self, v, load=False): """ Setter method for fortygigabitethernet, mapped from YANG variable /interface/fortygigabitethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_fortygigabitethernet is considered as a private method. Ba...
Setter method for fortygigabitethernet, mapped from YANG variable /interface/fortygigabitethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_fortygigabitethernet is considered as a private method. Backends looking to populate this variable should do so via ca...
Below is the the instruction that describes the task: ### Input: Setter method for fortygigabitethernet, mapped from YANG variable /interface/fortygigabitethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_fortygigabitethernet is considered as a private metho...
def get_cases(self, skip_ws=False): """Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None. """ CONDITION = 1 VALUE = 2 ret = [] mode = CONDITION for token in self.tokens: # Set mode from the current statement ...
Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None.
Below is the the instruction that describes the task: ### Input: Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None. ### Response: def get_cases(self, skip_ws=False): """Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None. ...
def dictionary(_object, *args): """ Validates a given input is of type dictionary. Example usage:: data = {'a' : {'b': 1}} schema = ('a', dictionary) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. n...
Validates a given input is of type dictionary. Example usage:: data = {'a' : {'b': 1}} schema = ('a', dictionary) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable,...
Below is the the instruction that describes the task: ### Input: Validates a given input is of type dictionary. Example usage:: data = {'a' : {'b': 1}} schema = ('a', dictionary) You can also use this as a decorator, as a way to check for the input before it even hits a validator you ...
def GetUsername(self, event, default_username='-'): """Retrieves the username related to the event. Args: event (EventObject): event. default_username (Optional[str]): default username. Returns: str: username. """ username = getattr(event, 'username', None) if username and us...
Retrieves the username related to the event. Args: event (EventObject): event. default_username (Optional[str]): default username. Returns: str: username.
Below is the the instruction that describes the task: ### Input: Retrieves the username related to the event. Args: event (EventObject): event. default_username (Optional[str]): default username. Returns: str: username. ### Response: def GetUsername(self, event, default_username='-'): ...
def doOverlap(bbox1, bbox2): """ :param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: 1 if the two rectangles overlap """ if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]: return False if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]...
:param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: 1 if the two rectangles overlap
Below is the the instruction that describes the task: ### Input: :param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: 1 if the two rectangles overlap ### Response: def doOverlap(bbox1, bbox2): """ :param bbox1: bounding box of the first recta...
def train( self, env_fn, hparams, simulated, save_continuously, epoch, sampling_temp=1.0, num_env_steps=None, env_step_multiplier=1, eval_env_fn=None, report_fn=None ): """Train.""" raise NotImplementedError()
Train.
Below is the the instruction that describes the task: ### Input: Train. ### Response: def train( self, env_fn, hparams, simulated, save_continuously, epoch, sampling_temp=1.0, num_env_steps=None, env_step_multiplier=1, eval_env_fn=None, report_fn=No...
def getResiduals(self): """ regress out fixed effects and results residuals """ X = np.zeros((self.N*self.P,self.n_fixed_effs)) ip = 0 for i in range(self.n_terms): Ki = self.A[i].shape[0]*self.F[i].shape[1] X[:,ip:ip+Ki] = np.kron(self.A[i].T,self.F[i]) ...
regress out fixed effects and results residuals
Below is the the instruction that describes the task: ### Input: regress out fixed effects and results residuals ### Response: def getResiduals(self): """ regress out fixed effects and results residuals """ X = np.zeros((self.N*self.P,self.n_fixed_effs)) ip = 0 for i in range(self.n...
def connect_emr(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.emr.EmrConnectio...
:type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.emr.EmrConnection` :return: A connection to Elastic mapreduce
Below is the the instruction that describes the task: ### Input: :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.emr.EmrConnection` :return: A conn...
def handle_block( self, message_header, block ): """ Got a block. * validate it * load its transactions * ask for each transaction's sender transaction """ if self.have_all_block_data(): self.loop_exit() return block_hash = block....
Got a block. * validate it * load its transactions * ask for each transaction's sender transaction
Below is the the instruction that describes the task: ### Input: Got a block. * validate it * load its transactions * ask for each transaction's sender transaction ### Response: def handle_block( self, message_header, block ): """ Got a block. * validate it *...
def do_march(self): """ March about and trace the outline of our object Returns ------- perimeter : list The pixels on the perimeter of the region [[x1, y1], ...] """ x, y = self.find_start_point() perimeter = self.walk_perimeter(x, y) ...
March about and trace the outline of our object Returns ------- perimeter : list The pixels on the perimeter of the region [[x1, y1], ...]
Below is the the instruction that describes the task: ### Input: March about and trace the outline of our object Returns ------- perimeter : list The pixels on the perimeter of the region [[x1, y1], ...] ### Response: def do_march(self): """ March about and trac...
def scripts(cls, pkg, metadata, paths=[], **kwargs): """This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among scri...
This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among scripts against particular criteria. Its use is application specific...
Below is the the instruction that describes the task: ### Input: This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among ...
def make_action_list(self, item_list, **kwargs): ''' Generates a list of actions for sending to Elasticsearch ''' action_list = [] es_index = get2(kwargs, "es_index", self.es_index) action_type = kwargs.get("action_type","index") action_settings = {'_op_type': action_type,...
Generates a list of actions for sending to Elasticsearch
Below is the the instruction that describes the task: ### Input: Generates a list of actions for sending to Elasticsearch ### Response: def make_action_list(self, item_list, **kwargs): ''' Generates a list of actions for sending to Elasticsearch ''' action_list = [] es_index = get2(kwa...
def benchmark(self, func, gpu_args, threads, grid, times): """runs the kernel and measures time repeatedly, returns average time Runs the kernel and measures kernel execution time repeatedly, number of iterations is set during the creation of CudaFunctions. Benchmark returns a robust av...
runs the kernel and measures time repeatedly, returns average time Runs the kernel and measures kernel execution time repeatedly, number of iterations is set during the creation of CudaFunctions. Benchmark returns a robust average, from all measurements the fastest and slowest runs are ...
Below is the the instruction that describes the task: ### Input: runs the kernel and measures time repeatedly, returns average time Runs the kernel and measures kernel execution time repeatedly, number of iterations is set during the creation of CudaFunctions. Benchmark returns a robust ave...
def get_program_list(): """ get a HTML formatted view of all Python programs in all subfolders of AIKIF, including imports and lists of functions and classes """ colList = ['FileName','FileSize','Functions', 'Imports'] txt = '<TABLE width=90% border=0>' txt += format_file_table_header(c...
get a HTML formatted view of all Python programs in all subfolders of AIKIF, including imports and lists of functions and classes
Below is the the instruction that describes the task: ### Input: get a HTML formatted view of all Python programs in all subfolders of AIKIF, including imports and lists of functions and classes ### Response: def get_program_list(): """ get a HTML formatted view of all Python programs in all su...
def js(request): """Returns the javascript needed to run persona""" userid = authenticated_userid(request) user = markupsafe.Markup("'%s'")%userid if userid else "null" redirect_paramater = request.registry['persona.redirect_url_parameter'] came_from = '%s%s' % (request.host_url, ...
Returns the javascript needed to run persona
Below is the the instruction that describes the task: ### Input: Returns the javascript needed to run persona ### Response: def js(request): """Returns the javascript needed to run persona""" userid = authenticated_userid(request) user = markupsafe.Markup("'%s'")%userid if userid else "null" redire...
def handle_action(self, channel, nick, msg): "Core message parser and dispatcher" messages = () for handler in Handler.find_matching(msg, channel): exception_handler = functools.partial( self._handle_exception, handler=handler, ) rest = handler.process(msg) client = connection = event = None ...
Core message parser and dispatcher
Below is the the instruction that describes the task: ### Input: Core message parser and dispatcher ### Response: def handle_action(self, channel, nick, msg): "Core message parser and dispatcher" messages = () for handler in Handler.find_matching(msg, channel): exception_handler = functools.partial( ...
def daylight_utc(self, date, latitude, longitude, observer_elevation=0): """Calculate daylight start and end times in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive...
Calculate daylight start and end times in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive :type latitude: float :param longitude: Longitude - Eastern lon...
Below is the the instruction that describes the task: ### Input: Calculate daylight start and end times in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive :type ...
def save(self, filename, format='auto'): """ Save the SGraph to disk. If the graph is saved in binary format, the graph can be re-loaded using the :py:func:`load_sgraph` method. Alternatively, the SGraph can be saved in JSON format for a human-readable and portable representation...
Save the SGraph to disk. If the graph is saved in binary format, the graph can be re-loaded using the :py:func:`load_sgraph` method. Alternatively, the SGraph can be saved in JSON format for a human-readable and portable representation. Parameters ---------- filename : s...
Below is the the instruction that describes the task: ### Input: Save the SGraph to disk. If the graph is saved in binary format, the graph can be re-loaded using the :py:func:`load_sgraph` method. Alternatively, the SGraph can be saved in JSON format for a human-readable and portable repres...
def delete(): """Deletes local XML file""" path = cache.local_path( filename=ALLELE_XML_FILENAME, url=ALLELE_XML_URL, decompress=ALLELE_XML_DECOMPRESS) os.remove(path)
Deletes local XML file
Below is the the instruction that describes the task: ### Input: Deletes local XML file ### Response: def delete(): """Deletes local XML file""" path = cache.local_path( filename=ALLELE_XML_FILENAME, url=ALLELE_XML_URL, decompress=ALLELE_XML_DECOMPRESS) os.remove(path)
def get_all_handleable(self): """Get list of all known handleable devices.""" nodes = self.get_device_tree() return [node.device for node in sorted(nodes.values(), key=DevNode._sort_key) if not node.ignored and node.device]
Get list of all known handleable devices.
Below is the the instruction that describes the task: ### Input: Get list of all known handleable devices. ### Response: def get_all_handleable(self): """Get list of all known handleable devices.""" nodes = self.get_device_tree() return [node.device for node in sorted(nodes....
def _next_argsig(s): """ given a string, find the next complete argument signature and return it and a new string advanced past that point """ c = s[0] if c in "BCDFIJSVZ": result = (c, s[1:]) elif c == "[": d, s = _next_argsig(s[1:]) result = (c + d, s[len(d) + 1:...
given a string, find the next complete argument signature and return it and a new string advanced past that point
Below is the the instruction that describes the task: ### Input: given a string, find the next complete argument signature and return it and a new string advanced past that point ### Response: def _next_argsig(s): """ given a string, find the next complete argument signature and return it and a new...
def project_surface(surface, angle=DEFAULT_ANGLE): """Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface. """ z_c...
Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface.
Below is the the instruction that describes the task: ### Input: Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface. ### ...
def find_one(self, resource, req, **lookup): """Find single document, if there is _id in lookup use that, otherwise filter.""" if config.ID_FIELD in lookup: return self._find_by_id(resource=resource, _id=lookup[config.ID_FIELD], parent=lookup.get('parent')) else: args = ...
Find single document, if there is _id in lookup use that, otherwise filter.
Below is the the instruction that describes the task: ### Input: Find single document, if there is _id in lookup use that, otherwise filter. ### Response: def find_one(self, resource, req, **lookup): """Find single document, if there is _id in lookup use that, otherwise filter.""" if config.ID_FIE...
def thing_type_exists(thingTypeName, region=None, key=None, keyid=None, profile=None): ''' Given a thing type name, check to see if the given thing type exists Returns True if the given thing type exists and returns False if the given thing type does not exist. .. versionadded:: 2016.1...
Given a thing type name, check to see if the given thing type exists Returns True if the given thing type exists and returns False if the given thing type does not exist. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.thing_type_exists mythingtype
Below is the the instruction that describes the task: ### Input: Given a thing type name, check to see if the given thing type exists Returns True if the given thing type exists and returns False if the given thing type does not exist. .. versionadded:: 2016.11.0 CLI Example: .. code-block::...
def neg(self, value, name=''): """ Integer negative: name = -value """ return self.sub(values.Constant(value.type, 0), value, name=name)
Integer negative: name = -value
Below is the the instruction that describes the task: ### Input: Integer negative: name = -value ### Response: def neg(self, value, name=''): """ Integer negative: name = -value """ return self.sub(values.Constant(value.type, 0), value, name=name)
def _add_method_to_class( target_cls, method_name, func, dataset_name, dataset, dataprovider, repeat_suffix, ): """ Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: ...
Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: `class` :param method_name: Base name of the method to add. :type method_name: `unicode` :param func: The underlying test function to call. ...
Below is the the instruction that describes the task: ### Input: Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: `class` :param method_name: Base name of the method to add. :type method_name: `uni...
def extend(self, schema): """ Extend a structured schema by another. For example extending ``tuple<rstring id, timestamp ts, float64 value>`` with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``. Args: schema(Str...
Extend a structured schema by another. For example extending ``tuple<rstring id, timestamp ts, float64 value>`` with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``. Args: schema(StreamSchema): Schema to extend this schema by. ...
Below is the the instruction that describes the task: ### Input: Extend a structured schema by another. For example extending ``tuple<rstring id, timestamp ts, float64 value>`` with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``. Args:...
def add_child(self, id_, child_id): """Adds a child to a ``Id``. arg: id (osid.id.Id): the ``Id`` of the node arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``child_id`` is already a child of ``id`` raise: NotFound - ``id``...
Adds a child to a ``Id``. arg: id (osid.id.Id): the ``Id`` of the node arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``child_id`` is already a child of ``id`` raise: NotFound - ``id`` or ``child_id`` not found raise: Null...
Below is the the instruction that describes the task: ### Input: Adds a child to a ``Id``. arg: id (osid.id.Id): the ``Id`` of the node arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``child_id`` is already a child of ``id`` rai...
def split_input(args): """Split query input into local files and URLs.""" args['files'] = [] args['urls'] = [] for arg in args['query']: if os.path.isfile(arg): args['files'].append(arg) else: args['urls'].append(arg.strip('/'))
Split query input into local files and URLs.
Below is the the instruction that describes the task: ### Input: Split query input into local files and URLs. ### Response: def split_input(args): """Split query input into local files and URLs.""" args['files'] = [] args['urls'] = [] for arg in args['query']: if os.path.isfile(arg): ...
def _read_ipv6_opts_options(self, length): """Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options """ counter = 0 # length of read options optkind = list() # ...
Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options
Below is the the instruction that describes the task: ### Input: Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options ### Response: def _read_ipv6_opts_options(self, length): """Read IPv6_Op...
def add_samples_stats(samples_table, samples): """ Add stats fields to samples table. The following information is added to each row: - Notes (warnings, errors) resulting from the analysis - Number of Events - Acquisition Time (s) The following information is added for each ro...
Add stats fields to samples table. The following information is added to each row: - Notes (warnings, errors) resulting from the analysis - Number of Events - Acquisition Time (s) The following information is added for each row, for each channel in which fluorescence units have be...
Below is the the instruction that describes the task: ### Input: Add stats fields to samples table. The following information is added to each row: - Notes (warnings, errors) resulting from the analysis - Number of Events - Acquisition Time (s) The following information is added f...
def save_response_to_file(self, response, filename): """Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful """ try: last_response = self.get_last_response() ...
Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful
Below is the the instruction that describes the task: ### Input: Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful ### Response: def save_response_to_file(self, response, filename): """Saves...
def gaps(args): """ %prog gaps OM.bed fastafile Create patches around OM gaps. """ from jcvi.formats.bed import uniq from jcvi.utils.iter import pairwise p = OptionParser(gaps.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) omb...
%prog gaps OM.bed fastafile Create patches around OM gaps.
Below is the the instruction that describes the task: ### Input: %prog gaps OM.bed fastafile Create patches around OM gaps. ### Response: def gaps(args): """ %prog gaps OM.bed fastafile Create patches around OM gaps. """ from jcvi.formats.bed import uniq from jcvi.utils.iter import pa...
def img2code(self, key, img): """Pastes wx.Image into single cell""" code_template = \ "wx.ImageFromData({width}, {height}, " + \ "bz2.decompress(base64.b64decode('{data}'))).ConvertToBitmap()" code_alpha_template = \ "wx.ImageFromDataWithAlpha({width}, {hei...
Pastes wx.Image into single cell
Below is the the instruction that describes the task: ### Input: Pastes wx.Image into single cell ### Response: def img2code(self, key, img): """Pastes wx.Image into single cell""" code_template = \ "wx.ImageFromData({width}, {height}, " + \ "bz2.decompress(base64.b64decode...
def create_container(app_id,container_id,container_name): """ insert container record when create container """ try: conn = get_conn() c = conn.cursor() c.execute("INSERT INTO container (id,name,app_id) VALUES ('{0}','{1}','{2}')" .format(container_id,container_name,a...
insert container record when create container
Below is the the instruction that describes the task: ### Input: insert container record when create container ### Response: def create_container(app_id,container_id,container_name): """ insert container record when create container """ try: conn = get_conn() c = conn.cursor() ...
def get( self: 'Option[Mapping[K,V]]', key: K, default=None ) -> 'Option[V]': """ Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The ...
Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is no...
Below is the the instruction that describes the task: ### Input: Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of t...
def on_delivery(self, name, channel, method, properties, body): """Process a message from Rabbit :param str name: The connection name :param pika.channel.Channel channel: The message's delivery channel :param pika.frames.MethodFrame method: The method frame :param pika.spec.Basi...
Process a message from Rabbit :param str name: The connection name :param pika.channel.Channel channel: The message's delivery channel :param pika.frames.MethodFrame method: The method frame :param pika.spec.BasicProperties properties: The message properties :param str body: The...
Below is the the instruction that describes the task: ### Input: Process a message from Rabbit :param str name: The connection name :param pika.channel.Channel channel: The message's delivery channel :param pika.frames.MethodFrame method: The method frame :param pika.spec.BasicPrope...
def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) return result
Returns total number of all generated adversarial examples.
Below is the the instruction that describes the task: ### Input: Returns total number of all generated adversarial examples. ### Response: def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v...
def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
Reset state.
Below is the the instruction that describes the task: ### Input: Reset state. ### Response: def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
def openSourceFile(self, fileToOpen): """Finds and opens the source file for link target fileToOpen. When links like [test](test) are clicked, the file test.md is opened. It has to be located next to the current opened file. Relative paths like [test](../test) or [test](folder/test) are also possible. """ ...
Finds and opens the source file for link target fileToOpen. When links like [test](test) are clicked, the file test.md is opened. It has to be located next to the current opened file. Relative paths like [test](../test) or [test](folder/test) are also possible.
Below is the the instruction that describes the task: ### Input: Finds and opens the source file for link target fileToOpen. When links like [test](test) are clicked, the file test.md is opened. It has to be located next to the current opened file. Relative paths like [test](../test) or [test](folder/test) a...
def key_string_to_lens_path(key_string): """ Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper'] :param {String} keyString The dot-separated key string :return {[String]} The lens array containing string or integers """ return map( if_else( isinstance(int)...
Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper'] :param {String} keyString The dot-separated key string :return {[String]} The lens array containing string or integers
Below is the the instruction that describes the task: ### Input: Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper'] :param {String} keyString The dot-separated key string :return {[String]} The lens array containing string or integers ### Response: def key_string_to_lens_path(key_string...
def mean_with_attention(x, name, num_heads=4): """Mean and attention to reduce spatial dimensions.""" with tf.variable_scope(name): shape = shape_list(x) m = tf.reduce_mean(x, [1, 2]) a = layers().Dense(num_heads, name="mean_attn")(x) s = tf.reshape(a, [shape[0], -1, num_heads]) s = tf.nn.softma...
Mean and attention to reduce spatial dimensions.
Below is the the instruction that describes the task: ### Input: Mean and attention to reduce spatial dimensions. ### Response: def mean_with_attention(x, name, num_heads=4): """Mean and attention to reduce spatial dimensions.""" with tf.variable_scope(name): shape = shape_list(x) m = tf.reduce_mean(x,...
def concatenate(cls, *args): """Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. """ nargs = len(args) if nargs == 1: return args[0] vs = [a.v for a in args if a.v is not None] vcs = [a.vc for a in ar...
Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces.
Below is the the instruction that describes the task: ### Input: Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. ### Response: def concatenate(cls, *args): """Concatenates an arbitrary number of meshes. Currently supports vertices, vertex...
def refresh(self, count_common=4, min_common=1000, timeout=20): """ Generate a new sentence :param int count_common: the number of words with minimal commonness :param int min_common: the minimal commonness based on Google common word list :param float timeout: time in seconds to...
Generate a new sentence :param int count_common: the number of words with minimal commonness :param int min_common: the minimal commonness based on Google common word list :param float timeout: time in seconds to timeout :return list of str: return tokens on success >>> Generate...
Below is the the instruction that describes the task: ### Input: Generate a new sentence :param int count_common: the number of words with minimal commonness :param int min_common: the minimal commonness based on Google common word list :param float timeout: time in seconds to timeout ...
def capability_functions(self, fn): """This generator yields functions that match the requested capability sorted by z-index.""" if _debug: Collector._debug("capability_functions %r", fn) # build a list of functions to call fns = [] for cls in self.capabilities: ...
This generator yields functions that match the requested capability sorted by z-index.
Below is the the instruction that describes the task: ### Input: This generator yields functions that match the requested capability sorted by z-index. ### Response: def capability_functions(self, fn): """This generator yields functions that match the requested capability sorted by z-index....
def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the value is a string, it is converted to the enum value in enum_type with the same name. If the value is not a st...
Adds an __init__ method to cls.
Below is the the instruction that describes the task: ### Input: Adds an __init__ method to cls. ### Response: def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the...
def parse_argument_list(self): """Parse a list of arguments starting at ``pos``, returning a list of Expression objects. Does not modify ``parts``. Should leave ``pos`` pointing to a } character or the end of the string. """ # Try to parse a subexpression in a subparser. ...
Parse a list of arguments starting at ``pos``, returning a list of Expression objects. Does not modify ``parts``. Should leave ``pos`` pointing to a } character or the end of the string.
Below is the the instruction that describes the task: ### Input: Parse a list of arguments starting at ``pos``, returning a list of Expression objects. Does not modify ``parts``. Should leave ``pos`` pointing to a } character or the end of the string. ### Response: def parse_argument_list(s...
def libvlc_media_add_option_flag(p_md, psz_options, i_flags): '''Add an option to the media with configurable flags. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detai...
Add an option to the media with configurable flags. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all". Note that all ...
Below is the the instruction that describes the task: ### Input: Add an option to the media with configurable flags. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detai...
def array_remove(col, element): """ Collection function: Remove all elements that equal to element from the given array. :param col: name of column containing array :param element: element to be removed from the array >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) >>> df...
Collection function: Remove all elements that equal to element from the given array. :param col: name of column containing array :param element: element to be removed from the array >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) >>> df.select(array_remove(df.data, 1)).collect() ...
Below is the the instruction that describes the task: ### Input: Collection function: Remove all elements that equal to element from the given array. :param col: name of column containing array :param element: element to be removed from the array >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([]...
def add(self, key, skip_check=False): """ Adds a key to this bloom filter. If the key already exists in this filter it will return True. Otherwise False. >>> b = BloomFilter(capacity=100) >>> b.add("hello") False >>> b.add("hello") True >>> b.count ...
Adds a key to this bloom filter. If the key already exists in this filter it will return True. Otherwise False. >>> b = BloomFilter(capacity=100) >>> b.add("hello") False >>> b.add("hello") True >>> b.count 1
Below is the the instruction that describes the task: ### Input: Adds a key to this bloom filter. If the key already exists in this filter it will return True. Otherwise False. >>> b = BloomFilter(capacity=100) >>> b.add("hello") False >>> b.add("hello") True ...
def validate_matrix(self, data): """Validates matrix data and creates the config objects""" is_grid_search = ( data.get('grid_search') is not None or (data.get('grid_search') is None and data.get('random_search') is None and data.get('hyperband') is None...
Validates matrix data and creates the config objects
Below is the the instruction that describes the task: ### Input: Validates matrix data and creates the config objects ### Response: def validate_matrix(self, data): """Validates matrix data and creates the config objects""" is_grid_search = ( data.get('grid_search') is not None or ...
def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__pillar__['proxy'].get('username', 'root')] passwords = __pillar__['proxy']['passwords'] for user in user_names: for password in passwords: t...
Cycle through all the possible credentials and return the first one that works.
Below is the the instruction that describes the task: ### Input: Cycle through all the possible credentials and return the first one that works. ### Response: def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__...
def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use): """Render all the pages of the PDF file at pdf_file_name to image files with path and filename prefix given by output_filename_root. Any directories must have already been created, and the calling program is responsibl...
Render all the pages of the PDF file at pdf_file_name to image files with path and filename prefix given by output_filename_root. Any directories must have already been created, and the calling program is responsible for deleting any directories or image files. The program program_to_use, currently ei...
Below is the the instruction that describes the task: ### Input: Render all the pages of the PDF file at pdf_file_name to image files with path and filename prefix given by output_filename_root. Any directories must have already been created, and the calling program is responsible for deleting any dire...
def dump_privatekey(type, pkey, cipher=None, passphrase=None): """ Dump the private key *pkey* into a buffer string encoded with the type *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it using *cipher* and *passphrase*. :param type: The file type (one of :const:`FILETYPE_PEM`,...
Dump the private key *pkey* into a buffer string encoded with the type *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it using *cipher* and *passphrase*. :param type: The file type (one of :const:`FILETYPE_PEM`, :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`) :param PKey...
Below is the the instruction that describes the task: ### Input: Dump the private key *pkey* into a buffer string encoded with the type *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it using *cipher* and *passphrase*. :param type: The file type (one of :const:`FILETYPE_PEM`, ...
def automatic_parser(result, dtypes={}, converters={}): """ Try and automatically convert strings formatted as tables into nested list structures. Under the hood, this function essentially applies the genfromtxt function to all files in the output, and passes it the additional kwargs. Args: ...
Try and automatically convert strings formatted as tables into nested list structures. Under the hood, this function essentially applies the genfromtxt function to all files in the output, and passes it the additional kwargs. Args: result (dict): the result to parse. dtypes (dict): a dicti...
Below is the the instruction that describes the task: ### Input: Try and automatically convert strings formatted as tables into nested list structures. Under the hood, this function essentially applies the genfromtxt function to all files in the output, and passes it the additional kwargs. Args: ...
def replace_multi(self, keys, ttl=0, format=None, persist_to=0, replicate_to=0): """Replace multiple keys. Multi variant of :meth:`replace` .. seealso:: :meth:`replace`, :meth:`upsert_multi`, :meth:`upsert` """ return _Base.replace_multi(self, keys, ttl=ttl, format...
Replace multiple keys. Multi variant of :meth:`replace` .. seealso:: :meth:`replace`, :meth:`upsert_multi`, :meth:`upsert`
Below is the the instruction that describes the task: ### Input: Replace multiple keys. Multi variant of :meth:`replace` .. seealso:: :meth:`replace`, :meth:`upsert_multi`, :meth:`upsert` ### Response: def replace_multi(self, keys, ttl=0, format=None, persist_to=0, replicate_to=0): ...
def terminate(self): """ Send termination signal to DAG parsing processor manager and expect it to terminate all DAG file processors. """ self.log.info("Sending termination message to manager.") self._child_signal_conn.send(DagParsingSignal.TERMINATE_MANAGER)
Send termination signal to DAG parsing processor manager and expect it to terminate all DAG file processors.
Below is the the instruction that describes the task: ### Input: Send termination signal to DAG parsing processor manager and expect it to terminate all DAG file processors. ### Response: def terminate(self): """ Send termination signal to DAG parsing processor manager and expect it...
def generate_facecolors(x, y, z, dx, dy, dz, color): """Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x (array_like): The x- coordinates of the anchor point of the bars. y (array_like): The y- coordinat...
Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x (array_like): The x- coordinates of the anchor point of the bars. y (array_like): The y- coordinates of the anchor point of the bars. z (array_like): ...
Below is the the instruction that describes the task: ### Input: Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x (array_like): The x- coordinates of the anchor point of the bars. y (array_like): The y- ...
def is_negative(self): """ Ensures :attr:`subject` is less than 0. """ self._run(unittest_case.assertLess, (self._subject, 0)) return ChainInspector(self._subject)
Ensures :attr:`subject` is less than 0.
Below is the the instruction that describes the task: ### Input: Ensures :attr:`subject` is less than 0. ### Response: def is_negative(self): """ Ensures :attr:`subject` is less than 0. """ self._run(unittest_case.assertLess, (self._subject, 0)) return ChainInspector(self._s...
def set_phases(self, literals=[]): """ Sets polarities of a given list of variables. """ if self.maplesat: pysolvers.maplesat_setphases(self.maplesat, literals)
Sets polarities of a given list of variables.
Below is the the instruction that describes the task: ### Input: Sets polarities of a given list of variables. ### Response: def set_phases(self, literals=[]): """ Sets polarities of a given list of variables. """ if self.maplesat: pysolvers.maplesat_setphases(self....
def __verify_db_file_existence(self, database_path): """ :raises SimpleSQLite.OperationalError: If unable to open database file. """ self.__validate_db_path(database_path) if not os.path.isfile(os.path.realpath(database_path)): raise IOError("file not found: " + data...
:raises SimpleSQLite.OperationalError: If unable to open database file.
Below is the the instruction that describes the task: ### Input: :raises SimpleSQLite.OperationalError: If unable to open database file. ### Response: def __verify_db_file_existence(self, database_path): """ :raises SimpleSQLite.OperationalError: If unable to open database file. """ ...
def get_page_tags_from_request(request, page_lookup, lang, site, title=False): """ Get the list of tags attached to a Page or a Title from a request from usual `page_lookup` parameters. :param request: request object :param page_lookup: a valid page_lookup argument :param lang: a language code...
Get the list of tags attached to a Page or a Title from a request from usual `page_lookup` parameters. :param request: request object :param page_lookup: a valid page_lookup argument :param lang: a language code :param site: a site id :param title: a boolean to extract the Page (if False) or T...
Below is the the instruction that describes the task: ### Input: Get the list of tags attached to a Page or a Title from a request from usual `page_lookup` parameters. :param request: request object :param page_lookup: a valid page_lookup argument :param lang: a language code :param site: a si...
def main(): """The main function.""" global config parser = OptionParser(version='%prog v' + __version__) parser.add_option('-c', '--config', default='config.ini', help='Location of config file (default: %default)', metavar='FILE') parser.add_option('-a', ...
The main function.
Below is the the instruction that describes the task: ### Input: The main function. ### Response: def main(): """The main function.""" global config parser = OptionParser(version='%prog v' + __version__) parser.add_option('-c', '--config', default='config.ini', help='Location ...
def format_z(cls, offset): """ Format `timedelta` into %z """ sec = offset.total_seconds() return '{s}{h:02d}{m:02d}'.format(s='-' if sec<0 else '+', h=abs(int(sec/3600)), m=int((sec%3600)/60))
Format `timedelta` into %z
Below is the the instruction that describes the task: ### Input: Format `timedelta` into %z ### Response: def format_z(cls, offset): """ Format `timedelta` into %z """ sec = offset.total_seconds() return '{s}{h:02d}{m:02d}'.format(s='-' if sec<0 else '+', h=abs(int(sec/3600)), m=int((sec%36...
def format_info_response(value): """Format the response from redis :param str value: The return response from redis :rtype: dict """ info = {} for line in value.decode('utf-8').splitlines(): if not line or line[0] == '#': continue if ':' in line: key, va...
Format the response from redis :param str value: The return response from redis :rtype: dict
Below is the the instruction that describes the task: ### Input: Format the response from redis :param str value: The return response from redis :rtype: dict ### Response: def format_info_response(value): """Format the response from redis :param str value: The return response from redis :rtyp...
def _extract_optional_list_field(blob, name): '''Handle optional fields that can be either a string or a list of strings.''' value = _optional_list(typesafe_pop(blob, name, [])) if value is None: raise ParserError( '"{}" field must be a string or a list.'.format(name)) return val...
Handle optional fields that can be either a string or a list of strings.
Below is the the instruction that describes the task: ### Input: Handle optional fields that can be either a string or a list of strings. ### Response: def _extract_optional_list_field(blob, name): '''Handle optional fields that can be either a string or a list of strings.''' value = _optional_list...
def dpgrdr(body, x, y, z, re, f): """ This routine computes the Jacobian matrix of the transformation from rectangular to planetographic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpgrdr_c.html :param body: Body with which coordinate system is associated. :type body: ...
This routine computes the Jacobian matrix of the transformation from rectangular to planetographic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpgrdr_c.html :param body: Body with which coordinate system is associated. :type body: str :param x: X-coordinate of point. :...
Below is the the instruction that describes the task: ### Input: This routine computes the Jacobian matrix of the transformation from rectangular to planetographic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpgrdr_c.html :param body: Body with which coordinate system is assoc...
def main(serial=None, host=None, port=None, scale=0.5, simple=False): '''interact''' if simple: screen_simple(host, port, serial, scale) else: screen_with_controls(host, port, serial, scale)
interact
Below is the the instruction that describes the task: ### Input: interact ### Response: def main(serial=None, host=None, port=None, scale=0.5, simple=False): '''interact''' if simple: screen_simple(host, port, serial, scale) else: screen_with_controls(host, port, serial, scale)
def time_entries(self, start_date=None, end_date=None): '''Array of all time entries''' if self.cache['time_entries']: return self.cache['time_entries'] if not start_date: start_date = datetime.date(1900, 1, 1) if not end_date: end_date = datetime.date.today() ...
Array of all time entries
Below is the the instruction that describes the task: ### Input: Array of all time entries ### Response: def time_entries(self, start_date=None, end_date=None): '''Array of all time entries''' if self.cache['time_entries']: return self.cache['time_entries'] if not start_date: st...
def form_upload_valid(self, form): """Handle a valid upload form.""" self.current_step = self.STEP_LINES lines = form.cleaned_data['file'] initial_lines = [dict(zip(self.get_columns(), line)) for line in lines] inner_form = self.get_form(self.get_form_class(), data=N...
Handle a valid upload form.
Below is the the instruction that describes the task: ### Input: Handle a valid upload form. ### Response: def form_upload_valid(self, form): """Handle a valid upload form.""" self.current_step = self.STEP_LINES lines = form.cleaned_data['file'] initial_lines = [dict(zip(self.get_c...
def StreamMetrics(self, request_iterator, context): """Dispatches metrics streamed by collector""" LOG.debug("StreamMetrics called") # set up arguments collect_args = (next(request_iterator)) max_metrics_buffer = 0 max_collect_duration = 0 cfg = Metric(pb=collect...
Dispatches metrics streamed by collector
Below is the the instruction that describes the task: ### Input: Dispatches metrics streamed by collector ### Response: def StreamMetrics(self, request_iterator, context): """Dispatches metrics streamed by collector""" LOG.debug("StreamMetrics called") # set up arguments collect_ar...
def flatten(self, obj): """Return a list with the field values """ return [self._serialize(f, obj) for f in self.fields]
Return a list with the field values
Below is the the instruction that describes the task: ### Input: Return a list with the field values ### Response: def flatten(self, obj): """Return a list with the field values """ return [self._serialize(f, obj) for f in self.fields]
def prepare_batch(self, batch: mx.io.DataBatch): """ Pre-fetches the next mini-batch. :param batch: The mini-batch to prepare. """ self.module.prepare(batch)
Pre-fetches the next mini-batch. :param batch: The mini-batch to prepare.
Below is the the instruction that describes the task: ### Input: Pre-fetches the next mini-batch. :param batch: The mini-batch to prepare. ### Response: def prepare_batch(self, batch: mx.io.DataBatch): """ Pre-fetches the next mini-batch. :param batch: The mini-batch to prepare. ...
def execute_deploy_clone_from_vm(self, si, logger, vcenter_data_model, reservation_id, deployment_params, cancellation_context, folder_manager): """ Calls the deployer to deploy vm from another vm :param cancellation_context: :param str reservation_id: :param si: :param l...
Calls the deployer to deploy vm from another vm :param cancellation_context: :param str reservation_id: :param si: :param logger: :type deployment_params: DeployFromTemplateDetails :param vcenter_data_model: :return:
Below is the the instruction that describes the task: ### Input: Calls the deployer to deploy vm from another vm :param cancellation_context: :param str reservation_id: :param si: :param logger: :type deployment_params: DeployFromTemplateDetails :param vcenter_data_mo...
def xml_to_json(root, tag_prefix=None, on_tag={}): ''' Parses a XML element to JSON format. This is a relatively generic function parsing a XML element to JSON format. It does not guarantee any specific formal behaviour but is empirically known to "work well" with respect to the author's needs....
Parses a XML element to JSON format. This is a relatively generic function parsing a XML element to JSON format. It does not guarantee any specific formal behaviour but is empirically known to "work well" with respect to the author's needs. External verification of the returned results by the user ...
Below is the the instruction that describes the task: ### Input: Parses a XML element to JSON format. This is a relatively generic function parsing a XML element to JSON format. It does not guarantee any specific formal behaviour but is empirically known to "work well" with respect to the author's ...
def delete_subscription(self): """Delete subscription for this thread. :returns: bool """ url = self._build_url('subscription', base_url=self._api) return self._boolean(self._delete(url), 204, 404)
Delete subscription for this thread. :returns: bool
Below is the the instruction that describes the task: ### Input: Delete subscription for this thread. :returns: bool ### Response: def delete_subscription(self): """Delete subscription for this thread. :returns: bool """ url = self._build_url('subscription', base_url=self....
def paste_action_callback(self, *event): """Add clipboard key value pairs into all selected sub-dictionary""" if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None: _, dict_paths = self.get_view_selection() selected_data_list = rafcon.gui.clipbo...
Add clipboard key value pairs into all selected sub-dictionary
Below is the the instruction that describes the task: ### Input: Add clipboard key value pairs into all selected sub-dictionary ### Response: def paste_action_callback(self, *event): """Add clipboard key value pairs into all selected sub-dictionary""" if react_to_event(self.view, self.tree_view, ev...
def best_sell_3(self): """三日均價由上往下 """ return self.data.continuous(self.data.moving_average(self.data.price, 3)) == -1
三日均價由上往下
Below is the the instruction that describes the task: ### Input: 三日均價由上往下 ### Response: def best_sell_3(self): """三日均價由上往下 """ return self.data.continuous(self.data.moving_average(self.data.price, 3)) == -1
def deletenode(self, node): """ >>> l = DLL() >>> l.push(1) >>> l [1] >>> l.size() 1 >>> l.deletenode(l._first) >>> l [] >>> l.size() 0 >>> l._index {} >>> l._first """ if self._last =...
>>> l = DLL() >>> l.push(1) >>> l [1] >>> l.size() 1 >>> l.deletenode(l._first) >>> l [] >>> l.size() 0 >>> l._index {} >>> l._first
Below is the the instruction that describes the task: ### Input: >>> l = DLL() >>> l.push(1) >>> l [1] >>> l.size() 1 >>> l.deletenode(l._first) >>> l [] >>> l.size() 0 >>> l._index {} >>> l._first ### Response: ...
def _slow_calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw): """Python implementation of ``calcbinflux``. This is only used if ``synphot.synphot_utils`` C-extension import fails. See docstrings.py """ binflux = np.empty(shape=(len_binwave, ), dtype=np.float64) intwave = np.empty(shap...
Python implementation of ``calcbinflux``. This is only used if ``synphot.synphot_utils`` C-extension import fails. See docstrings.py
Below is the the instruction that describes the task: ### Input: Python implementation of ``calcbinflux``. This is only used if ``synphot.synphot_utils`` C-extension import fails. See docstrings.py ### Response: def _slow_calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw): """Python implement...
def fit(self, X, y): """Fit estimator. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and t...
Fit estimator. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censorin...
Below is the the instruction that describes the task: ### Input: Fit estimator. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indica...
def initialize( plugins, exclude_files_regex=None, exclude_lines_regex=None, path='.', scan_all_files=False, ): """Scans the entire codebase for secrets, and returns a SecretsCollection object. :type plugins: tuple of detect_secrets.plugins.base.BasePlugin :param plugins: rules to i...
Scans the entire codebase for secrets, and returns a SecretsCollection object. :type plugins: tuple of detect_secrets.plugins.base.BasePlugin :param plugins: rules to initialize the SecretsCollection with. :type exclude_files_regex: str|None :type exclude_lines_regex: str|None :type path: str ...
Below is the the instruction that describes the task: ### Input: Scans the entire codebase for secrets, and returns a SecretsCollection object. :type plugins: tuple of detect_secrets.plugins.base.BasePlugin :param plugins: rules to initialize the SecretsCollection with. :type exclude_files_regex: ...
async def _create_rev_reg(self, rr_id: str, rr_size: int = None) -> None: """ Create revocation registry and new tails file (and association to corresponding revocation registry definition via symbolic link) for input revocation registry identifier. :param rr_id: revocation regi...
Create revocation registry and new tails file (and association to corresponding revocation registry definition via symbolic link) for input revocation registry identifier. :param rr_id: revocation registry identifier :param rr_size: revocation registry size (defaults to 256)
Below is the the instruction that describes the task: ### Input: Create revocation registry and new tails file (and association to corresponding revocation registry definition via symbolic link) for input revocation registry identifier. :param rr_id: revocation registry identifier :...
def _create_equivalence_transform(equiv): """Compute an equivalence transformation that transforms this compound to another compound's coordinate system. Parameters ---------- equiv : np.ndarray, shape=(n, 3), dtype=float Array of equivalent points. Returns ------- T : Coordina...
Compute an equivalence transformation that transforms this compound to another compound's coordinate system. Parameters ---------- equiv : np.ndarray, shape=(n, 3), dtype=float Array of equivalent points. Returns ------- T : CoordinateTransform Transform that maps this poin...
Below is the the instruction that describes the task: ### Input: Compute an equivalence transformation that transforms this compound to another compound's coordinate system. Parameters ---------- equiv : np.ndarray, shape=(n, 3), dtype=float Array of equivalent points. Returns ----...
def add_category(self, category): """ Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately....
Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names...
Below is the the instruction that describes the task: ### Input: Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effe...
def get_conn(): ''' Return a conn object for the passed VM data ''' return ProfitBricksService( username=config.get_cloud_config_value( 'username', get_configured_provider(), __opts__, search_global=False ), password=config.get_clou...
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 ''' return ProfitBricksService( username=config.get_cloud_config_value( 'username', ...
def verbosityToLogLevel(verbosity): """ Returns the specfied verbosity level interpreted as a logging level. """ ret = 0 if verbosity == 1: ret = logging.INFO elif verbosity >= 2: ret = logging.DEBUG return ret
Returns the specfied verbosity level interpreted as a logging level.
Below is the the instruction that describes the task: ### Input: Returns the specfied verbosity level interpreted as a logging level. ### Response: def verbosityToLogLevel(verbosity): """ Returns the specfied verbosity level interpreted as a logging level. """ ret = 0 if verbosity == 1: ...
def listfilepath(p): """ generator of list files in the path. filenames only """ for entry in scandir.scandir(p): if entry.is_file(): yield entry.path
generator of list files in the path. filenames only
Below is the the instruction that describes the task: ### Input: generator of list files in the path. filenames only ### Response: def listfilepath(p): """ generator of list files in the path. filenames only """ for entry in scandir.scandir(p): if entry.is_file(): yield ...
def create_model(self): """Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`. """ properties = { 'name': self.name, 'default_flux_limit': 1000 } # Load objective as biomass reaction objective = se...
Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`.
Below is the the instruction that describes the task: ### Input: Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`. ### Response: def create_model(self): """Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel...
def note(name, source=None, contents=None, **kwargs): ''' Add content to a document generated using `highstate_doc.render`. This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers to include extra documents. .. code-block:: yaml {{sls}} exa...
Add content to a document generated using `highstate_doc.render`. This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers to include extra documents. .. code-block:: yaml {{sls}} example note: highstate_doc.note: - name:...
Below is the the instruction that describes the task: ### Input: Add content to a document generated using `highstate_doc.render`. This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers to include extra documents. .. code-block:: yaml {{sls}} ...
def readin_volt(filename): """Read in measurement data from a volt.dat file and return electrodes and measured resistance. """ with open(filename, 'r') as fid: content = np.loadtxt(fid, skiprows=1, usecols=[0, 1, 2]) volt = content[:, 2] elecs = content[:, 0:2] return elecs, ...
Read in measurement data from a volt.dat file and return electrodes and measured resistance.
Below is the the instruction that describes the task: ### Input: Read in measurement data from a volt.dat file and return electrodes and measured resistance. ### Response: def readin_volt(filename): """Read in measurement data from a volt.dat file and return electrodes and measured resistance. """ ...
def _connect_model_signals(model): """Connect signals for a single model.""" dispatch_uid = "%s.post_save" % model._meta.model_name logger.debug("Connecting search index model post_save signal: %s", dispatch_uid) signals.post_save.connect(_on_model_save, sender=model, dispatch_uid=dispatch_uid) disp...
Connect signals for a single model.
Below is the the instruction that describes the task: ### Input: Connect signals for a single model. ### Response: def _connect_model_signals(model): """Connect signals for a single model.""" dispatch_uid = "%s.post_save" % model._meta.model_name logger.debug("Connecting search index model post_save si...
def _Viscosity(rho, T, fase=None, drho=None): """Equation for the Viscosity Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] fase: dict, optional for calculate critical enhancement phase properties drho: float, optional for calculate crit...
Equation for the Viscosity Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] fase: dict, optional for calculate critical enhancement phase properties drho: float, optional for calculate critical enhancement [∂ρ/∂P]T at reference state,...
Below is the the instruction that describes the task: ### Input: Equation for the Viscosity Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] fase: dict, optional for calculate critical enhancement phase properties drho: float, optional fo...
def add_item(self, radius, item_type): """ Add a single item in random open position """ assert isinstance(radius, int) or isinstance(radius, float) assert isinstance(item_type, str) separation_scale = 1.1 min_separation = separation_scale * radius # Rem...
Add a single item in random open position
Below is the the instruction that describes the task: ### Input: Add a single item in random open position ### Response: def add_item(self, radius, item_type): """ Add a single item in random open position """ assert isinstance(radius, int) or isinstance(radius, float) asser...
def system_monitor_MM_threshold_down_threshold(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") MM = ET.SubElement(system_monitor, "MM") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def system_monitor_MM_threshold_down_threshold(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns=...
def get_prep_value(self, value: LocalizedIntegerValue) -> dict: """Gets the value in a format to store into the database.""" # apply default values default_values = LocalizedIntegerValue(self.default) if isinstance(value, LocalizedIntegerValue): for lang_code, _ in settings....
Gets the value in a format to store into the database.
Below is the the instruction that describes the task: ### Input: Gets the value in a format to store into the database. ### Response: def get_prep_value(self, value: LocalizedIntegerValue) -> dict: """Gets the value in a format to store into the database.""" # apply default values default_...
def save(self, *args, **kwargs): """save(filething=None, padding=None)""" super(MP4, self).save(*args, **kwargs)
save(filething=None, padding=None)
Below is the the instruction that describes the task: ### Input: save(filething=None, padding=None) ### Response: def save(self, *args, **kwargs): """save(filething=None, padding=None)""" super(MP4, self).save(*args, **kwargs)
def connect(self, timeout_sec=TIMEOUT_SEC): """Connect to the device. If not connected within the specified timeout then an exception is thrown. """ self._connected.clear() self._device.Connect() if not self._connected.wait(timeout_sec): raise RuntimeError('E...
Connect to the device. If not connected within the specified timeout then an exception is thrown.
Below is the the instruction that describes the task: ### Input: Connect to the device. If not connected within the specified timeout then an exception is thrown. ### Response: def connect(self, timeout_sec=TIMEOUT_SEC): """Connect to the device. If not connected within the specified timeout ...
def _uploadStream(self, fileName, update=False, encrypt=True): """ Yields a context manager that can be used to write to the bucket with a stream. See :class:`~toil.jobStores.utils.WritablePipe` for an example. Will throw assertion error if the file shouldn't be updated and yet ...
Yields a context manager that can be used to write to the bucket with a stream. See :class:`~toil.jobStores.utils.WritablePipe` for an example. Will throw assertion error if the file shouldn't be updated and yet exists. :param fileName: name of file to be inserted into bucket :...
Below is the the instruction that describes the task: ### Input: Yields a context manager that can be used to write to the bucket with a stream. See :class:`~toil.jobStores.utils.WritablePipe` for an example. Will throw assertion error if the file shouldn't be updated and yet exists. ...