code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def getsuffix(subject): """ Returns the suffix of a filename. If the file has no suffix, returns None. Can return an empty string if the filenam ends with a period. """ index = subject.rfind('.') if index > subject.replace('\\', '/').rfind('/'): return subject[index+1:] return None
Returns the suffix of a filename. If the file has no suffix, returns None. Can return an empty string if the filenam ends with a period.
Below is the the instruction that describes the task: ### Input: Returns the suffix of a filename. If the file has no suffix, returns None. Can return an empty string if the filenam ends with a period. ### Response: def getsuffix(subject): """ Returns the suffix of a filename. If the file has no suffix, retu...
def add_variable(self, node): """Add a variable node to this node. :sig: (VariableNode) -> None :param node: Variable node to add. """ if node.name not in self.variable_names: self.variables.append(node) self.variable_names.add(node.name) node...
Add a variable node to this node. :sig: (VariableNode) -> None :param node: Variable node to add.
Below is the the instruction that describes the task: ### Input: Add a variable node to this node. :sig: (VariableNode) -> None :param node: Variable node to add. ### Response: def add_variable(self, node): """Add a variable node to this node. :sig: (VariableNode) -> None ...
def get_formats( self, token: dict = None, format_code: str = None, prot: str = "https" ) -> dict: """Get formats. :param str token: API auth token :param str format_code: code of a specific format :param str prot: https [DEFAULT] or http (use it only for dev and tr...
Get formats. :param str token: API auth token :param str format_code: code of a specific format :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs).
Below is the the instruction that describes the task: ### Input: Get formats. :param str token: API auth token :param str format_code: code of a specific format :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). ### Response: def get_formats( ...
def variants(institute_id, case_name): """Display a list of SNV variants.""" page = int(request.form.get('page', 1)) institute_obj, case_obj = institute_and_case(store, institute_id, case_name) variant_type = request.args.get('variant_type', 'clinical') # Update filter settings if Clinical Filter ...
Display a list of SNV variants.
Below is the the instruction that describes the task: ### Input: Display a list of SNV variants. ### Response: def variants(institute_id, case_name): """Display a list of SNV variants.""" page = int(request.form.get('page', 1)) institute_obj, case_obj = institute_and_case(store, institute_id, case_nam...
def _expand_authorized_keys_path(path, user, home): ''' Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) ''' converted_path = '' had_escape = False for char in path: if had_escape: had_escape = False if char == '%': converted...
Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5)
Below is the the instruction that describes the task: ### Input: Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) ### Response: def _expand_authorized_keys_path(path, user, home): ''' Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) ''' converted_path =...
def spliced_offset(self, position): """ Convert from an absolute chromosomal position to the offset into this transcript"s spliced mRNA. Position must be inside some exon (otherwise raise exception). """ # this code is performance sensitive, so switching from # t...
Convert from an absolute chromosomal position to the offset into this transcript"s spliced mRNA. Position must be inside some exon (otherwise raise exception).
Below is the the instruction that describes the task: ### Input: Convert from an absolute chromosomal position to the offset into this transcript"s spliced mRNA. Position must be inside some exon (otherwise raise exception). ### Response: def spliced_offset(self, position): """ Con...
def GET(self): # pylint: disable=arguments-differ """ Display main course list page """ if not self.app.welcome_page: raise web.seeother("/courselist") return self.show_page(self.app.welcome_page)
Display main course list page
Below is the the instruction that describes the task: ### Input: Display main course list page ### Response: def GET(self): # pylint: disable=arguments-differ """ Display main course list page """ if not self.app.welcome_page: raise web.seeother("/courselist") return self.show_...
def info(cwd, targets=None, user=None, username=None, password=None, fmt='str'): ''' Display the Subversion information from the checkout. cwd The path to the Subversion repository targets : None files, directories, and URLs to pass to the c...
Display the Subversion information from the checkout. cwd The path to the Subversion repository targets : None files, directories, and URLs to pass to the command as arguments svn uses '.' by default user : None Run svn as a user other than what the minion runs as use...
Below is the the instruction that describes the task: ### Input: Display the Subversion information from the checkout. cwd The path to the Subversion repository targets : None files, directories, and URLs to pass to the command as arguments svn uses '.' by default user : None ...
def login(self): ''' user login. ''' post_data = self.get_post_data() if 'next' in post_data: next_url = post_data['next'] else: next_url = '/' u_name = post_data['user_name'] u_pass = post_data['user_pass'] result = MUse...
user login.
Below is the the instruction that describes the task: ### Input: user login. ### Response: def login(self): ''' user login. ''' post_data = self.get_post_data() if 'next' in post_data: next_url = post_data['next'] else: next_url = '/' ...
def _crc32(self, ch, crc): """Compute the CRC32 primitive on one byte.""" return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
Compute the CRC32 primitive on one byte.
Below is the the instruction that describes the task: ### Input: Compute the CRC32 primitive on one byte. ### Response: def _crc32(self, ch, crc): """Compute the CRC32 primitive on one byte.""" return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
def datatable_df(self): """ returns the dataframe representation of the symbol's final data """ data = self._all_datatable_data() adf = pd.DataFrame(data) adf.columns = self.dt_all_cols return self._finish_df(adf, 'ALL')
returns the dataframe representation of the symbol's final data
Below is the the instruction that describes the task: ### Input: returns the dataframe representation of the symbol's final data ### Response: def datatable_df(self): """ returns the dataframe representation of the symbol's final data """ data = self._all_datatable_data() adf = pd.DataFr...
def set_chat_title(chat_id, title, **kwargs): """ Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. :param chat_id: Unique identifier for the target chat or ...
Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channeluser...
Below is the the instruction that describes the task: ### Input: Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. :param chat_id: Unique identifier for the targ...
def parse_output(self, s): ''' Example output: AVR Memory Usage ---------------- Device: atmega2561 Program: 4168 bytes (1.6% Full) (.text + .data + .bootloader) Data: 72 bytes (0.9% Full) (.data + .bss + .noinit) ''' ...
Example output: AVR Memory Usage ---------------- Device: atmega2561 Program: 4168 bytes (1.6% Full) (.text + .data + .bootloader) Data: 72 bytes (0.9% Full) (.data + .bss + .noinit)
Below is the the instruction that describes the task: ### Input: Example output: AVR Memory Usage ---------------- Device: atmega2561 Program: 4168 bytes (1.6% Full) (.text + .data + .bootloader) Data: 72 bytes (0.9% Full) (.data + .bss + .noinit...
def interruptwait(): """ If waituntil() has been called, this will interrupt the waiting process so it can check whether it should stop waiting. """ evt = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, NSPoint(), NSApplicat...
If waituntil() has been called, this will interrupt the waiting process so it can check whether it should stop waiting.
Below is the the instruction that describes the task: ### Input: If waituntil() has been called, this will interrupt the waiting process so it can check whether it should stop waiting. ### Response: def interruptwait(): """ If waituntil() has been called, this will interrupt the waiting process so ...
def expose_ancestors_or_children(self, member, collection, lang=None): """ Build an ancestor or descendant dict view based on selected information :param member: Current Member to build for :param collection: Collection from which we retrieved it :param lang: Language to express data in...
Build an ancestor or descendant dict view based on selected information :param member: Current Member to build for :param collection: Collection from which we retrieved it :param lang: Language to express data in :return:
Below is the the instruction that describes the task: ### Input: Build an ancestor or descendant dict view based on selected information :param member: Current Member to build for :param collection: Collection from which we retrieved it :param lang: Language to express data in :retu...
def update_hard_unknown_phase_state(self): """Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important, and they should not raise notif about it :return: None """ self.was_in_hard_unknown_r...
Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important, and they should not raise notif about it :return: None
Below is the the instruction that describes the task: ### Input: Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important, and they should not raise notif about it :return: None ### Response: def update_hard_...
def _get_table_with_column_changes(self, blueprint, table): """ Get a copy of the given table after making the column changes. :param blueprint: The blueprint :type blueprint: Blueprint :type table: orator.dbal.table.Table :rtype: orator.dbal.table.Table """ ...
Get a copy of the given table after making the column changes. :param blueprint: The blueprint :type blueprint: Blueprint :type table: orator.dbal.table.Table :rtype: orator.dbal.table.Table
Below is the the instruction that describes the task: ### Input: Get a copy of the given table after making the column changes. :param blueprint: The blueprint :type blueprint: Blueprint :type table: orator.dbal.table.Table :rtype: orator.dbal.table.Table ### Response: def _get_t...
def uniquify(model): ''' Remove all duplicate relationships ''' seen = set() to_remove = set() for ix, (o, r, t, a) in model: hashable_link = (o, r, t) + tuple(sorted(a.items())) #print(hashable_link) if hashable_link in seen: to_remove.add(ix) seen.ad...
Remove all duplicate relationships
Below is the the instruction that describes the task: ### Input: Remove all duplicate relationships ### Response: def uniquify(model): ''' Remove all duplicate relationships ''' seen = set() to_remove = set() for ix, (o, r, t, a) in model: hashable_link = (o, r, t) + tuple(sorted(a....
def upload(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs): """ This method uploads a local file to the SAS servers file system. localfile - path to the local file to upload remotefile - path to remote file to create or overwrite overwrite ...
This method uploads a local file to the SAS servers file system. localfile - path to the local file to upload remotefile - path to remote file to create or overwrite overwrite - overwrite the output file if it exists? permission - permissions to set on the new file. See SAS Filename Statement...
Below is the the instruction that describes the task: ### Input: This method uploads a local file to the SAS servers file system. localfile - path to the local file to upload remotefile - path to remote file to create or overwrite overwrite - overwrite the output file if it exists? permis...
def models(self): """Return self.application models.""" Model_ = self.app.config['PEEWEE_MODELS_CLASS'] ignore = self.app.config['PEEWEE_MODELS_IGNORE'] models = [] if Model_ is not Model: try: mod = import_module(self.app.config['PEEWEE_MODELS_MODULE...
Return self.application models.
Below is the the instruction that describes the task: ### Input: Return self.application models. ### Response: def models(self): """Return self.application models.""" Model_ = self.app.config['PEEWEE_MODELS_CLASS'] ignore = self.app.config['PEEWEE_MODELS_IGNORE'] models = [] ...
def output(data, **kwargs): # pylint: disable=unused-argument ''' Read in the dict structure generated by the salt key API methods and print the structure. ''' color = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) strip_colors = __opts_...
Read in the dict structure generated by the salt key API methods and print the structure.
Below is the the instruction that describes the task: ### Input: Read in the dict structure generated by the salt key API methods and print the structure. ### Response: def output(data, **kwargs): # pylint: disable=unused-argument ''' Read in the dict structure generated by the salt key API methods an...
def insert(self, tname, record=None, columns=None, astype=None): ''' Inserts record into the provided table from the database. Returns inserted record as list, str or series depending on the value of `astype`. Parameters ---------- tname : str Table to insert...
Inserts record into the provided table from the database. Returns inserted record as list, str or series depending on the value of `astype`. Parameters ---------- tname : str Table to insert records into. where : dict or None (default `None`) Dictionary o...
Below is the the instruction that describes the task: ### Input: Inserts record into the provided table from the database. Returns inserted record as list, str or series depending on the value of `astype`. Parameters ---------- tname : str Table to insert records into. ...
def detect_blob(self, img, filters): """ "filters" must be something similar to: filters = { 'R': (150, 255), # (min, max) 'S': (150, 255), } """ acc_mask = ones(img.shape[:2], dtype=uint8) * 255 rgb = img.copy() ...
"filters" must be something similar to: filters = { 'R': (150, 255), # (min, max) 'S': (150, 255), }
Below is the the instruction that describes the task: ### Input: "filters" must be something similar to: filters = { 'R': (150, 255), # (min, max) 'S': (150, 255), } ### Response: def detect_blob(self, img, filters): """ "filters" must be ...
def configure(self, options, conf): """ Configures the plugin. """ super(EverestNosePlugin, self).configure(options, conf) opt_val = getattr(options, self.__dest_opt_name, None) if opt_val: self.enabled = True EverestIni.ini_file_path = opt_val
Configures the plugin.
Below is the the instruction that describes the task: ### Input: Configures the plugin. ### Response: def configure(self, options, conf): """ Configures the plugin. """ super(EverestNosePlugin, self).configure(options, conf) opt_val = getattr(options, self.__dest_opt_name, N...
def set_user_avatar(self, username, avatar): """Set a user's avatar. :param username: the user to set the avatar for :param avatar: ID of the avatar to set """ self._set_avatar( {'username': username}, self._get_url('user/avatar'), avatar)
Set a user's avatar. :param username: the user to set the avatar for :param avatar: ID of the avatar to set
Below is the the instruction that describes the task: ### Input: Set a user's avatar. :param username: the user to set the avatar for :param avatar: ID of the avatar to set ### Response: def set_user_avatar(self, username, avatar): """Set a user's avatar. :param username: the user...
def poller_tasker_handler(event, context): # pylint: disable=W0613 """ Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contai...
Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector...
Below is the the instruction that describes the task: ### Input: Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configura...
def next(self): """Returns next error checking strategy.""" # Where this link is in the chain: location = self.chain.index(self) if not self.end(): return self.chain[location + 1]
Returns next error checking strategy.
Below is the the instruction that describes the task: ### Input: Returns next error checking strategy. ### Response: def next(self): """Returns next error checking strategy.""" # Where this link is in the chain: location = self.chain.index(self) if not self.end(): return...
def tag_add(self, item, tag): """ Add tag to the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str """ tags = self.item(item, "tags") self.item(item, tags=tags + (tag,))
Add tag to the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str
Below is the the instruction that describes the task: ### Input: Add tag to the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str ### Response: def tag_add(self, item, tag): """ Add tag to the tags of item. ...
def finish_commit(self, commit): """ Ends the process of committing data to a Repo and persists the Commit. Once a Commit is finished the data becomes immutable and future attempts to write to it with PutFile will error. Params: * commit: A tuple, string, or Commit objec...
Ends the process of committing data to a Repo and persists the Commit. Once a Commit is finished the data becomes immutable and future attempts to write to it with PutFile will error. Params: * commit: A tuple, string, or Commit object representing the commit.
Below is the the instruction that describes the task: ### Input: Ends the process of committing data to a Repo and persists the Commit. Once a Commit is finished the data becomes immutable and future attempts to write to it with PutFile will error. Params: * commit: A tuple, string,...
def set_args(self, **kwargs): """ Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value """ try: kwargs_items = kwargs.iteritems() except AttributeError: kwargs_items = kwargs...
Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value
Below is the the instruction that describes the task: ### Input: Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value ### Response: def set_args(self, **kwargs): """ Set more arguments to self.args args: ...
def heartbeat_callback(self, session=None): """Self destruct task if state has been moved away from running externally""" if self.terminating: # ensure termination if processes are created later self.task_runner.terminate() return self.task_instance.refresh_...
Self destruct task if state has been moved away from running externally
Below is the the instruction that describes the task: ### Input: Self destruct task if state has been moved away from running externally ### Response: def heartbeat_callback(self, session=None): """Self destruct task if state has been moved away from running externally""" if self.terminating: ...
def downsample_with_averaging(array, factor): """Downsample x by factor using averaging. @return: The downsampled array, of the same type as x. """ factor = tuple(factor) output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor)) temp = np.zeros(output_shape, dtype=np.floa...
Downsample x by factor using averaging. @return: The downsampled array, of the same type as x.
Below is the the instruction that describes the task: ### Input: Downsample x by factor using averaging. @return: The downsampled array, of the same type as x. ### Response: def downsample_with_averaging(array, factor): """Downsample x by factor using averaging. @return: The downsampled array, of the...
def normalize_encoding(encoding, default=DEFAULT_ENCODING): """Normalize the encoding name, replace ASCII w/ UTF-8.""" if encoding is None: return default encoding = encoding.lower().strip() if encoding in ['', 'ascii']: return default try: codecs.lookup(encoding) ret...
Normalize the encoding name, replace ASCII w/ UTF-8.
Below is the the instruction that describes the task: ### Input: Normalize the encoding name, replace ASCII w/ UTF-8. ### Response: def normalize_encoding(encoding, default=DEFAULT_ENCODING): """Normalize the encoding name, replace ASCII w/ UTF-8.""" if encoding is None: return default encoding...
def getSCDPURL(self, serviceType, default=None): """Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace th...
Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace the associated URL to the SCDP. If the device definitions ...
Below is the the instruction that describes the task: ### Input: Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/nam...
def create_app(): """ Flask application factory """ # Create Flask app load app.config app = Flask(__name__) app.config.from_object(__name__+'.ConfigClass') # Initialize Flask-SQLAlchemy db = SQLAlchemy(app) # Define the User data-model. # NB: Make sure to add flask_user UserMixin...
Flask application factory
Below is the the instruction that describes the task: ### Input: Flask application factory ### Response: def create_app(): """ Flask application factory """ # Create Flask app load app.config app = Flask(__name__) app.config.from_object(__name__+'.ConfigClass') # Initialize Flask-SQLAlche...
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` ...
Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
Below is the the instruction that describes the task: ### Input: Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input a...
def fasta_from_biom(table, fasta_file_name): '''Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file ''' logger = logging.getLogger(__name__) ...
Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file
Below is the the instruction that describes the task: ### Input: Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file ### Response: def fasta_from_biom(t...
def make_idx(f, lb, ub): """ This is a little utility function to replace an oft-called set of operations Parameters ---------- f : 1d array A frequency axis along which we want to slice lb : float Defines the upper bound of slicing ub : float Defines the ...
This is a little utility function to replace an oft-called set of operations Parameters ---------- f : 1d array A frequency axis along which we want to slice lb : float Defines the upper bound of slicing ub : float Defines the lower bound of slicing Returns ...
Below is the the instruction that describes the task: ### Input: This is a little utility function to replace an oft-called set of operations Parameters ---------- f : 1d array A frequency axis along which we want to slice lb : float Defines the upper bound of slicing ...
def add_for_targets(self, targets, classpath_elements): """Adds classpath path elements to the products of all the provided targets.""" for target in targets: self.add_for_target(target, classpath_elements)
Adds classpath path elements to the products of all the provided targets.
Below is the the instruction that describes the task: ### Input: Adds classpath path elements to the products of all the provided targets. ### Response: def add_for_targets(self, targets, classpath_elements): """Adds classpath path elements to the products of all the provided targets.""" for target in targ...
def set_image(self, text): """ Save image resource at `text` (path or url) to storage, then return the replacement string and the necessary exercicse image file object. Args: - text (str): path or url to parse as an exercise image resource Returns: (new_text, files) ...
Save image resource at `text` (path or url) to storage, then return the replacement string and the necessary exercicse image file object. Args: - text (str): path or url to parse as an exercise image resource Returns: (new_text, files) - `new_text` (str): replacement string f...
Below is the the instruction that describes the task: ### Input: Save image resource at `text` (path or url) to storage, then return the replacement string and the necessary exercicse image file object. Args: - text (str): path or url to parse as an exercise image resource Returns:...
def get_genus_type(self): """Gets the genus type of this object. return: (osid.type.Type) - the genus type of this object *compliance: mandatory -- This method must be implemented.* """ try: # Try to stand up full Type objects if they can be found # (Als...
Gets the genus type of this object. return: (osid.type.Type) - the genus type of this object *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the genus type of this object. return: (osid.type.Type) - the genus type of this object *compliance: mandatory -- This method must be implemented.* ### Response: def get_genus_type(self): """Gets the genus type of this o...
def digest(self): """Return final digest value. """ if self._digest is None: if self._buf: self._add_block(self._buf) self._buf = EMPTY ctx = self._blake2s(0, 1, True) for t in self._thread: ctx.update(t.digest()...
Return final digest value.
Below is the the instruction that describes the task: ### Input: Return final digest value. ### Response: def digest(self): """Return final digest value. """ if self._digest is None: if self._buf: self._add_block(self._buf) self._buf = EMPTY ...
def value(self, t): """See Schedule.value""" for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]): if l_t <= t and t < r_t: alpha = float(t - l_t) / (r_t - l_t) return self._interpolation(l, r, alpha) # t does not belong to any of ...
See Schedule.value
Below is the the instruction that describes the task: ### Input: See Schedule.value ### Response: def value(self, t): """See Schedule.value""" for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]): if l_t <= t and t < r_t: alpha = float(t - l_t) / (r_t...
def lower(self, lowering): """Lower the ReshapeOperation. Reshaping can require collective communication between processors. We haven't yet implemented all possible reshapes. We try to handle the common cases here - otherwise we raise a NotImplementedError. Args: lowering: a Lowering Ra...
Lower the ReshapeOperation. Reshaping can require collective communication between processors. We haven't yet implemented all possible reshapes. We try to handle the common cases here - otherwise we raise a NotImplementedError. Args: lowering: a Lowering Raises: NotImplementedError: i...
Below is the the instruction that describes the task: ### Input: Lower the ReshapeOperation. Reshaping can require collective communication between processors. We haven't yet implemented all possible reshapes. We try to handle the common cases here - otherwise we raise a NotImplementedError. Args...
def draw_layer(ax, layer): """Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot """ ax.set_aspect('equal', 'datalim') ax.plot(*layer) ax.axis('off')
Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot
Below is the the instruction that describes the task: ### Input: Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot ### Response: def draw_layer(ax, layer): """Draws a layer on the given matplotlib axis. Args: ...
def tke(u, v, w, perturbation=False, axis=-1): r"""Compute turbulence kinetic energy. Compute the turbulence kinetic energy (e) from the time series of the velocity components. Parameters ---------- u : array_like The wind component along the x-axis v : array_like The wind ...
r"""Compute turbulence kinetic energy. Compute the turbulence kinetic energy (e) from the time series of the velocity components. Parameters ---------- u : array_like The wind component along the x-axis v : array_like The wind component along the y-axis w : array_like ...
Below is the the instruction that describes the task: ### Input: r"""Compute turbulence kinetic energy. Compute the turbulence kinetic energy (e) from the time series of the velocity components. Parameters ---------- u : array_like The wind component along the x-axis v : array_like...
def config(self, show_row_hdrs=True, show_col_hdrs=True, show_col_hdr_in_cell=False, auto_resize=True): """ Override the in-class params: @param show_row_hdrs : show row headers @param show_col_hdrs : show column headers @param show_col_hdr_in_cell : embed column...
Override the in-class params: @param show_row_hdrs : show row headers @param show_col_hdrs : show column headers @param show_col_hdr_in_cell : embed column header in each cell @param auto_resize : auto resize according to the size of terminal
Below is the the instruction that describes the task: ### Input: Override the in-class params: @param show_row_hdrs : show row headers @param show_col_hdrs : show column headers @param show_col_hdr_in_cell : embed column header in each cell @param auto_resize : auto resize according...
def _post(self, url, data={}, **kwargs): """Wrapper around request.post() to use the API prefix. Returns a JSON response.""" if 'files' in kwargs: req = self._session.post(self._api_prefix + url, auth=self._session.auth, data=data, **kwargs) return self._action(req) req ...
Wrapper around request.post() to use the API prefix. Returns a JSON response.
Below is the the instruction that describes the task: ### Input: Wrapper around request.post() to use the API prefix. Returns a JSON response. ### Response: def _post(self, url, data={}, **kwargs): """Wrapper around request.post() to use the API prefix. Returns a JSON response.""" if 'files' in kwa...
def create_objective(dist, abscissas): """Create objective function.""" abscissas_ = numpy.array(abscissas[1:-1]) def obj(absisa): """Local objective function.""" out = -numpy.sqrt(dist.pdf(absisa)) out *= numpy.prod(numpy.abs(abscissas_ - absisa)) return out return obj
Create objective function.
Below is the the instruction that describes the task: ### Input: Create objective function. ### Response: def create_objective(dist, abscissas): """Create objective function.""" abscissas_ = numpy.array(abscissas[1:-1]) def obj(absisa): """Local objective function.""" out = -numpy.sqrt(...
def RegisterAt(cls, *args, **kwargs): """ **RegisterAt** RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None) Most of the time you don't want to register an method as such, that is, you don't car...
**RegisterAt** RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None) Most of the time you don't want to register an method as such, that is, you don't care about the `self` builder object, instead you wan...
Below is the the instruction that describes the task: ### Input: **RegisterAt** RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None) Most of the time you don't want to register an method as such, tha...
def action_stats(self, hostname=None): "Shows stats (possibly limited by hostname)" format = "%-35s %-11s %-11s %-11s %-11s" print format % ("HOST", "OPEN", "COMPLETED", "BYTES IN", "BYTES OUT") for host, details in sorted(self.client.stats(hostname).items()): print format % ...
Shows stats (possibly limited by hostname)
Below is the the instruction that describes the task: ### Input: Shows stats (possibly limited by hostname) ### Response: def action_stats(self, hostname=None): "Shows stats (possibly limited by hostname)" format = "%-35s %-11s %-11s %-11s %-11s" print format % ("HOST", "OPEN", "COMPLETED",...
def main_loop(args): '''main loop logic for trial keeper''' if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) stdout_file = open(STDOUT_FULL_PATH, 'a+') stderr_file = open(STDERR_FULL_PATH, 'a+') trial_keeper_syslogger = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'tr...
main loop logic for trial keeper
Below is the the instruction that describes the task: ### Input: main loop logic for trial keeper ### Response: def main_loop(args): '''main loop logic for trial keeper''' if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) stdout_file = open(STDOUT_FULL_PATH, 'a+') stderr_file =...
def parse_geometry(ml_log, log=None, ml_version='2016.12', print_output=False): """Parse the ml_log file generated by the measure_geometry function. Warnings: Not all keys may exist if mesh is not watertight or manifold Args: ml_log (str): MeshLab log file to parse log (str): filename to l...
Parse the ml_log file generated by the measure_geometry function. Warnings: Not all keys may exist if mesh is not watertight or manifold Args: ml_log (str): MeshLab log file to parse log (str): filename to log output
Below is the the instruction that describes the task: ### Input: Parse the ml_log file generated by the measure_geometry function. Warnings: Not all keys may exist if mesh is not watertight or manifold Args: ml_log (str): MeshLab log file to parse log (str): filename to log output ### Resp...
def get_config(self): """Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns: config: A Python dictionary of cl...
Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns: config: A Python dictionary of class keyword arguments and the...
Below is the the instruction that describes the task: ### Input: Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns:...
def get_user_groups(self, user): """ Get user's group memberships. Args: user (string): User name. Returns: (list): User's groups. Raises: requests.HTTPError on failure. """ self.project_service.set_auth(self._token_project) ...
Get user's group memberships. Args: user (string): User name. Returns: (list): User's groups. Raises: requests.HTTPError on failure.
Below is the the instruction that describes the task: ### Input: Get user's group memberships. Args: user (string): User name. Returns: (list): User's groups. Raises: requests.HTTPError on failure. ### Response: def get_user_groups(self, user): ...
def _find_evil(self): """A utility function that computes a list of missing couplers which should connect two working qubits in the same cell. The presence of (a nonconstant number of) these breaks the polynomial-time claim for our algorithm. Note: we're only actually hurt by missing ...
A utility function that computes a list of missing couplers which should connect two working qubits in the same cell. The presence of (a nonconstant number of) these breaks the polynomial-time claim for our algorithm. Note: we're only actually hurt by missing intercell couplers.
Below is the the instruction that describes the task: ### Input: A utility function that computes a list of missing couplers which should connect two working qubits in the same cell. The presence of (a nonconstant number of) these breaks the polynomial-time claim for our algorithm. Note: w...
def get_primary_key_columns(self): """ Returns the primary key columns. :rtype: list """ if not self.has_primary_key(): raise DBALException('Table "%s" has no primary key.' % self.get_name()) return self.get_primary_key().get_columns()
Returns the primary key columns. :rtype: list
Below is the the instruction that describes the task: ### Input: Returns the primary key columns. :rtype: list ### Response: def get_primary_key_columns(self): """ Returns the primary key columns. :rtype: list """ if not self.has_primary_key(): raise DB...
def create_configuration(self, node, ports): """Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing ...
Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing information of ports for the node :r...
Below is the the instruction that describes the task: ### Input: Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionarie...
def create_releasenotes(project_dir=os.curdir, bugtracker_url=''): """ Creates the release notes file, if not in a package. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: None Raises: ...
Creates the release notes file, if not in a package. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: None Raises: RuntimeError: If the release notes could not be retrieved
Below is the the instruction that describes the task: ### Input: Creates the release notes file, if not in a package. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: None Raises: RuntimeE...
def ceil(self, value, *args): """ Ceil number args: value (str): target returns: str """ n, u = utility.analyze_number(value) return utility.with_unit(int(math.ceil(n)), u)
Ceil number args: value (str): target returns: str
Below is the the instruction that describes the task: ### Input: Ceil number args: value (str): target returns: str ### Response: def ceil(self, value, *args): """ Ceil number args: value (str): target returns: str """ ...
def do_cp(self, params): """ \x1b[1mNAME\x1b[0m cp - Copy from/to local/remote or remote/remote paths \x1b[1mSYNOPSIS\x1b[0m cp <src> <dst> [recursive] [overwrite] [asynchronous] [verbose] [max_items] \x1b[1mDESCRIPTION\x1b[0m src and dst can be: /some/path (in the connecte...
\x1b[1mNAME\x1b[0m cp - Copy from/to local/remote or remote/remote paths \x1b[1mSYNOPSIS\x1b[0m cp <src> <dst> [recursive] [overwrite] [asynchronous] [verbose] [max_items] \x1b[1mDESCRIPTION\x1b[0m src and dst can be: /some/path (in the connected server) zk://[scheme:use...
Below is the the instruction that describes the task: ### Input: \x1b[1mNAME\x1b[0m cp - Copy from/to local/remote or remote/remote paths \x1b[1mSYNOPSIS\x1b[0m cp <src> <dst> [recursive] [overwrite] [asynchronous] [verbose] [max_items] \x1b[1mDESCRIPTION\x1b[0m src and dst can be: ...
def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. ...
Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0
Below is the the instruction that describes the task: ### Input: Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` ot...
def create(self, path, lock): """Create a direct lock for a resource path. path: Normalized path (utf8 encoded string, no trailing '/') lock: lock dictionary, without a token entry Returns: New unique lock token.: <lock **Note:** the lock dic...
Create a direct lock for a resource path. path: Normalized path (utf8 encoded string, no trailing '/') lock: lock dictionary, without a token entry Returns: New unique lock token.: <lock **Note:** the lock dictionary may be modified on return: ...
Below is the the instruction that describes the task: ### Input: Create a direct lock for a resource path. path: Normalized path (utf8 encoded string, no trailing '/') lock: lock dictionary, without a token entry Returns: New unique lock token.: <lock ...
def get_specs_depth_first(self): """ Get the specs for all processes (including called ones), in depth first order. """ done = set() specs = [self] def recursive_find(task_spec): if task_spec in done: return done.add(task...
Get the specs for all processes (including called ones), in depth first order.
Below is the the instruction that describes the task: ### Input: Get the specs for all processes (including called ones), in depth first order. ### Response: def get_specs_depth_first(self): """ Get the specs for all processes (including called ones), in depth first order. "...
def uid(uid): """Decorator specifying the unique identifier (UID) of a test case. The UID will be recorded in the test's record when executed by Mobly. If you use any other decorator for the test method, you may want to use this as the outer-most one. Note a common UID system is the Universal Uni...
Decorator specifying the unique identifier (UID) of a test case. The UID will be recorded in the test's record when executed by Mobly. If you use any other decorator for the test method, you may want to use this as the outer-most one. Note a common UID system is the Universal Unitque Identifier (UUID...
Below is the the instruction that describes the task: ### Input: Decorator specifying the unique identifier (UID) of a test case. The UID will be recorded in the test's record when executed by Mobly. If you use any other decorator for the test method, you may want to use this as the outer-most one. ...
def get_related_indicators_page(self, indicators=None, enclave_ids=None, page_size=None, page_number=None): """ Finds all reports that contain any of the given indicators and returns correlated indicators from those reports. :param indicators: list of indicator values to search for :par...
Finds all reports that contain any of the given indicators and returns correlated indicators from those reports. :param indicators: list of indicator values to search for :param enclave_ids: list of IDs of enclaves to search in :param page_size: number of results per page :param page_nu...
Below is the the instruction that describes the task: ### Input: Finds all reports that contain any of the given indicators and returns correlated indicators from those reports. :param indicators: list of indicator values to search for :param enclave_ids: list of IDs of enclaves to search in ...
def selected_functions_2(self): """Obtain functions available for hazard and exposure selected by user. :returns: List of the available functions metadata. :rtype: list, None """ selection = self.tblFunctions2.selectedItems() if len(selection) != 1: return []...
Obtain functions available for hazard and exposure selected by user. :returns: List of the available functions metadata. :rtype: list, None
Below is the the instruction that describes the task: ### Input: Obtain functions available for hazard and exposure selected by user. :returns: List of the available functions metadata. :rtype: list, None ### Response: def selected_functions_2(self): """Obtain functions available for hazar...
def _l_cv_weight_factor(self): """ Return multiplier for L-CV weightings in case of enhanced single site analysis. Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b """ b = 0.0047 * sqrt(0) + 0.0023 / 2 c = 0.02609 / (self.catchment.record_length - 1) ...
Return multiplier for L-CV weightings in case of enhanced single site analysis. Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b
Below is the the instruction that describes the task: ### Input: Return multiplier for L-CV weightings in case of enhanced single site analysis. Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b ### Response: def _l_cv_weight_factor(self): """ Return multiplier for L-CV wei...
def setValue(self, value): """ Set the attributes value @param value: The new value (may be None) @type value: basestring @return: self @rtype: L{Attribute} """ if isinstance(value, Text): self.value = value else: self.value...
Set the attributes value @param value: The new value (may be None) @type value: basestring @return: self @rtype: L{Attribute}
Below is the the instruction that describes the task: ### Input: Set the attributes value @param value: The new value (may be None) @type value: basestring @return: self @rtype: L{Attribute} ### Response: def setValue(self, value): """ Set the attributes value ...
def is_locked(self): """ Returns: - lock state(bool) Raises: RuntimeError """ _lockScreenRE = re.compile('mShowingLockscreen=(true|false)') m = _lockScreenRE.search(self.shell('dumpsys', 'window', 'policy')) if m: return (m.grou...
Returns: - lock state(bool) Raises: RuntimeError
Below is the the instruction that describes the task: ### Input: Returns: - lock state(bool) Raises: RuntimeError ### Response: def is_locked(self): """ Returns: - lock state(bool) Raises: RuntimeError """ _lockScreenRE...
def liujordan(zenith, transmittance, airmass, dni_extra=1367.0): ''' Determine DNI, DHI, GHI from extraterrestrial flux, transmittance, and optical air mass number. Liu and Jordan, 1960, developed a simplified direct radiation model. DHI is from an empirical equation for diffuse radiation from Liu ...
Determine DNI, DHI, GHI from extraterrestrial flux, transmittance, and optical air mass number. Liu and Jordan, 1960, developed a simplified direct radiation model. DHI is from an empirical equation for diffuse radiation from Liu and Jordan, 1960. Parameters ---------- zenith: pd.Series ...
Below is the the instruction that describes the task: ### Input: Determine DNI, DHI, GHI from extraterrestrial flux, transmittance, and optical air mass number. Liu and Jordan, 1960, developed a simplified direct radiation model. DHI is from an empirical equation for diffuse radiation from Liu and ...
def getMetricsTimeline(tmaster, component_name, metric_names, instances, start_time, end_time, callback=None): """ Get the specified metrics for the given component name of this ...
Get the specified metrics for the given component name of this topology. Returns the following dict on success: { "timeline": { <metricname>: { <instance>: { <start_time> : <numeric value>, <start_time> : <numeric value>, ... } ... }, ... }, ...
Below is the the instruction that describes the task: ### Input: Get the specified metrics for the given component name of this topology. Returns the following dict on success: { "timeline": { <metricname>: { <instance>: { <start_time> : <numeric value>, <start_time> : <num...
def _get_simple_uploaded_file(self, image, file_name): """ :param image: a python PIL ``Image`` instance. :param file_name: The file name of the image. :returns: A django ``SimpleUploadedFile`` instance ready to be saved. """ extensio...
:param image: a python PIL ``Image`` instance. :param file_name: The file name of the image. :returns: A django ``SimpleUploadedFile`` instance ready to be saved.
Below is the the instruction that describes the task: ### Input: :param image: a python PIL ``Image`` instance. :param file_name: The file name of the image. :returns: A django ``SimpleUploadedFile`` instance ready to be saved. ### Response: def _get_simple_upl...
def import_module(module_name): """Helper function to import module""" import sys, os import importlib sys.path.append(os.path.dirname(__file__)) return importlib.import_module(module_name)
Helper function to import module
Below is the the instruction that describes the task: ### Input: Helper function to import module ### Response: def import_module(module_name): """Helper function to import module""" import sys, os import importlib sys.path.append(os.path.dirname(__file__)) return importlib.import_module(module...
def win_menu_select_item(title, *items, **kwargs): """ Usage: win_menu_select_item("[CLASS:Notepad]", "", u"文件(&F)", u"退出(&X)") :param title: :param text: :param items: :return: """ text = kwargs.get("text", "") if not (0 < len(items) < 8): raise ValueError("accepted ...
Usage: win_menu_select_item("[CLASS:Notepad]", "", u"文件(&F)", u"退出(&X)") :param title: :param text: :param items: :return:
Below is the the instruction that describes the task: ### Input: Usage: win_menu_select_item("[CLASS:Notepad]", "", u"文件(&F)", u"退出(&X)") :param title: :param text: :param items: :return: ### Response: def win_menu_select_item(title, *items, **kwargs): """ Usage: win_menu_se...
def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used...
For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used as input to train another supervised learning model such as a :py:cla...
Below is the the instruction that describes the task: ### Input: For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used as input to trai...
def args_as_tuple(self): """FIXME: en fonction de la manière dont la commande a été générée (factory ou parser), le type des arguments est différent : string quand ça vient de la factory ou type normal depuis le parser. Il faut uniformiser tout ça !! """ value = self.arg...
FIXME: en fonction de la manière dont la commande a été générée (factory ou parser), le type des arguments est différent : string quand ça vient de la factory ou type normal depuis le parser. Il faut uniformiser tout ça !!
Below is the the instruction that describes the task: ### Input: FIXME: en fonction de la manière dont la commande a été générée (factory ou parser), le type des arguments est différent : string quand ça vient de la factory ou type normal depuis le parser. Il faut uniformiser tout ça !! ### ...
def trace_sync(self, data, timeout=5.0): """Send tracing data and wait for it to finish. This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns the callback into an awaitable object. The appropriate usage of this method is by calling it inside the event loop as: ...
Send tracing data and wait for it to finish. This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns the callback into an awaitable object. The appropriate usage of this method is by calling it inside the event loop as: await device.trace_sync(data) Args: ...
Below is the the instruction that describes the task: ### Input: Send tracing data and wait for it to finish. This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns the callback into an awaitable object. The appropriate usage of this method is by calling it inside the event l...
def organisation_group_id(self): """ str: Organisation Group ID """ self._validate() self._validate_for_organisation_group_id() parts = [] parts.append(self.election_type) if self.subtype: parts.append(self.subtype) parts.append(self.o...
str: Organisation Group ID
Below is the the instruction that describes the task: ### Input: str: Organisation Group ID ### Response: def organisation_group_id(self): """ str: Organisation Group ID """ self._validate() self._validate_for_organisation_group_id() parts = [] parts.append(...
def get_host_cache(host_ref, host_cache_manager=None): ''' Returns a vim.HostScsiDisk if the host cache is configured on the specified host, other wise returns None host_ref The vim.HostSystem object representing the host that contains the requested disks. host_cache_manager ...
Returns a vim.HostScsiDisk if the host cache is configured on the specified host, other wise returns None host_ref The vim.HostSystem object representing the host that contains the requested disks. host_cache_manager The vim.HostCacheConfigurationManager object representing the cac...
Below is the the instruction that describes the task: ### Input: Returns a vim.HostScsiDisk if the host cache is configured on the specified host, other wise returns None host_ref The vim.HostSystem object representing the host that contains the requested disks. host_cache_manager ...
def is_atlas_enabled(blockstack_opts): """ Can we do atlas operations? """ if not blockstack_opts['atlas']: log.debug("Atlas is disabled") return False if 'zonefiles' not in blockstack_opts: log.debug("Atlas is disabled: no 'zonefiles' path set") return False if...
Can we do atlas operations?
Below is the the instruction that describes the task: ### Input: Can we do atlas operations? ### Response: def is_atlas_enabled(blockstack_opts): """ Can we do atlas operations? """ if not blockstack_opts['atlas']: log.debug("Atlas is disabled") return False if 'zonefiles' not ...
def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): ...
Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): y...
Below is the the instruction that describes the task: ### Input: Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str,...
def sampleVRVT(self,R,n=1,nsigma=None,target=True): """ NAME: sampleVRVT PURPOSE: sample a radial and azimuthal velocity at R INPUT: R - Galactocentric distance (can be Quantity) n= number of distances to sample nsigma= number...
NAME: sampleVRVT PURPOSE: sample a radial and azimuthal velocity at R INPUT: R - Galactocentric distance (can be Quantity) n= number of distances to sample nsigma= number of sigma to rejection-sample on target= if True, sample usi...
Below is the the instruction that describes the task: ### Input: NAME: sampleVRVT PURPOSE: sample a radial and azimuthal velocity at R INPUT: R - Galactocentric distance (can be Quantity) n= number of distances to sample nsigma= number of...
def book(self, name): """Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookError: If an invalid order book is gi...
Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookError: If an invalid order book is given. **Example**: ...
Below is the the instruction that describes the task: ### Input: Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookE...
def hyperparameter_ranges(self): """Return the hyperparameter ranges in a dictionary to be used as part of a request for creating a hyperparameter tuning job. """ hyperparameter_ranges = dict() for range_type in ParameterRange.__all_types__: parameter_ranges = [] ...
Return the hyperparameter ranges in a dictionary to be used as part of a request for creating a hyperparameter tuning job.
Below is the the instruction that describes the task: ### Input: Return the hyperparameter ranges in a dictionary to be used as part of a request for creating a hyperparameter tuning job. ### Response: def hyperparameter_ranges(self): """Return the hyperparameter ranges in a dictionary to be used a...
def refit(self, data, label, decay_rate=0.9, **kwargs): """Refit the existing Booster by new data. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse Data source for refit. If string, it represents the path t...
Refit the existing Booster by new data. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse Data source for refit. If string, it represents the path to txt file. label : list, numpy 1-D array or pandas Series ...
Below is the the instruction that describes the task: ### Input: Refit the existing Booster by new data. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse Data source for refit. If string, it represents the path...
def expect(func, args, times=7, sleep_t=0.5): """try many times as in times with sleep time""" while times > 0: try: return func(*args) except Exception as e: times -= 1 logger.debug("expect failed - attempts left: %d" % times) time.sleep(sleep_t) ...
try many times as in times with sleep time
Below is the the instruction that describes the task: ### Input: try many times as in times with sleep time ### Response: def expect(func, args, times=7, sleep_t=0.5): """try many times as in times with sleep time""" while times > 0: try: return func(*args) except Exception as e...
def VxLANTunnelState_TunnelDestinationIpAddress(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") VxLANTunnelState = ET.SubElement(config, "VxLANTunnelState", xmlns="http://brocade.com/ns/brocade-notification-stream") TunnelDestinationIpAddress = ET.SubEle...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def VxLANTunnelState_TunnelDestinationIpAddress(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") VxLANTunnelState = ET.SubElement(config, "VxLANTunnelState", x...
def GetPythonLibraryDirectoryPath(): """Retrieves the Python library directory path.""" path = sysconfig.get_python_lib(True) _, _, path = path.rpartition(sysconfig.PREFIX) if path.startswith(os.sep): path = path[1:] return path
Retrieves the Python library directory path.
Below is the the instruction that describes the task: ### Input: Retrieves the Python library directory path. ### Response: def GetPythonLibraryDirectoryPath(): """Retrieves the Python library directory path.""" path = sysconfig.get_python_lib(True) _, _, path = path.rpartition(sysconfig.PREFIX) if path.s...
def pfeedback(self, msg: str) -> None: """For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.""" if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: ...
For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.
Below is the the instruction that describes the task: ### Input: For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`. ### Response: def pfeedback(self, msg: str) -> None: """For printing nonessential feedback. C...
def _CopyFromDateTimeValues(self, date_time_values): """Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. Raises: ValueError: if no helper can be cr...
Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. Raises: ValueError: if no helper can be created for the current precision.
Below is the the instruction that describes the task: ### Input: Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. Raises: ValueError: if no helper ...
def strip_figures(figure): """ Strips a figure into multiple figures with a trace on each of them Parameters: ----------- figure : Figure Plotly Figure """ fig=[] for trace in figure['data']: fig.append(dict(data=[trace],layout=figure['layout'])) return fig
Strips a figure into multiple figures with a trace on each of them Parameters: ----------- figure : Figure Plotly Figure
Below is the the instruction that describes the task: ### Input: Strips a figure into multiple figures with a trace on each of them Parameters: ----------- figure : Figure Plotly Figure ### Response: def strip_figures(figure): """ Strips a figure into multiple figures with a trace on each of them Param...
def loop(self): """ Inner loop for interactive mode. Do not call directly. """ while True: with self.setup_readline(): try: line = input(self.prompt) except EOFError: _vprinterr('^D') break ...
Inner loop for interactive mode. Do not call directly.
Below is the the instruction that describes the task: ### Input: Inner loop for interactive mode. Do not call directly. ### Response: def loop(self): """ Inner loop for interactive mode. Do not call directly. """ while True: with self.setup_readline(): try: ...
def list_queues(self): ''' Enumerates the queues in the service namespace. ''' request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = '/$Resources/Queues' request.path, request.query = self._httpclient._update_request...
Enumerates the queues in the service namespace.
Below is the the instruction that describes the task: ### Input: Enumerates the queues in the service namespace. ### Response: def list_queues(self): ''' Enumerates the queues in the service namespace. ''' request = HTTPRequest() request.method = 'GET' request.host =...
def shared(self, value, name=None): """ Create a shared theano scalar value. """ if type(value) == int: final_value = np.array(value, dtype="int32") elif type(value) == float: final_value = np.array(value, dtype=env.FLOATX) else: final_...
Create a shared theano scalar value.
Below is the the instruction that describes the task: ### Input: Create a shared theano scalar value. ### Response: def shared(self, value, name=None): """ Create a shared theano scalar value. """ if type(value) == int: final_value = np.array(value, dtype="int32") ...
def ltouches(self, span): """ Returns true if the end of this span touches the left (starting) side of the given span. """ if isinstance(span, list): return [sp for sp in span if self._ltouches(sp)] return self._ltouches(span)
Returns true if the end of this span touches the left (starting) side of the given span.
Below is the the instruction that describes the task: ### Input: Returns true if the end of this span touches the left (starting) side of the given span. ### Response: def ltouches(self, span): """ Returns true if the end of this span touches the left (starting) side of the given span. """ ...
def _basic_cancel_notify(self, args): """Consumer cancelled by server. Most likely the queue was deleted. """ consumer_tag = args.read_shortstr() callback = self._on_cancel(consumer_tag) if callback: callback(consumer_tag) else: raise Con...
Consumer cancelled by server. Most likely the queue was deleted.
Below is the the instruction that describes the task: ### Input: Consumer cancelled by server. Most likely the queue was deleted. ### Response: def _basic_cancel_notify(self, args): """Consumer cancelled by server. Most likely the queue was deleted. """ consumer_tag = arg...
def patch_storage_class(self, name, body, **kwargs): # noqa: E501 """patch_storage_class # noqa: E501 partially update the specified StorageClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
patch_storage_class # noqa: E501 partially update the specified StorageClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_storage_class(name, body, async_req=True) ...
Below is the the instruction that describes the task: ### Input: patch_storage_class # noqa: E501 partially update the specified StorageClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> ...
def override_if_not_in_args(flag, argument, args): """Checks if flags is in args, and if not it adds the flag to args.""" if flag not in args: args.extend([flag, argument])
Checks if flags is in args, and if not it adds the flag to args.
Below is the the instruction that describes the task: ### Input: Checks if flags is in args, and if not it adds the flag to args. ### Response: def override_if_not_in_args(flag, argument, args): """Checks if flags is in args, and if not it adds the flag to args.""" if flag not in args: args.extend([flag, a...
def docker_fabric(*args, **kwargs): """ :param args: Positional arguments to Docker client. :param kwargs: Keyword arguments to Docker client. :return: Docker client. :rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient """ ci = kwargs.get('client_implementati...
:param args: Positional arguments to Docker client. :param kwargs: Keyword arguments to Docker client. :return: Docker client. :rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient
Below is the the instruction that describes the task: ### Input: :param args: Positional arguments to Docker client. :param kwargs: Keyword arguments to Docker client. :return: Docker client. :rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient ### Response: def docker_f...