code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _find_files(root, includes, excludes, follow_symlinks): """List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[s...
List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those pat...
Below is the the instruction that describes the task: ### Input: List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list...
def compute_default_choice(self): """Computes and sets the default choice""" choices = self.choices if len(choices) == 0: return None high_choice = max(choices, key=lambda choice: choice.performance) self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "defau...
Computes and sets the default choice
Below is the the instruction that describes the task: ### Input: Computes and sets the default choice ### Response: def compute_default_choice(self): """Computes and sets the default choice""" choices = self.choices if len(choices) == 0: return None high_choice = max(...
def _make_sure_table_exists(self, name_seq): """ Makes sure the table with the full name comprising of name_seq exists. """ t = self for key in name_seq[:-1]: t = t[key] name = name_seq[-1] if name not in t: self.append_elements([element_fa...
Makes sure the table with the full name comprising of name_seq exists.
Below is the the instruction that describes the task: ### Input: Makes sure the table with the full name comprising of name_seq exists. ### Response: def _make_sure_table_exists(self, name_seq): """ Makes sure the table with the full name comprising of name_seq exists. """ t = self ...
def add_scroll_bar(self): """Packs the scrollbar. """ adj = self.terminal.get_vadjustment() scroll = Gtk.VScrollbar(adj) scroll.show() self.pack_start(scroll, False, False, 0)
Packs the scrollbar.
Below is the the instruction that describes the task: ### Input: Packs the scrollbar. ### Response: def add_scroll_bar(self): """Packs the scrollbar. """ adj = self.terminal.get_vadjustment() scroll = Gtk.VScrollbar(adj) scroll.show() self.pack_start(scroll, False, F...
def get_image_layer(self, image_id): """GET /v1/images/(image_id)/json""" return self._http_call(self.IMAGE_JSON, get, image_id=image_id)
GET /v1/images/(image_id)/json
Below is the the instruction that describes the task: ### Input: GET /v1/images/(image_id)/json ### Response: def get_image_layer(self, image_id): """GET /v1/images/(image_id)/json""" return self._http_call(self.IMAGE_JSON, get, image_id=image_id)
def Boolean(): """ Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t...
Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t, true`` * ``n, no, f, ...
Below is the the instruction that describes the task: ### Input: Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted i...
def datetime_field_data(field, **kwargs): """ Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'> """ from_date = kwargs.get('from_date', datetime(1990, 1, 1)) to_date = kwargs.get('to_date', datetime.today()) date_f...
Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'>
Below is the the instruction that describes the task: ### Input: Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'> ### Response: def datetime_field_data(field, **kwargs): """ Return random value for DateTimeField >>> res...
def _get_snmpv3(self, oid): """ Try to send an SNMP GET operation using SNMPv3 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value ...
Try to send an SNMP GET operation using SNMPv3 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value from the OID you are trying to retrieve.
Below is the the instruction that describes the task: ### Input: Try to send an SNMP GET operation using SNMPv3 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string ...
def poll_job(self, job_key, timeoutSecs=10, retryDelaySecs=0.5, key=None, **kwargs): ''' Poll a single job from the /Jobs endpoint until it is "status": "DONE" or "CANCELLED" or "FAILED" or we time out. ''' params_dict = {} # merge kwargs into params_dict h2o_methods.check_params_update_kwargs(p...
Poll a single job from the /Jobs endpoint until it is "status": "DONE" or "CANCELLED" or "FAILED" or we time out.
Below is the the instruction that describes the task: ### Input: Poll a single job from the /Jobs endpoint until it is "status": "DONE" or "CANCELLED" or "FAILED" or we time out. ### Response: def poll_job(self, job_key, timeoutSecs=10, retryDelaySecs=0.5, key=None, **kwargs): ''' Poll a single job from th...
def add_content_type(self, ct): """ Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute """ lst = self._attributes.get("ct") if lst is None: lst = [] if isinstance(ct, str): ct = defines.Conten...
Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute
Below is the the instruction that describes the task: ### Input: Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute ### Response: def add_content_type(self, ct): """ Add a CoRE Link Format ct attribute to the resource. :param ct: the ...
def separate_particles_into_groups(s, region_size=40, bounds=None, doshift=False): """ Separates particles into convenient groups for optimization. Given a state, returns a list of groups of particles. Each group of particles are located near each other in the image. Every particle located ...
Separates particles into convenient groups for optimization. Given a state, returns a list of groups of particles. Each group of particles are located near each other in the image. Every particle located in the desired region is contained in exactly 1 group. Parameters ---------- s : :class:`p...
Below is the the instruction that describes the task: ### Input: Separates particles into convenient groups for optimization. Given a state, returns a list of groups of particles. Each group of particles are located near each other in the image. Every particle located in the desired region is contained...
def contents(self, path, ref=None): """Get the contents of the file pointed to by ``path``. If the path provided is actually a directory, you will receive a dictionary back of the form:: { 'filename.md': Contents(), # Where Contents an instance 'git...
Get the contents of the file pointed to by ``path``. If the path provided is actually a directory, you will receive a dictionary back of the form:: { 'filename.md': Contents(), # Where Contents an instance 'github.py': Contents(), } :pa...
Below is the the instruction that describes the task: ### Input: Get the contents of the file pointed to by ``path``. If the path provided is actually a directory, you will receive a dictionary back of the form:: { 'filename.md': Contents(), # Where Contents an instanc...
def is_met(self, ti, session, dep_context=None): """ Returns whether or not this dependency is met for a given task instance. A dependency is considered met if all of the dependency statuses it reports are passing. :param ti: the task instance to see if this dependency is met fo...
Returns whether or not this dependency is met for a given task instance. A dependency is considered met if all of the dependency statuses it reports are passing. :param ti: the task instance to see if this dependency is met for :type ti: airflow.models.TaskInstance :param sessio...
Below is the the instruction that describes the task: ### Input: Returns whether or not this dependency is met for a given task instance. A dependency is considered met if all of the dependency statuses it reports are passing. :param ti: the task instance to see if this dependency is met fo...
def element_should_be_disabled(self, locator, loglevel='INFO'): """Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ if self._element_find(locato...
Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements.
Below is the the instruction that describes the task: ### Input: Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. ### Response: def element_should_be_disabled(self, locat...
def _client_allowed(self): """Check if client is allowed to connect to this server.""" client_ip = self._client_address[0] if not client_ip in self._settings.allowed_clients and \ not 'ALL' in self._settings.allowed_clients: content = 'Access from host {} forbidden.'.format(client_ip).encode('u...
Check if client is allowed to connect to this server.
Below is the the instruction that describes the task: ### Input: Check if client is allowed to connect to this server. ### Response: def _client_allowed(self): """Check if client is allowed to connect to this server.""" client_ip = self._client_address[0] if not client_ip in self._settings.allowed_clie...
def watch(self, path, func=None, delay=0, ignore=None): """Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to n...
Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to not send it. This is useful to compile sass files to ...
Below is the the instruction that describes the task: ### Input: Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to ...
def plot(self, name, funcname): """Plot item""" sw = self.shellwidget if sw._reading: sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name)) else: sw.execute("%%varexp --%s %s" % (funcname, name))
Plot item
Below is the the instruction that describes the task: ### Input: Plot item ### Response: def plot(self, name, funcname): """Plot item""" sw = self.shellwidget if sw._reading: sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name)) else: sw.execute("%%...
def check_save(sender, **kwargs): """ Checks item type uniqueness, field applicability and multiplicity. """ tag = kwargs['instance'] obj = Tag.get_object(tag) previous_tags = Tag.get_tags(obj) err_uniq = check_item_type_uniqueness(tag, previous_tags) err_appl = check_field_applicab...
Checks item type uniqueness, field applicability and multiplicity.
Below is the the instruction that describes the task: ### Input: Checks item type uniqueness, field applicability and multiplicity. ### Response: def check_save(sender, **kwargs): """ Checks item type uniqueness, field applicability and multiplicity. """ tag = kwargs['instance'] obj = Tag.get_o...
def get(self, spike_ids, channels=None): """Load the waveforms of the specified spikes.""" if isinstance(spike_ids, slice): spike_ids = _range_from_slice(spike_ids, start=0, stop=self.n_spikes, ...
Load the waveforms of the specified spikes.
Below is the the instruction that describes the task: ### Input: Load the waveforms of the specified spikes. ### Response: def get(self, spike_ids, channels=None): """Load the waveforms of the specified spikes.""" if isinstance(spike_ids, slice): spike_ids = _range_from_slice(spike_ids,...
def top_1(x, reduced_dim, dtype=tf.int32, name=None): """Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce_max(x, re...
Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce_max(x, reduced_dim=reduced_dim)
Below is the the instruction that describes the task: ### Input: Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce...
def main(): """Main""" lic = ( 'License :: OSI Approved :: GNU Affero ' 'General Public License v3 or later (AGPLv3+)') version = load_source("version", os.path.join("spamc", "version.py")) opts = dict( name="spamc", version=version.__version__, description="Pyth...
Main
Below is the the instruction that describes the task: ### Input: Main ### Response: def main(): """Main""" lic = ( 'License :: OSI Approved :: GNU Affero ' 'General Public License v3 or later (AGPLv3+)') version = load_source("version", os.path.join("spamc", "version.py")) opts = d...
def open_without_clobber(name, *args): """ Try to open the given file with the given mode; if that filename exists, try "name.1", "name.2", etc. until we find an unused filename. """ fd = None count = 1 orig_name = name while fd is None: try: fd = os.open(name, os.O_C...
Try to open the given file with the given mode; if that filename exists, try "name.1", "name.2", etc. until we find an unused filename.
Below is the the instruction that describes the task: ### Input: Try to open the given file with the given mode; if that filename exists, try "name.1", "name.2", etc. until we find an unused filename. ### Response: def open_without_clobber(name, *args): """ Try to open the given file with the given mod...
def set_seq1(self, a): """Set the first sequence to be compared. The second sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq1("bcde") >>> s.ratio() 1.0 >>> SequenceMat...
Set the first sequence to be compared. The second sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq1("bcde") >>> s.ratio() 1.0 >>> SequenceMatcher computes and caches detailed ...
Below is the the instruction that describes the task: ### Input: Set the first sequence to be compared. The second sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq1("bcde") >>> s.ratio() 1...
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
Returns the planet radiustype given the mass and using planetAssumptions['radiusType']
Below is the the instruction that describes the task: ### Input: Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] ### Response: def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius i...
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are...
Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and log...
Below is the the instruction that describes the task: ### Input: Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have b...
def _generateMetricsSubstitutions(options, tokenReplacements): """Generate the token substitution for metrics related fields. This includes: \$METRICS \$LOGGED_METRICS \$PERM_OPTIMIZE_SETTING """ # ----------------------------------------------------------------------- # options['loggedMetrics']...
Generate the token substitution for metrics related fields. This includes: \$METRICS \$LOGGED_METRICS \$PERM_OPTIMIZE_SETTING
Below is the the instruction that describes the task: ### Input: Generate the token substitution for metrics related fields. This includes: \$METRICS \$LOGGED_METRICS \$PERM_OPTIMIZE_SETTING ### Response: def _generateMetricsSubstitutions(options, tokenReplacements): """Generate the token substitut...
def main(api_key, markup): '''Doing the regex parsing and running the create_html function.''' match = GIPHY.search(markup) attrs = None if match: attrs = dict( [(key, value.strip()) for (key, value) in match.groupdict().items() if value]) else: raise Valu...
Doing the regex parsing and running the create_html function.
Below is the the instruction that describes the task: ### Input: Doing the regex parsing and running the create_html function. ### Response: def main(api_key, markup): '''Doing the regex parsing and running the create_html function.''' match = GIPHY.search(markup) attrs = None if match: a...
def new_file(self, vd, length, isoname, parent, seqnum, rock_ridge, rr_name, xa, file_mode): # type: (headervd.PrimaryOrSupplementaryVD, int, bytes, DirectoryRecord, int, str, bytes, bool, int) -> None ''' Create a new file Directory Record. Parameters: vd - Th...
Create a new file Directory Record. Parameters: vd - The Volume Descriptor this record is part of. length - The length of the data. isoname - The name for this directory record. parent - The parent of this directory record. seqnum - The sequence number for this dire...
Below is the the instruction that describes the task: ### Input: Create a new file Directory Record. Parameters: vd - The Volume Descriptor this record is part of. length - The length of the data. isoname - The name for this directory record. parent - The parent of this ...
def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None): """Find vdwradii.dat and add special entries for lipids. See :data:`gromacs.setup.vdw_lipid_resnames` for lipid resnames. Add more if necessary. """ vdwradii_dat = os.path.join(outdir, "vdwradii.dat") if libdir is not None: fi...
Find vdwradii.dat and add special entries for lipids. See :data:`gromacs.setup.vdw_lipid_resnames` for lipid resnames. Add more if necessary.
Below is the the instruction that describes the task: ### Input: Find vdwradii.dat and add special entries for lipids. See :data:`gromacs.setup.vdw_lipid_resnames` for lipid resnames. Add more if necessary. ### Response: def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None): """Find vdwradii.dat ...
def adjustTitleFont(self): """ Adjusts the font used for the title based on the current with and \ display name. """ left, top, right, bottom = self.contentsMargins() r = self.roundingRadius() # include text padding left += 5 + r / 2 top +...
Adjusts the font used for the title based on the current with and \ display name.
Below is the the instruction that describes the task: ### Input: Adjusts the font used for the title based on the current with and \ display name. ### Response: def adjustTitleFont(self): """ Adjusts the font used for the title based on the current with and \ display name. "...
def freeze(self): """ Freeze (disable) all settings """ for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur, self.ys, self.nx, self.ny): for field in fields: field.disable() self.nquad.disable() self.xbin.disa...
Freeze (disable) all settings
Below is the the instruction that describes the task: ### Input: Freeze (disable) all settings ### Response: def freeze(self): """ Freeze (disable) all settings """ for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur, self.ys, self.nx, self.ny): ...
async def expand(self, request: Request, layer: BaseLayer): """ Expand a layer into a list of layers including the pauses. """ if isinstance(layer, lyr.RawText): t = self.reading_time(layer.text) yield layer yield lyr.Sleep(t) elif isinstance...
Expand a layer into a list of layers including the pauses.
Below is the the instruction that describes the task: ### Input: Expand a layer into a list of layers including the pauses. ### Response: async def expand(self, request: Request, layer: BaseLayer): """ Expand a layer into a list of layers including the pauses. """ if isinstance(lay...
def add_cloud_bt_task(self, source_url, save_path=None): '''从服务器上获取种子, 并建立离线下载任务 source_url - BT 种子在服务器上的绝对路径, 或者是磁链的地址. save_path - 要保存到的路径, 如果为None, 就会弹出目录选择的对话框 ''' def check_vcode(info, error=None): if error or not info: logger.error('CloudPage.c...
从服务器上获取种子, 并建立离线下载任务 source_url - BT 种子在服务器上的绝对路径, 或者是磁链的地址. save_path - 要保存到的路径, 如果为None, 就会弹出目录选择的对话框
Below is the the instruction that describes the task: ### Input: 从服务器上获取种子, 并建立离线下载任务 source_url - BT 种子在服务器上的绝对路径, 或者是磁链的地址. save_path - 要保存到的路径, 如果为None, 就会弹出目录选择的对话框 ### Response: def add_cloud_bt_task(self, source_url, save_path=None): '''从服务器上获取种子, 并建立离线下载任务 source_url - BT ...
def R_package_path(package): """ return the path to an installed R package """ local_sitelib = R_sitelib() rscript = Rscript_cmd() cmd = """{rscript} --no-environ -e '.libPaths(c("{local_sitelib}")); find.package("{package}")'""" try: output = subprocess.check_output(cmd.format(**loc...
return the path to an installed R package
Below is the the instruction that describes the task: ### Input: return the path to an installed R package ### Response: def R_package_path(package): """ return the path to an installed R package """ local_sitelib = R_sitelib() rscript = Rscript_cmd() cmd = """{rscript} --no-environ -e '.li...
def start(self): """Start performing the action.""" self.status = 'pending' self.thing.action_notify(self) self.perform_action() self.finish()
Start performing the action.
Below is the the instruction that describes the task: ### Input: Start performing the action. ### Response: def start(self): """Start performing the action.""" self.status = 'pending' self.thing.action_notify(self) self.perform_action() self.finish()
def read_init(key): """Parse the package __init__ file to find a variable so that it's not in multiple places. """ filename = os.path.join("traces", "__init__.py") result = None with open(filename) as stream: for line in stream: if key in line: result = line....
Parse the package __init__ file to find a variable so that it's not in multiple places.
Below is the the instruction that describes the task: ### Input: Parse the package __init__ file to find a variable so that it's not in multiple places. ### Response: def read_init(key): """Parse the package __init__ file to find a variable so that it's not in multiple places. """ filename = o...
def get_open_port() -> int: """ Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT """ free_socket = socket.s...
Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT
Below is the the instruction that describes the task: ### Input: Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT ### R...
def url_fix(s, charset='utf-8'): r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wi...
r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'ht...
Below is the the instruction that describes the task: ### Input: r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_...
def build_environ(self, sock_file, conn): """ Build the execution environment. """ # Grab the request line request = self.read_request_line(sock_file) # Copy the Base Environment environ = self.base_environ.copy() # Grab the headers for k, v in self.read_headers...
Build the execution environment.
Below is the the instruction that describes the task: ### Input: Build the execution environment. ### Response: def build_environ(self, sock_file, conn): """ Build the execution environment. """ # Grab the request line request = self.read_request_line(sock_file) # Copy the Base Env...
def percentile(a, q): """ Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> perc...
Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> percentile(a, [20, 80]) [2.0, 7.0]...
Below is the the instruction that describes the task: ### Input: Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> per...
def _split_symbol_mappings(df, exchanges): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_in...
Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_info : pd.DataFrame The asset info with one ...
Below is the the instruction that describes the task: ### Input: Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns -...
def from_bytes(value): """Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: ValueError: ...
Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: ValueError: If the value could not be conv...
Below is the the instruction that describes the task: ### Input: Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as uni...
def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_linkinfo = ET.Element("show_linkinfo") config = show_linkinfo output = ET.SubElement(show_linkinfo, "output") show_link_info = E...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_linkinfo = ET.Element("show_linkinfo") c...
def maxind_numba(block): """ filter for indels """ ## remove terminal edges inds = 0 for row in xrange(block.shape[0]): where = np.where(block[row] != 45)[0] if len(where) == 0: obs = 100 else: left = np.min(where) right = np.max(where) ...
filter for indels
Below is the the instruction that describes the task: ### Input: filter for indels ### Response: def maxind_numba(block): """ filter for indels """ ## remove terminal edges inds = 0 for row in xrange(block.shape[0]): where = np.where(block[row] != 45)[0] if len(where) == 0: ...
def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating option labels. """ return '%s %s' % (self.level_indicator * getattr(obj, obj._mptt_meta.level_attr), obj)
Creates labels which represent the tree level of each node when generating option labels.
Below is the the instruction that describes the task: ### Input: Creates labels which represent the tree level of each node when generating option labels. ### Response: def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating...
def _toVec(shape, val): ''' takes a single value and creates a vecotor / matrix with that value filled in it ''' mat = np.empty(shape) mat.fill(val) return mat
takes a single value and creates a vecotor / matrix with that value filled in it
Below is the the instruction that describes the task: ### Input: takes a single value and creates a vecotor / matrix with that value filled in it ### Response: def _toVec(shape, val): ''' takes a single value and creates a vecotor / matrix with that value filled in it ''' mat = np.emp...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'exclude') and self.exclude is not None: _dict['exclude'] = self.exclude if hasattr(self, 'include') and self.include is not None: _dict['include'] = self.inclu...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'exclude') and self.exclude is not None: _dict...
def snake_to_camel(snake_str): """ :param snake_str: string :return: string converted from a snake_case to a CamelCase """ components = snake_str.split('_') return ''.join(x.title() for x in components)
:param snake_str: string :return: string converted from a snake_case to a CamelCase
Below is the the instruction that describes the task: ### Input: :param snake_str: string :return: string converted from a snake_case to a CamelCase ### Response: def snake_to_camel(snake_str): """ :param snake_str: string :return: string converted from a snake_case to a CamelCase """ compo...
def exec_func_src3(func, globals_, sentinal=None, verbose=False, start=None, stop=None): """ execs a func and returns requested local vars. Does not modify globals unless update=True (or in IPython) SeeAlso: ut.execstr_funckw """ import utool as ut sourcecode = u...
execs a func and returns requested local vars. Does not modify globals unless update=True (or in IPython) SeeAlso: ut.execstr_funckw
Below is the the instruction that describes the task: ### Input: execs a func and returns requested local vars. Does not modify globals unless update=True (or in IPython) SeeAlso: ut.execstr_funckw ### Response: def exec_func_src3(func, globals_, sentinal=None, verbose=False, s...
def var_contains(var, value): ''' Verify if variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.var_contains 'LINGUAS' 'en' ''' setval = get_var(var) # Remove any escaping that was needed to past throu...
Verify if variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.var_contains 'LINGUAS' 'en'
Below is the the instruction that describes the task: ### Input: Verify if variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.var_contains 'LINGUAS' 'en' ### Response: def var_contains(var, value): ''' Verif...
def update_event_hub(self, hub_name, hub=None): ''' Updates an Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to retain the events for this...
Updates an Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to retain the events for this Event Hub.
Below is the the instruction that describes the task: ### Input: Updates an Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to retain the events for thi...
def OnUpView(self, event): """Request to move up the hierarchy to highest-weight parent""" node = self.activated_node parents = [] selected_parent = None if node: if hasattr( self.adapter, 'best_parent' ): selected_parent = self.adapter.best_p...
Request to move up the hierarchy to highest-weight parent
Below is the the instruction that describes the task: ### Input: Request to move up the hierarchy to highest-weight parent ### Response: def OnUpView(self, event): """Request to move up the hierarchy to highest-weight parent""" node = self.activated_node parents = [] selected_parent...
def operator_same_class(method): """ Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with. """ def wrapper(self, other): ...
Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with.
Below is the the instruction that describes the task: ### Input: Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with. ### Response: de...
def validate(self): """ validate: Makes sure node is valid Args: None Returns: boolean indicating if node is valid """ from .files import File assert self.source_id is not None, "Assumption Failed: Node must have a source_id" assert isinstance(self.title,...
validate: Makes sure node is valid Args: None Returns: boolean indicating if node is valid
Below is the the instruction that describes the task: ### Input: validate: Makes sure node is valid Args: None Returns: boolean indicating if node is valid ### Response: def validate(self): """ validate: Makes sure node is valid Args: None Returns: boolean in...
def MakeFITS(model, fitsfile=None): ''' Generate a FITS file for a given :py:mod:`everest` run. :param model: An :py:mod:`everest` model instance ''' # Get the fits file name if fitsfile is None: outfile = os.path.join(model.dir, model._mission.FITSFile( model.ID, model.se...
Generate a FITS file for a given :py:mod:`everest` run. :param model: An :py:mod:`everest` model instance
Below is the the instruction that describes the task: ### Input: Generate a FITS file for a given :py:mod:`everest` run. :param model: An :py:mod:`everest` model instance ### Response: def MakeFITS(model, fitsfile=None): ''' Generate a FITS file for a given :py:mod:`everest` run. :param model: An...
def merge_vcf_files(infiles, ref_seqs, outfile, threads=1): '''infiles: list of input VCF file to be merge. outfile: name of output VCF file. threads: number of input files to read in parallel''' vars_dict = vcf_file_read.vcf_files_to_dict_of_vars(infiles, ref_seqs, threads=threads) _dict_of_vars_to...
infiles: list of input VCF file to be merge. outfile: name of output VCF file. threads: number of input files to read in parallel
Below is the the instruction that describes the task: ### Input: infiles: list of input VCF file to be merge. outfile: name of output VCF file. threads: number of input files to read in parallel ### Response: def merge_vcf_files(infiles, ref_seqs, outfile, threads=1): '''infiles: list of input VCF file...
def from_file(self, fname): """read in a file and compute digest""" f = open(fname, "rb") data = f.read() self.update(data) f.close()
read in a file and compute digest
Below is the the instruction that describes the task: ### Input: read in a file and compute digest ### Response: def from_file(self, fname): """read in a file and compute digest""" f = open(fname, "rb") data = f.read() self.update(data) f.close()
def series_resistors(target, pore_area='pore.area', throat_area='throat.area', pore_thermal_conductivity='pore.thermal_conductivity', throat_thermal_conductivity='throat.thermal_conductivity', conduit_lengths='throa...
r""" Calculate the thermal conductance of conduits in network, where a conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated ar...
Below is the the instruction that describes the task: ### Input: r""" Calculate the thermal conductance of conduits in network, where a conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section. Parameters ---------- target : OpenPNM Object The object which this model is a...
def calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. ...
r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. ...
Below is the the instruction that describes the task: ### Input: r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. ...
def _pfp__build(self, stream=None, save_offset=False): """Build the String field :stream: TODO :returns: TODO """ if stream is not None and save_offset: self._pfp__offset = stream.tell() data = self._pfp__value + utils.binary("\x00") if stream is No...
Build the String field :stream: TODO :returns: TODO
Below is the the instruction that describes the task: ### Input: Build the String field :stream: TODO :returns: TODO ### Response: def _pfp__build(self, stream=None, save_offset=False): """Build the String field :stream: TODO :returns: TODO """ if stream i...
def _compute_edge_transforms(node_states, depth, num_transforms, name="transform"): """Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph...
Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total_value_d...
Below is the the instruction that describes the task: ### Input: Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_k...
def django(line): ''' >>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1...
>>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1 = django(input_line1) >>>...
Below is the the instruction that describes the task: ### Input: >>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "...
def custodian_archive(packages=None): """Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml policy: ...
Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml policy: name: lambda-archive-example re...
Below is the the instruction that describes the task: ### Input: Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml...
def read_wav(self, filename): """Read sample data for this sample from a WAV file. :param filename: the file from which to read """ wave_input = None try: wave_input = wave.open(filename, 'r') wave_frames = bytearray( wave_input.readframe...
Read sample data for this sample from a WAV file. :param filename: the file from which to read
Below is the the instruction that describes the task: ### Input: Read sample data for this sample from a WAV file. :param filename: the file from which to read ### Response: def read_wav(self, filename): """Read sample data for this sample from a WAV file. :param filename: the file from w...
def socket(self): """The running processes socket/port information (or None).""" return self._socket or self.read_metadata_by_name(self._name, 'socket', self._socket_type)
The running processes socket/port information (or None).
Below is the the instruction that describes the task: ### Input: The running processes socket/port information (or None). ### Response: def socket(self): """The running processes socket/port information (or None).""" return self._socket or self.read_metadata_by_name(self._name, 'socket', self._socket_type)
def createWidgets(self): """ Instantiate the Gooey Widgets that are used within the RadioGroup """ from gooey.gui.components import widgets return [getattr(widgets, item['type'])(self, item) for item in getin(self.widgetInfo, ['data', 'widgets'], [])]
Instantiate the Gooey Widgets that are used within the RadioGroup
Below is the the instruction that describes the task: ### Input: Instantiate the Gooey Widgets that are used within the RadioGroup ### Response: def createWidgets(self): """ Instantiate the Gooey Widgets that are used within the RadioGroup """ from gooey.gui.components import wi...
def smooth(self, noise, strategy=INVERSE_STRATEGY): """ In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: ...
In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment`
Below is the the instruction that describes the task: ### Input: In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns...
def is_contained_in(pe_pe, root): ''' Determine if a PE_PE is contained within a EP_PKG or a C_C. ''' if not pe_pe: return False if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() c_c = one(pe_pe).C_C[8003]() ...
Determine if a PE_PE is contained within a EP_PKG or a C_C.
Below is the the instruction that describes the task: ### Input: Determine if a PE_PE is contained within a EP_PKG or a C_C. ### Response: def is_contained_in(pe_pe, root): ''' Determine if a PE_PE is contained within a EP_PKG or a C_C. ''' if not pe_pe: return False if type(pe_pe)...
def run(self, command, opts): """Dispatch the given command & args.""" handlers = { 'create': self.create, 'delete': self.delete, 'list': self.list } handler = handlers.get(command, None) if handler is None: error("Unrecognized com...
Dispatch the given command & args.
Below is the the instruction that describes the task: ### Input: Dispatch the given command & args. ### Response: def run(self, command, opts): """Dispatch the given command & args.""" handlers = { 'create': self.create, 'delete': self.delete, 'list': self.list ...
def OpenEnumerateInstancePaths(self, ClassName, namespace=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None, **extra): # pylint: disable=inval...
Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. *New in pywbem 0.9.* This method performs the OpenEnumerateInstancePaths operation (see :term:`DSP0200`). See :ref:`WBEM operations` for a...
Below is the the instruction that describes the task: ### Input: Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. *New in pywbem 0.9.* This method performs the OpenEnumerateInstancePaths oper...
def get_serializer(self, node): """Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization. """ return self.options['serializers'].ge...
Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization.
Below is the the instruction that describes the task: ### Input: Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization. ### Response: def get_serialize...
def assert_pickle_idempotent(obj): '''Assert that obj does not change (w.r.t. ==) under repeated picklings ''' from six.moves.cPickle import dumps, loads obj1 = loads(dumps(obj)) obj2 = loads(dumps(obj1)) obj3 = loads(dumps(obj2)) assert_equivalent(obj, obj1) assert_equivalent(obj, obj2)...
Assert that obj does not change (w.r.t. ==) under repeated picklings
Below is the the instruction that describes the task: ### Input: Assert that obj does not change (w.r.t. ==) under repeated picklings ### Response: def assert_pickle_idempotent(obj): '''Assert that obj does not change (w.r.t. ==) under repeated picklings ''' from six.moves.cPickle import dumps, loads ...
def on_scopes_request(self, py_db, request): ''' Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request: ''' frame_id = request.arguments.frameId variables_reference = fra...
Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request:
Below is the the instruction that describes the task: ### Input: Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request: ### Response: def on_scopes_request(self, py_db, request): ''' Scopes ...
def validate_uses_tls_for_glance(audit_options): """Verify that TLS is used to communicate with Glance.""" section = _config_section(audit_options, 'glance') assert section is not None, "Missing section 'glance'" assert not section.get('insecure') and \ "https://" in section.get("api_servers"), ...
Verify that TLS is used to communicate with Glance.
Below is the the instruction that describes the task: ### Input: Verify that TLS is used to communicate with Glance. ### Response: def validate_uses_tls_for_glance(audit_options): """Verify that TLS is used to communicate with Glance.""" section = _config_section(audit_options, 'glance') assert section...
def generate_valid_keys(): """ create a list of valid keys """ valid_keys = [] for minimum, maximum in RANGES: for i in range(ord(minimum), ord(maximum) + 1): valid_keys.append(chr(i)) return valid_keys
create a list of valid keys
Below is the the instruction that describes the task: ### Input: create a list of valid keys ### Response: def generate_valid_keys(): """ create a list of valid keys """ valid_keys = [] for minimum, maximum in RANGES: for i in range(ord(minimum), ord(maximum) + 1): valid_keys.append...
def hideOverlay(self, ulOverlayHandle): """Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this.""" fn = self.function_table.hideOverlay result = fn(ulOverlayHandle) return result
Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this.
Below is the the instruction that describes the task: ### Input: Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this. ### Response: def hideOverlay(self, ulOverlayHandle): """Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed t...
def get_ctm(self): """Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. :returns: A new :class:`Matrix` obje...
Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. :returns: A new :class:`Matrix` object.
Below is the the instruction that describes the task: ### Input: Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. ...
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions t...
Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated.
Below is the the instruction that describes the task: ### Input: Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: E...
def _print_header(self): """Print the header for screen logging""" header = " Iter Dir " if self.constraints is not None: header += ' SC CC' header += " Function" if self.convergence_condition is not None: header += self.convergence_condition.ge...
Print the header for screen logging
Below is the the instruction that describes the task: ### Input: Print the header for screen logging ### Response: def _print_header(self): """Print the header for screen logging""" header = " Iter Dir " if self.constraints is not None: header += ' SC CC' header += " ...
def get_artifact_classpath_entries_for_targets(self, targets, respect_excludes=True): """Gets the artifact classpath products for the given targets. Products are returned in order, optionally respecting target excludes, and the products only include external artifact classpath elements (ie: resolved jars)....
Gets the artifact classpath products for the given targets. Products are returned in order, optionally respecting target excludes, and the products only include external artifact classpath elements (ie: resolved jars). :param targets: The targets to lookup classpath products for. :param bool respect_e...
Below is the the instruction that describes the task: ### Input: Gets the artifact classpath products for the given targets. Products are returned in order, optionally respecting target excludes, and the products only include external artifact classpath elements (ie: resolved jars). :param targets: Th...
def _build_archive(self, dir_path): """ Creates a zip archive from files in path. """ zip_path = os.path.join(dir_path, "import.zip") archive = zipfile.ZipFile(zip_path, "w") for filename in CSV_FILES: filepath = os.path.join(dir_path, filename) ...
Creates a zip archive from files in path.
Below is the the instruction that describes the task: ### Input: Creates a zip archive from files in path. ### Response: def _build_archive(self, dir_path): """ Creates a zip archive from files in path. """ zip_path = os.path.join(dir_path, "import.zip") archive = zipfile.Zi...
def checksum_status(self, area_uuid, filename): """ Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information ...
Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information coul...
Below is the the instruction that describes the task: ### Input: Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information ...
def fit(self, SF, x_range, y_range, matrix_z): ''' #================================================= /the main fitting process /xx,yy,zz = Hb,Ha,p /p is the FORC distribution /m0,n0 is the index of values on Ha = Hb /then loop m0 and n0 /based on smooth f...
#================================================= /the main fitting process /xx,yy,zz = Hb,Ha,p /p is the FORC distribution /m0,n0 is the index of values on Ha = Hb /then loop m0 and n0 /based on smooth factor(SF) /select data grid from the matrix_z for curve fit...
Below is the the instruction that describes the task: ### Input: #================================================= /the main fitting process /xx,yy,zz = Hb,Ha,p /p is the FORC distribution /m0,n0 is the index of values on Ha = Hb /then loop m0 and n0 /based on smooth...
def trans_from_matrix(matrix): """ Convert a vtk matrix to a numpy.ndarray """ t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
Convert a vtk matrix to a numpy.ndarray
Below is the the instruction that describes the task: ### Input: Convert a vtk matrix to a numpy.ndarray ### Response: def trans_from_matrix(matrix): """ Convert a vtk matrix to a numpy.ndarray """ t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElemen...
def colorbar(self, mappable=None, **kwargs): """Add a `~matplotlib.colorbar.Colorbar` to these `Axes` Parameters ---------- mappable : matplotlib data collection, optional collection against which to map the colouring, default will be the last added mappable arti...
Add a `~matplotlib.colorbar.Colorbar` to these `Axes` Parameters ---------- mappable : matplotlib data collection, optional collection against which to map the colouring, default will be the last added mappable artist (collection or image) fraction : `float`, op...
Below is the the instruction that describes the task: ### Input: Add a `~matplotlib.colorbar.Colorbar` to these `Axes` Parameters ---------- mappable : matplotlib data collection, optional collection against which to map the colouring, default will be the last added ...
def _pop_buffer_and_writer(self): """pop the most recent capturing buffer from this Context and return the current writer after the pop. """ buf = self._buffer_stack.pop() return buf, self._buffer_stack[-1].write
pop the most recent capturing buffer from this Context and return the current writer after the pop.
Below is the the instruction that describes the task: ### Input: pop the most recent capturing buffer from this Context and return the current writer after the pop. ### Response: def _pop_buffer_and_writer(self): """pop the most recent capturing buffer from this Context and return the curre...
def _get_events(self): """ Fetches events from the calendar into a list. Returns: The list of events. """ self.last_update = datetime.datetime.now() time_min = datetime.datetime.utcnow() time_max = time_min + datetime.timedelta(hours=self.events_within_hours) ...
Fetches events from the calendar into a list. Returns: The list of events.
Below is the the instruction that describes the task: ### Input: Fetches events from the calendar into a list. Returns: The list of events. ### Response: def _get_events(self): """ Fetches events from the calendar into a list. Returns: The list of events. """ self....
def lookup_domain(self, domain, nameserver=None, log_prefix=''): """Most basic DNS primitive that looks up a domain, waits for a second response, then returns all of the results :param domain: the domain to lookup :param nameserver: the nameserver to use :param log_prefix: ...
Most basic DNS primitive that looks up a domain, waits for a second response, then returns all of the results :param domain: the domain to lookup :param nameserver: the nameserver to use :param log_prefix: :return: Note: if you want to lookup multiple domains you *shoul...
Below is the the instruction that describes the task: ### Input: Most basic DNS primitive that looks up a domain, waits for a second response, then returns all of the results :param domain: the domain to lookup :param nameserver: the nameserver to use :param log_prefix: :ret...
def _get_all_tables(self, dataset_id, cache=False, project_id=None): """Retrieve the list of tables for dataset, that respect the formats: * appid_YYYY_MM * YYYY_MM_appid Parameters ---------- dataset_id : str The dataset to retrieve table names for ...
Retrieve the list of tables for dataset, that respect the formats: * appid_YYYY_MM * YYYY_MM_appid Parameters ---------- dataset_id : str The dataset to retrieve table names for cache : bool, optional To use cached value or not (de...
Below is the the instruction that describes the task: ### Input: Retrieve the list of tables for dataset, that respect the formats: * appid_YYYY_MM * YYYY_MM_appid Parameters ---------- dataset_id : str The dataset to retrieve table names for ...
def del_node(self, node): """ Delete a given node from the hypergraph. @type node: node @param node: Node identifier. """ if self.has_node(node): for e in self.node_links[node]: self.edge_links[e].remove(node) self.node_l...
Delete a given node from the hypergraph. @type node: node @param node: Node identifier.
Below is the the instruction that describes the task: ### Input: Delete a given node from the hypergraph. @type node: node @param node: Node identifier. ### Response: def del_node(self, node): """ Delete a given node from the hypergraph. @type node: node ...
def parse_name(name): """ Split a query name into field name, operator and whether it is inverted. """ inverted, op = False, OP_EQ if name is not None: for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE): if name.endswith(op_): op = op_ name = name[:len(name) ...
Split a query name into field name, operator and whether it is inverted.
Below is the the instruction that describes the task: ### Input: Split a query name into field name, operator and whether it is inverted. ### Response: def parse_name(name): """ Split a query name into field name, operator and whether it is inverted. """ inverted, op = False, OP_EQ if name is n...
def is_tp(self, atol=None, rtol=None): """Test if a channel is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(choi, atol, rtol)
Test if a channel is completely-positive (CP)
Below is the the instruction that describes the task: ### Input: Test if a channel is completely-positive (CP) ### Response: def is_tp(self, atol=None, rtol=None): """Test if a channel is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(...
def prob_imf(m1, m2, s1z, s2z, **kwargs): ''' Return probability density for power-law Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1(Not in use currently) s2z: ...
Return probability density for power-law Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1(Not in use currently) s2z: Aligned spin 2(Not in use currently) **kwa...
Below is the the instruction that describes the task: ### Input: Return probability density for power-law Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1(Not in use currently) ...
def RunStateMethod(self, method_name, request=None, responses=None, event=None, direct_response=None): """Completes the request by calling the state method. Args: method_name: The name of the state me...
Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of GrrMessages responding to the request. event: A threading.Event() instance to signal completion of this request. direct_re...
Below is the the instruction that describes the task: ### Input: Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of GrrMessages responding to the request. event: A threading.E...
def _utc_datetime_to_epoch(self, activity_datetime): """ Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be co...
Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be considered to be UTC). :return: Epoch timestamp. :rtype: in...
Below is the the instruction that describes the task: ### Input: Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be consid...
def get_request_headers(self, *args, **kwds): """ A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications. """ ...
A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications.
Below is the the instruction that describes the task: ### Input: A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications. ### Respons...
def add_cli_options(cli_options, action): # type: (dict, str) -> None """Adds CLI options to the configuration object :param dict cli_options: CLI options dict :param TransferAction action: action """ cli_options['_action'] = action.name.lower() # if url is present, convert to constituent op...
Adds CLI options to the configuration object :param dict cli_options: CLI options dict :param TransferAction action: action
Below is the the instruction that describes the task: ### Input: Adds CLI options to the configuration object :param dict cli_options: CLI options dict :param TransferAction action: action ### Response: def add_cli_options(cli_options, action): # type: (dict, str) -> None """Adds CLI options to the...
def add_remote(name, location): ''' Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_...
Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_flathub: flatpack.add_remote: ...
Below is the the instruction that describes the task: ### Input: Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-b...
def cur_space(self, name=None): """Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned. """ if name is None: ...
Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned.
Below is the the instruction that describes the task: ### Input: Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned. ### Response: def c...
def add_prerequisite(self, prerequisite): """Adds prerequisites""" if self.prerequisites is None: self.prerequisites = SCons.Util.UniqueList() self.prerequisites.extend(prerequisite) self._children_reset()
Adds prerequisites
Below is the the instruction that describes the task: ### Input: Adds prerequisites ### Response: def add_prerequisite(self, prerequisite): """Adds prerequisites""" if self.prerequisites is None: self.prerequisites = SCons.Util.UniqueList() self.prerequisites.extend(prerequisite...