code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def __set_recent_files_actions(self): """ Sets the recent files actions. """ recentFiles = [foundations.strings.to_string(file) for file in self.__settings.get_key(self.__settings_section, "recentFiles").toStringList() if foundations.common....
Sets the recent files actions.
Below is the the instruction that describes the task: ### Input: Sets the recent files actions. ### Response: def __set_recent_files_actions(self): """ Sets the recent files actions. """ recentFiles = [foundations.strings.to_string(file) for file in self.__se...
def _read_missing_lob_data_from_db(self, readoffset, readlength): """Read LOB request part from database""" logger.debug('Reading missing lob data from db. Offset: %d, readlength: %d' % (readoffset, readlength)) lob_data = self._make_read_lob_request(readoffset, readlength) # make sure ...
Read LOB request part from database
Below is the the instruction that describes the task: ### Input: Read LOB request part from database ### Response: def _read_missing_lob_data_from_db(self, readoffset, readlength): """Read LOB request part from database""" logger.debug('Reading missing lob data from db. Offset: %d, readlength: %d' ...
def save_image(image, destination=None, filename=None, **options): """ Save a PIL image. """ if destination is None: destination = BytesIO() filename = filename or '' # Ensure plugins are fully loaded so that Image.EXTENSION is populated. Image.init() format = Image.EXTENSION.get...
Save a PIL image.
Below is the the instruction that describes the task: ### Input: Save a PIL image. ### Response: def save_image(image, destination=None, filename=None, **options): """ Save a PIL image. """ if destination is None: destination = BytesIO() filename = filename or '' # Ensure plugins ar...
def get_block(self, x, y, z): """Get a block from relative x,y,z.""" sy,by = divmod(y, 16) section = self.get_section(sy) if section == None: return None return section.get_block(x, by, z)
Get a block from relative x,y,z.
Below is the the instruction that describes the task: ### Input: Get a block from relative x,y,z. ### Response: def get_block(self, x, y, z): """Get a block from relative x,y,z.""" sy,by = divmod(y, 16) section = self.get_section(sy) if section == None: return None ...
def add_features(self, kept_indices, new_indices, new_state_vec, new_state_cov, new_noise_var): '''Add new features to the state kept_indices - the mapping from all indices in the state to new indices in the new version new_indices - the indices of t...
Add new features to the state kept_indices - the mapping from all indices in the state to new indices in the new version new_indices - the indices of the new features in the new version new_state_vec - the state vectors for the new indices new_state_cov - the c...
Below is the the instruction that describes the task: ### Input: Add new features to the state kept_indices - the mapping from all indices in the state to new indices in the new version new_indices - the indices of the new features in the new version new_state_vec -...
def cut_matrix(self, n): """Compute the cut matrix for this cut. The cut matrix is a square matrix which represents connections severed by the cut. Args: n (int): The size of the network. Example: >>> cut = Cut((1,), (2,)) >>> cut.cut_matrix(...
Compute the cut matrix for this cut. The cut matrix is a square matrix which represents connections severed by the cut. Args: n (int): The size of the network. Example: >>> cut = Cut((1,), (2,)) >>> cut.cut_matrix(3) array([[0., 0., 0.], ...
Below is the the instruction that describes the task: ### Input: Compute the cut matrix for this cut. The cut matrix is a square matrix which represents connections severed by the cut. Args: n (int): The size of the network. Example: >>> cut = Cut((1,), (2,)...
def read(self, filename, encoding=None): """Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of file, default None """ with open(filename, encoding=encoding) as fp: self._read(fp, filename) self._filename ...
Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of file, default None
Below is the the instruction that describes the task: ### Input: Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of file, default None ### Response: def read(self, filename, encoding=None): """Read and parse a filename. Args: ...
def bulleted_list(items, indent=0, bullet_type='-'): """Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type t...
Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type to use. Returns ------- formatted_list : str ...
Below is the the instruction that describes the task: ### Input: Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bull...
def add_pending(self, family: str, email: str=None) -> models.Analysis: """Add pending entry for an analysis.""" started_at = dt.datetime.now() new_log = self.Analysis(family=family, status='pending', started_at=started_at) new_log.user = self.user(email) if email else None self....
Add pending entry for an analysis.
Below is the the instruction that describes the task: ### Input: Add pending entry for an analysis. ### Response: def add_pending(self, family: str, email: str=None) -> models.Analysis: """Add pending entry for an analysis.""" started_at = dt.datetime.now() new_log = self.Analysis(family=fa...
def write_discrete_trajectory(filename, dtraj): r"""Write discrete trajectory to ascii file. The discrete trajectory is written to a single column ascii file with integer entries Parameters ---------- filename : str The filename of the discrete state trajectory file. The filena...
r"""Write discrete trajectory to ascii file. The discrete trajectory is written to a single column ascii file with integer entries Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relati...
Below is the the instruction that describes the task: ### Input: r"""Write discrete trajectory to ascii file. The discrete trajectory is written to a single column ascii file with integer entries Parameters ---------- filename : str The filename of the discrete state trajectory file. ...
def get_rubric(self): """Gets the rubric. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: IllegalState - ``has_rubric()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be ...
Gets the rubric. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: IllegalState - ``has_rubric()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the rubric. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: IllegalState - ``has_rubric()`` is ``false`` raise: OperationFailed - unable to complete request *complianc...
def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.""" if env.GetOption("no_exec"): # find these paths for use in is_LaTeX to search fo...
A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.
Below is the the instruction that describes the task: ### Input: A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string. ### Response: def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunctio...
def launch_processes(tests, run_module, group=True, **config): """ Helper method to launch processes and sync output """ manager = multiprocessing.Manager() test_summaries = manager.dict() process_handles = [multiprocessing.Process(target=run_module.run_suite, args=(test, config[t...
Helper method to launch processes and sync output
Below is the the instruction that describes the task: ### Input: Helper method to launch processes and sync output ### Response: def launch_processes(tests, run_module, group=True, **config): """ Helper method to launch processes and sync output """ manager = multiprocessing.Manager() test_summaries = ...
def from_dict(self, dirent): """ Create a new FilePermissions object from the given dictionary. This works with the FileListing parser class, which has already done the hard work of pulling many of these fields out. We create an object with all the dictionary keys available as ...
Create a new FilePermissions object from the given dictionary. This works with the FileListing parser class, which has already done the hard work of pulling many of these fields out. We create an object with all the dictionary keys available as properties, and also split the ``perms`` ...
Below is the the instruction that describes the task: ### Input: Create a new FilePermissions object from the given dictionary. This works with the FileListing parser class, which has already done the hard work of pulling many of these fields out. We create an object with all the dictionar...
def splitMeiUyir(uyirmei_char): """ This function split uyirmei compound character into mei + uyir characters and returns in tuple. Input : It must be unicode tamil char. Written By : Arulalan.T Date : 22.09.2014 """ if not isinstance(uyirmei_char, PYTHON3 and str or unicode): ...
This function split uyirmei compound character into mei + uyir characters and returns in tuple. Input : It must be unicode tamil char. Written By : Arulalan.T Date : 22.09.2014
Below is the the instruction that describes the task: ### Input: This function split uyirmei compound character into mei + uyir characters and returns in tuple. Input : It must be unicode tamil char. Written By : Arulalan.T Date : 22.09.2014 ### Response: def splitMeiUyir(uyirmei_char): """ ...
def vertical_offset(self, value): """ Setter for **self.__vertical_offset** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("vertical_offset", ...
Setter for **self.__vertical_offset** attribute. :param value: Attribute value. :type value: int
Below is the the instruction that describes the task: ### Input: Setter for **self.__vertical_offset** attribute. :param value: Attribute value. :type value: int ### Response: def vertical_offset(self, value): """ Setter for **self.__vertical_offset** attribute. :param val...
def _evalQUnits(self, datetimeString, sourceTime): """ Evaluate text passed by L{_partialParseQUnits()} """ s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is a time string with single char units like "5 h 30 m" mod...
Evaluate text passed by L{_partialParseQUnits()}
Below is the the instruction that describes the task: ### Input: Evaluate text passed by L{_partialParseQUnits()} ### Response: def _evalQUnits(self, datetimeString, sourceTime): """ Evaluate text passed by L{_partialParseQUnits()} """ s = datetimeString.strip() sourceTime =...
def this_quarter(): """ Return start and end date of this quarter. """ since = TODAY + delta(day=1) while since.month % 3 != 0: since -= delta(months=1) until = since + delta(months=3) return Date(since), Date(until)
Return start and end date of this quarter.
Below is the the instruction that describes the task: ### Input: Return start and end date of this quarter. ### Response: def this_quarter(): """ Return start and end date of this quarter. """ since = TODAY + delta(day=1) while since.month % 3 != 0: since -= delta(months=1) ...
def import_image(image_path, os_version): """Import image. Input parameters: :image_path: Image file path :os_version: Operating system version. e.g. rhel7.2 """ image_name = os.path.basename(image_path) print("Checking if image %s exists or not, import it if not exists" % ...
Import image. Input parameters: :image_path: Image file path :os_version: Operating system version. e.g. rhel7.2
Below is the the instruction that describes the task: ### Input: Import image. Input parameters: :image_path: Image file path :os_version: Operating system version. e.g. rhel7.2 ### Response: def import_image(image_path, os_version): """Import image. Input parameters: :image_pat...
def configure_containers(self, current_options): """ Configures the container dict """ containers = [ ("default", "Default container. For Bash and Python 2 tasks"), ("cpp", "Contains gcc and g++ for compiling C++"), ("java7", "Contains Java 7"), ("java8sca...
Configures the container dict
Below is the the instruction that describes the task: ### Input: Configures the container dict ### Response: def configure_containers(self, current_options): """ Configures the container dict """ containers = [ ("default", "Default container. For Bash and Python 2 tasks"), (...
def _init_client(self, from_archive=False): """Init client""" return RSSClient(self.url, self.archive, from_archive)
Init client
Below is the the instruction that describes the task: ### Input: Init client ### Response: def _init_client(self, from_archive=False): """Init client""" return RSSClient(self.url, self.archive, from_archive)
def graph_from_point(center_point, distance=1000, distance_type='bbox', network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, ...
Create a networkx graph from OSM data within some distance of some (lat, lon) center point. Parameters ---------- center_point : tuple the (lat, lon) central point around which to construct the graph distance : int retain only those nodes within this many meters of the center of the...
Below is the the instruction that describes the task: ### Input: Create a networkx graph from OSM data within some distance of some (lat, lon) center point. Parameters ---------- center_point : tuple the (lat, lon) central point around which to construct the graph distance : int ...
def _update_nilrt_restart_state(): ''' NILRT systems determine whether to reboot after various package operations including but not limited to kernel module installs/removals by checking specific file md5sums & timestamps. These files are touched/modified by the post-install/post-remove functions of...
NILRT systems determine whether to reboot after various package operations including but not limited to kernel module installs/removals by checking specific file md5sums & timestamps. These files are touched/modified by the post-install/post-remove functions of their respective packages. The opkg modul...
Below is the the instruction that describes the task: ### Input: NILRT systems determine whether to reboot after various package operations including but not limited to kernel module installs/removals by checking specific file md5sums & timestamps. These files are touched/modified by the post-install/po...
def copy_samples(self, other, parameters=None, parameter_names=None, read_args=None, write_args=None): """Should copy samples to the other files. Parameters ---------- other : InferenceFile An open inference file to write to. parameters : list of...
Should copy samples to the other files. Parameters ---------- other : InferenceFile An open inference file to write to. parameters : list of str, optional List of parameters to copy. If None, will copy all parameters. parameter_names : dict, optional ...
Below is the the instruction that describes the task: ### Input: Should copy samples to the other files. Parameters ---------- other : InferenceFile An open inference file to write to. parameters : list of str, optional List of parameters to copy. If None, wi...
def calculate(self, **state): """ Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param y: [mass fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} :returns: [Pa.s]...
Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param y: [mass fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} :returns: [Pa.s] dynamic viscosity The **state parameter ...
Below is the the instruction that describes the task: ### Input: Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param y: [mass fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} ...
def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call...
Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found.
Below is the the instruction that describes the task: ### Input: Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. ##...
def _iter_coords(nsls): """Iterate through all matching coordinates in a sequence of slices.""" # First convert all slices to ranges ranges = list() for nsl in nsls: if isinstance(nsl, int): ranges.append(range(nsl, nsl+1)) else: ranges.append(range(nsl.start, nsl...
Iterate through all matching coordinates in a sequence of slices.
Below is the the instruction that describes the task: ### Input: Iterate through all matching coordinates in a sequence of slices. ### Response: def _iter_coords(nsls): """Iterate through all matching coordinates in a sequence of slices.""" # First convert all slices to ranges ranges = list() for n...
def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.form...
Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} ...
Below is the the instruction that describes the task: ### Input: Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> ...
def edit_account_info(self, short_name=None, author_name=None, author_url=None): """ Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several ac...
Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publis...
Below is the the instruction that describes the task: ### Input: Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several accounts remember which they are currently using. ...
def process_unavailable_presence(self,stanza): """ Process <presence type="unavailable"/> received from the room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `MucPresence` """ fr=stanza.get_from() if not fr.resource: ...
Process <presence type="unavailable"/> received from the room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `MucPresence`
Below is the the instruction that describes the task: ### Input: Process <presence type="unavailable"/> received from the room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `MucPresence` ### Response: def process_unavailable_presence(self,stanza): ...
def __get_right_line(self, widget_output): ''' Gets next line for right panel ''' right_line = '' if widget_output: right_line = widget_output.pop(0) if len(right_line) > self.right_panel_width: right_line_plain = self.markup.clean_markup(rig...
Gets next line for right panel
Below is the the instruction that describes the task: ### Input: Gets next line for right panel ### Response: def __get_right_line(self, widget_output): ''' Gets next line for right panel ''' right_line = '' if widget_output: right_line = widget_output.pop(0) ...
def airspeed_ratio(VFR_HUD): '''recompute airspeed with a different ARSPD_RATIO''' import mavutil mav = mavutil.mavfile_global airspeed_pressure = (VFR_HUD.airspeed**2) / ratio airspeed = sqrt(airspeed_pressure * ratio) return airspeed
recompute airspeed with a different ARSPD_RATIO
Below is the the instruction that describes the task: ### Input: recompute airspeed with a different ARSPD_RATIO ### Response: def airspeed_ratio(VFR_HUD): '''recompute airspeed with a different ARSPD_RATIO''' import mavutil mav = mavutil.mavfile_global airspeed_pressure = (VFR_HUD.airspeed**2) / r...
def get(self, url, callback, params=None, json=None, headers=None): """Get a URL. Args: callback(func): The response callback function Keyword Args: params(dict): Parameters for the request json(dict): JSON body for the request he...
Get a URL. Args: callback(func): The response callback function Keyword Args: params(dict): Parameters for the request json(dict): JSON body for the request headers(dict): Additional headers for the request Returns: The result o...
Below is the the instruction that describes the task: ### Input: Get a URL. Args: callback(func): The response callback function Keyword Args: params(dict): Parameters for the request json(dict): JSON body for the request headers(dict): Additiona...
def _construct_losses(self, data, predictions, ensemble_prediction): """ Construct losses for the ensemble and each constitute model Parameters ---------- data: np.ndarray The univariate time series predictions : np.ndarray The predictions of eac...
Construct losses for the ensemble and each constitute model Parameters ---------- data: np.ndarray The univariate time series predictions : np.ndarray The predictions of each constitute model ensemble_prediction : np.ndarray The pred...
Below is the the instruction that describes the task: ### Input: Construct losses for the ensemble and each constitute model Parameters ---------- data: np.ndarray The univariate time series predictions : np.ndarray The predictions of each constitute...
def assign_activity_to_objective_bank(self, activity_id, objective_bank_id): """Adds an existing ``Activity`` to a ``ObjectiveBank``. arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity`` arg: objective_bank_id (osid.id.Id): the ``Id`` of the ``ObjectiveBank`` ...
Adds an existing ``Activity`` to a ``ObjectiveBank``. arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity`` arg: objective_bank_id (osid.id.Id): the ``Id`` of the ``ObjectiveBank`` raise: AlreadyExists - ``activity_id`` already mapped to ``objectiv...
Below is the the instruction that describes the task: ### Input: Adds an existing ``Activity`` to a ``ObjectiveBank``. arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity`` arg: objective_bank_id (osid.id.Id): the ``Id`` of the ``ObjectiveBank`` raise: Already...
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): """ Return the BestNR statistic for this row. """ # weight SNR by chisq bestnr = self.get_new_snr(index=index, nhigh=nhigh, column="chisq") if len(self....
Return the BestNR statistic for this row.
Below is the the instruction that describes the task: ### Input: Return the BestNR statistic for this row. ### Response: def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): """ Return the BestNR statistic for this row. """ # weight...
def create_from_hash(self, stream, name, output_type, output_params, initial_status=None, start=None, end=None): """ Create a new push subscription using a live stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param...
Create a new push subscription using a live stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param stream: The hash of a DataSift stream. :type stream: str :param name: The name to give the newly created subscription ...
Below is the the instruction that describes the task: ### Input: Create a new push subscription using a live stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param stream: The hash of a DataSift stream. :type stream: str ...
def check_columns(column, line, columns): """ Make sure the column is the minimum between the largest column asked for and the max column available in the line. """ return column <= min(len(line), max(columns))
Make sure the column is the minimum between the largest column asked for and the max column available in the line.
Below is the the instruction that describes the task: ### Input: Make sure the column is the minimum between the largest column asked for and the max column available in the line. ### Response: def check_columns(column, line, columns): """ Make sure the column is the minimum between the largest column ...
def onecmd(self, line): """Do not crash the entire program when a single command fails.""" try: return cmd.Cmd.onecmd(self, line) except Exception as e: print("Critical error.", e)
Do not crash the entire program when a single command fails.
Below is the the instruction that describes the task: ### Input: Do not crash the entire program when a single command fails. ### Response: def onecmd(self, line): """Do not crash the entire program when a single command fails.""" try: return cmd.Cmd.onecmd(self, line) except Ex...
def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, ...
Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type stri...
Below is the the instruction that describes the task: ### Input: Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type ...
def generateSimpleSequences(nCoinc=10, seqLength=[5,6,7], nSeq=100): """ Generate a set of simple sequences. The elements of the sequences will be integers from 0 to 'nCoinc'-1. The length of each sequence will be randomly chosen from the 'seqLength' list. Parameters: --------------------------------------...
Generate a set of simple sequences. The elements of the sequences will be integers from 0 to 'nCoinc'-1. The length of each sequence will be randomly chosen from the 'seqLength' list. Parameters: ----------------------------------------------- nCoinc: the number of elements available to use in the seque...
Below is the the instruction that describes the task: ### Input: Generate a set of simple sequences. The elements of the sequences will be integers from 0 to 'nCoinc'-1. The length of each sequence will be randomly chosen from the 'seqLength' list. Parameters: ----------------------------------------------...
def get_cursor_position(): """Write an escape sequence to ask for the current cursor position. Since the result is written on the standard input, this function should not be used if you expect that your input has been pasted, because the characters in the buffer would be read before the answer about...
Write an escape sequence to ask for the current cursor position. Since the result is written on the standard input, this function should not be used if you expect that your input has been pasted, because the characters in the buffer would be read before the answer about the cursor.
Below is the the instruction that describes the task: ### Input: Write an escape sequence to ask for the current cursor position. Since the result is written on the standard input, this function should not be used if you expect that your input has been pasted, because the characters in the buffer would ...
def add_partition(self, partition): """Add partition to partition list.""" assert(partition not in self._partitions) # Add partition to existing set self._partitions.add(partition) # Add broker to replica list partition.add_replica(self)
Add partition to partition list.
Below is the the instruction that describes the task: ### Input: Add partition to partition list. ### Response: def add_partition(self, partition): """Add partition to partition list.""" assert(partition not in self._partitions) # Add partition to existing set self._partitions.add(p...
def get_merged_config(**options): """Get the final merged configuration for supvervisord, as a string. This is the top-level function exported by this module. It combines the config file from the main project with default settings and those specified in the command-line, processes various special sect...
Get the final merged configuration for supvervisord, as a string. This is the top-level function exported by this module. It combines the config file from the main project with default settings and those specified in the command-line, processes various special section names, and returns the resulting ...
Below is the the instruction that describes the task: ### Input: Get the final merged configuration for supvervisord, as a string. This is the top-level function exported by this module. It combines the config file from the main project with default settings and those specified in the command-line, pr...
def portfolio_from_orders(orders, funds=1e5, price_type='close'): """Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates) Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated. Appends the symbol "total_value" to store the total value of cash + st...
Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates) Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated. Appends the symbol "total_value" to store the total value of cash + stocks at each timestamp. The symbol holdings are found by multipling ...
Below is the the instruction that describes the task: ### Input: Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates) Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated. Appends the symbol "total_value" to store the total value of cash + stocks...
def create_data_descriptor(self, is_sequence: bool, collection_dimension_count: int, datum_dimension_count: int) -> DataAndMetadata.DataDescriptor: """Create a data descriptor. :param is_sequence: whether the descriptor describes a sequence of data. :param collection_dimension_count: the number...
Create a data descriptor. :param is_sequence: whether the descriptor describes a sequence of data. :param collection_dimension_count: the number of collection dimensions represented by the descriptor. :param datum_dimension_count: the number of datum dimensions represented by the descriptor. ...
Below is the the instruction that describes the task: ### Input: Create a data descriptor. :param is_sequence: whether the descriptor describes a sequence of data. :param collection_dimension_count: the number of collection dimensions represented by the descriptor. :param datum_dimension_co...
def reset(self): """ Resets the value of config item to its default value. """ old_value = self._value old_raw_str_value = self.raw_str_value self._value = not_set self.raw_str_value = not_set new_value = self._value if old_value is not_set: ...
Resets the value of config item to its default value.
Below is the the instruction that describes the task: ### Input: Resets the value of config item to its default value. ### Response: def reset(self): """ Resets the value of config item to its default value. """ old_value = self._value old_raw_str_value = self.raw_str_value ...
def _prepare_b_jkl_mn(readout_povm, pauli_basis, pre_channel_ops, post_channel_ops, rho0): """ Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_...
Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_{jr}(\mathcal{R}_{k})_{rm} (\mathcal{R}_{l})_{nq} (\rho_0)_q where :math:`\mathcal{R}_{k}` is the ...
Below is the the instruction that describes the task: ### Input: Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_{jr}(\mathcal{R}_{k})_{rm} (\mathc...
def get_asn_verbose_dns(self, asn=None): """ The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`str`): T...
The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`str`): The AS number (required). Returns: str: T...
Below is the the instruction that describes the task: ### Input: The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`...
def get_attribute(self, name): """ Returns the requested SAML attribute. :param name: Name of the attribute :type name: string :returns: Attribute value if exists or [] :rtype: string """ assert isinstance(name, compat.str_type) return self.__att...
Returns the requested SAML attribute. :param name: Name of the attribute :type name: string :returns: Attribute value if exists or [] :rtype: string
Below is the the instruction that describes the task: ### Input: Returns the requested SAML attribute. :param name: Name of the attribute :type name: string :returns: Attribute value if exists or [] :rtype: string ### Response: def get_attribute(self, name): """ Re...
def abbreviate(s): """Apply a set of standard transformations to string to produce an abbreviation no more than 4 characters long. """ if not s: return '' # check the cache if s in abbreviate.abbreviations: return abbreviate.abbreviations[s] # anything less than 4 characters ...
Apply a set of standard transformations to string to produce an abbreviation no more than 4 characters long.
Below is the the instruction that describes the task: ### Input: Apply a set of standard transformations to string to produce an abbreviation no more than 4 characters long. ### Response: def abbreviate(s): """Apply a set of standard transformations to string to produce an abbreviation no more than 4 c...
def _restore_event_client(self): """Restores previously created event client.""" if not self._event_client: self._event_client = self._start_event_client() return self._event_client.host_port = self.host_port self._event_client.device_port = self.device_port ...
Restores previously created event client.
Below is the the instruction that describes the task: ### Input: Restores previously created event client. ### Response: def _restore_event_client(self): """Restores previously created event client.""" if not self._event_client: self._event_client = self._start_event_client() ...
def index_tuple(self,tables_dict,index,is_set): "helper for rowget/rowset" if not self.aonly_resolved: raise RuntimeError('resolve_aonly() before querying nix') with tables_dict.tempkeys(): tables_dict.update(self.aonly) # todo: find spec support for aliases overwriting existing tables. (more likely, ...
helper for rowget/rowset
Below is the the instruction that describes the task: ### Input: helper for rowget/rowset ### Response: def index_tuple(self,tables_dict,index,is_set): "helper for rowget/rowset" if not self.aonly_resolved: raise RuntimeError('resolve_aonly() before querying nix') with tables_dict.tempkeys(): tab...
def nativestring(val, encodings=None): """ Converts the inputted value to a native python string-type format. :param val | <variant> encodings | (<str>, ..) || None :sa decoded :return <unicode> || <str> """ # if it is already a nativ...
Converts the inputted value to a native python string-type format. :param val | <variant> encodings | (<str>, ..) || None :sa decoded :return <unicode> || <str>
Below is the the instruction that describes the task: ### Input: Converts the inputted value to a native python string-type format. :param val | <variant> encodings | (<str>, ..) || None :sa decoded :return <unicode> || <str> ### Response: def n...
def get_tick(self, name): """Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph c...
Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph compiler and used for fast ope...
Below is the the instruction that describes the task: ### Input: Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated...
def parse(cls, filepath, filecontent, parser): """Parses a source for addressable Serializable objects. No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any objects they point to in other namespaces or even in the same namespace but from a seperate source are lef...
Parses a source for addressable Serializable objects. No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any objects they point to in other namespaces or even in the same namespace but from a seperate source are left as unresolved pointers. :param string filepath:...
Below is the the instruction that describes the task: ### Input: Parses a source for addressable Serializable objects. No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any objects they point to in other namespaces or even in the same namespace but from a seperate ...
def paramsarray(self): """All free model parameters as 1-dimensional `numpy.ndarray`. You are allowed to update model parameters by direct assignment of this property.""" # Return copy of `_paramsarray` because setter checks if changed if self._paramsarray is not None: ...
All free model parameters as 1-dimensional `numpy.ndarray`. You are allowed to update model parameters by direct assignment of this property.
Below is the the instruction that describes the task: ### Input: All free model parameters as 1-dimensional `numpy.ndarray`. You are allowed to update model parameters by direct assignment of this property. ### Response: def paramsarray(self): """All free model parameters as 1-dimensional ...
def __move(self, current_pos): ''' Move in the feature map. Args: current_pos: The now position. Returns: The next position. ''' if self.__move_range is not None: next_pos = np.random.randint(current_pos - self.__move_range, curren...
Move in the feature map. Args: current_pos: The now position. Returns: The next position.
Below is the the instruction that describes the task: ### Input: Move in the feature map. Args: current_pos: The now position. Returns: The next position. ### Response: def __move(self, current_pos): ''' Move in the feature map. Args: ...
async def connect(self, *, timeout=60.0, reconnect=True): """|coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. Parameters ----------- timeout: :class:`float` The timeout in seconds to wait for the v...
|coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. Parameters ----------- timeout: :class:`float` The timeout in seconds to wait for the voice endpoint. reconnect: :class:`bool` Whether t...
Below is the the instruction that describes the task: ### Input: |coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. Parameters ----------- timeout: :class:`float` The timeout in seconds to wait for the v...
def matches(self, pattern): """Asserts that val is string and matches regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if l...
Asserts that val is string and matches regex pattern.
Below is the the instruction that describes the task: ### Input: Asserts that val is string and matches regex pattern. ### Response: def matches(self, pattern): """Asserts that val is string and matches regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is no...
def wiki_download(url): ''' scrape friendly: sleep 20 seconds between each request, cache each result. ''' DOWNLOAD_TMPL = '../data/tv_and_movie_freqlist%s.html' freq_range = url[url.rindex('/')+1:] tmp_path = DOWNLOAD_TMPL % freq_range if os.path.exists(tmp_path): print('cached.......
scrape friendly: sleep 20 seconds between each request, cache each result.
Below is the the instruction that describes the task: ### Input: scrape friendly: sleep 20 seconds between each request, cache each result. ### Response: def wiki_download(url): ''' scrape friendly: sleep 20 seconds between each request, cache each result. ''' DOWNLOAD_TMPL = '../data/tv_and_movie_...
def infer_format(filename:str) -> str: """Return extension identifying format of given filename""" _, ext = os.path.splitext(filename) return ext
Return extension identifying format of given filename
Below is the the instruction that describes the task: ### Input: Return extension identifying format of given filename ### Response: def infer_format(filename:str) -> str: """Return extension identifying format of given filename""" _, ext = os.path.splitext(filename) return ext
def _validate_noneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'noneof'} """ valids, _errors = \ self.__validate_logical('noneof', definitions, field, value) if valids > 0: self._error(field, errors.NONEOF, _errors, valids, ...
{'type': 'list', 'logical': 'noneof'}
Below is the the instruction that describes the task: ### Input: {'type': 'list', 'logical': 'noneof'} ### Response: def _validate_noneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'noneof'} """ valids, _errors = \ self.__validate_logical('noneof', definitions, fi...
def expect_element(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b...
Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b') 'B' >>> foo('c') # doctest: +NORMALIZE_WHITESPACE +ELLIPS...
Below is the the instruction that describes the task: ### Input: Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b...
def list(cls, service, ops_filter, page_size=0): """Gets the list of operations for the specified filter. Args: service: Google Genomics API service object ops_filter: string filter of operations to return page_size: the number of operations to requested on each list operation to the ...
Gets the list of operations for the specified filter. Args: service: Google Genomics API service object ops_filter: string filter of operations to return page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) ...
Below is the the instruction that describes the task: ### Input: Gets the list of operations for the specified filter. Args: service: Google Genomics API service object ops_filter: string filter of operations to return page_size: the number of operations to requested on each list operation to...
def subclass_genesis(self, genesisclass): """Subclass the given genesis class and implement all abstract methods :param genesisclass: the GenesisWin class to subclass :type genesisclass: :class:`GenesisWin` :returns: the subclass :rtype: subclass of :class:`GenesisWin` :...
Subclass the given genesis class and implement all abstract methods :param genesisclass: the GenesisWin class to subclass :type genesisclass: :class:`GenesisWin` :returns: the subclass :rtype: subclass of :class:`GenesisWin` :raises: None
Below is the the instruction that describes the task: ### Input: Subclass the given genesis class and implement all abstract methods :param genesisclass: the GenesisWin class to subclass :type genesisclass: :class:`GenesisWin` :returns: the subclass :rtype: subclass of :class:`Genes...
def register_client(provider_info, redirect_uris): """ This function registers a new client with the specified OpenID Provider, and then returns the regitered client ID and other information. :param provider_info: The contents of the discovery endpoint as specified by the OpenID Connect Discove...
This function registers a new client with the specified OpenID Provider, and then returns the regitered client ID and other information. :param provider_info: The contents of the discovery endpoint as specified by the OpenID Connect Discovery 1.0 specifications. :type provider_info: dict :param...
Below is the the instruction that describes the task: ### Input: This function registers a new client with the specified OpenID Provider, and then returns the regitered client ID and other information. :param provider_info: The contents of the discovery endpoint as specified by the OpenID Connect D...
def fixpix(data, mask, kind='linear'): """Interpolate 2D array data in rows""" if data.shape != mask.shape: raise ValueError if not numpy.any(mask): return data x = numpy.arange(0, data.shape[0]) for row, mrow in zip(data, mask): if numpy.any(mrow): # Interpolate if there'...
Interpolate 2D array data in rows
Below is the the instruction that describes the task: ### Input: Interpolate 2D array data in rows ### Response: def fixpix(data, mask, kind='linear'): """Interpolate 2D array data in rows""" if data.shape != mask.shape: raise ValueError if not numpy.any(mask): return data x = num...
async def _readline(self, reader): """ Readline helper """ ret = await reader.readline() if len(ret) == 0 and reader.at_eof(): raise EOFError() return ret
Readline helper
Below is the the instruction that describes the task: ### Input: Readline helper ### Response: async def _readline(self, reader): """ Readline helper """ ret = await reader.readline() if len(ret) == 0 and reader.at_eof(): raise EOFError() return ret
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, subheader=None, track=False, header=None): """Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_...
Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unserialize methods convert the nested message dict into this format...
Below is the the instruction that describes the task: ### Input: Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unseria...
def _ParseSignatureIdentifiers(self, data_location, signature_identifiers): """Parses the signature identifiers. Args: data_location (str): location of the format specification file, for example, "signatures.conf". signature_identifiers (str): comma separated signature identifiers. R...
Parses the signature identifiers. Args: data_location (str): location of the format specification file, for example, "signatures.conf". signature_identifiers (str): comma separated signature identifiers. Raises: IOError: if the format specification file could not be read from ...
Below is the the instruction that describes the task: ### Input: Parses the signature identifiers. Args: data_location (str): location of the format specification file, for example, "signatures.conf". signature_identifiers (str): comma separated signature identifiers. Raises: I...
def pose2mat(pose): """ Converts pose to homogeneous matrix. Args: pose: a (pos, orn) tuple where pos is vec3 float cartesian, and orn is vec4 float quaternion. Returns: 4x4 homogeneous matrix """ homo_pose_mat = np.zeros((4, 4), dtype=np.float32) homo_pose_mat[...
Converts pose to homogeneous matrix. Args: pose: a (pos, orn) tuple where pos is vec3 float cartesian, and orn is vec4 float quaternion. Returns: 4x4 homogeneous matrix
Below is the the instruction that describes the task: ### Input: Converts pose to homogeneous matrix. Args: pose: a (pos, orn) tuple where pos is vec3 float cartesian, and orn is vec4 float quaternion. Returns: 4x4 homogeneous matrix ### Response: def pose2mat(pose): """ ...
def _open(self, skip=0): """ Perform HID initialization """ usb_device = self._get_usb_device(skip) if usb_device: usb_conf = usb_device.configurations[0] self._usb_int = usb_conf.interfaces[0][0] else: raise YubiKeyUSBHIDError('No USB YubiKey found')...
Perform HID initialization
Below is the the instruction that describes the task: ### Input: Perform HID initialization ### Response: def _open(self, skip=0): """ Perform HID initialization """ usb_device = self._get_usb_device(skip) if usb_device: usb_conf = usb_device.configurations[0] self....
def active_scalar(self): """Returns the active scalar as an array""" field, name = self.active_scalar_info if name is None: return None if field == POINT_DATA_FIELD: return self._point_scalar(name) elif field == CELL_DATA_FIELD: return self._ce...
Returns the active scalar as an array
Below is the the instruction that describes the task: ### Input: Returns the active scalar as an array ### Response: def active_scalar(self): """Returns the active scalar as an array""" field, name = self.active_scalar_info if name is None: return None if field == POINT_...
def get(self, sid): """ Constructs a CertificateContext :param sid: A string that uniquely identifies the Certificate. :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateC...
Constructs a CertificateContext :param sid: A string that uniquely identifies the Certificate. :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext
Below is the the instruction that describes the task: ### Input: Constructs a CertificateContext :param sid: A string that uniquely identifies the Certificate. :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext :rtype: twilio.rest.preview.deployed_devices.f...
def give_another_quote(q): """When you pass a quote character, returns you an another one if possible""" for qc in QUOTES: if qc != q: return qc else: raise ValueError(u'Could not find a different quote for {}'.format(q))
When you pass a quote character, returns you an another one if possible
Below is the the instruction that describes the task: ### Input: When you pass a quote character, returns you an another one if possible ### Response: def give_another_quote(q): """When you pass a quote character, returns you an another one if possible""" for qc in QUOTES: if qc != q: r...
def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. """ cmd = list(self.vasp_cmd) if self.auto_gamma: vi = VaspInput.from_directory(".") kpts = vi["KPOINTS"] if kpts.style == Kpo...
Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring.
Below is the the instruction that describes the task: ### Input: Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. ### Response: def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. ...
def _version_from_file( path_to_version, default_version=DEFAULT_VERSION, ): """for PyPI installed versions, just get data from file Args: path_to_version (str): abspath to dir where version.txt exists default_version (str): fallback version in case of error Returns: ...
for PyPI installed versions, just get data from file Args: path_to_version (str): abspath to dir where version.txt exists default_version (str): fallback version in case of error Returns: str: current working version
Below is the the instruction that describes the task: ### Input: for PyPI installed versions, just get data from file Args: path_to_version (str): abspath to dir where version.txt exists default_version (str): fallback version in case of error Returns: str: current working version ...
def polarisText(): """polarisText part of _TypedList objects """ def fget(self): _out = '' _n = '\n' if len(self): if self.parent: _out = '%s%s%s' % (_out, PolarisText( *self.parent).out,_n) ...
polarisText part of _TypedList objects
Below is the the instruction that describes the task: ### Input: polarisText part of _TypedList objects ### Response: def polarisText(): """polarisText part of _TypedList objects """ def fget(self): _out = '' _n = '\n' if len(self): if se...
def signingPayloadState(self, identifier=None): """ Special signing state where the the data for an attribute is hashed before signing :return: state to be used when signing """ if self.operation.get(TXN_TYPE) == ATTRIB: d = deepcopy(super().signingPayloadStat...
Special signing state where the the data for an attribute is hashed before signing :return: state to be used when signing
Below is the the instruction that describes the task: ### Input: Special signing state where the the data for an attribute is hashed before signing :return: state to be used when signing ### Response: def signingPayloadState(self, identifier=None): """ Special signing state where th...
def ml(line, cell=None): """Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser( prog='%ml', description=textwrap.dedent("""\ ...
Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell.
Below is the the instruction that describes the task: ### Input: Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell. ### Response: def ml(line, cell=None): """Implements the datalab cell magic for ...
def calculate_tensor_to_probability_map_output_shapes(operator): ''' Allowed input/output patterns are ONNX < 1.2 1. [1, C] ---> ---> A map 2. [1, C_1, ..., C_n] ---> A map ONNX >= 1.2 1. [N, C] ---> ---> A sequence of maps 2. [N, C_1, ..., C_n] ---> A sequence of maps ...
Allowed input/output patterns are ONNX < 1.2 1. [1, C] ---> ---> A map 2. [1, C_1, ..., C_n] ---> A map ONNX >= 1.2 1. [N, C] ---> ---> A sequence of maps 2. [N, C_1, ..., C_n] ---> A sequence of maps Note that N must be 1 currently if you're using ONNX<1.2 because old ZipMa...
Below is the the instruction that describes the task: ### Input: Allowed input/output patterns are ONNX < 1.2 1. [1, C] ---> ---> A map 2. [1, C_1, ..., C_n] ---> A map ONNX >= 1.2 1. [N, C] ---> ---> A sequence of maps 2. [N, C_1, ..., C_n] ---> A sequence of maps Note ...
def sample_transitions(self, batch_size, batch_info) -> Transitions: """ Sample batch of transitions and return them """ probs, indexes, tree_idxs = self.backend.sample_batch_transitions(batch_size) return self._get_transitions(probs, indexes, tree_idxs, batch_info)
Sample batch of transitions and return them
Below is the the instruction that describes the task: ### Input: Sample batch of transitions and return them ### Response: def sample_transitions(self, batch_size, batch_info) -> Transitions: """ Sample batch of transitions and return them """ probs, indexes, tree_idxs = self.backend.sample_batch_t...
def inet_to_str(inet): """Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address """ # First try ipv4 and then ipv6 try: return socket.inet_ntop(socket.AF_INET, inet) except ValueErro...
Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address
Below is the the instruction that describes the task: ### Input: Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address ### Response: def inet_to_str(inet): """Convert inet object to a string A...
def get_oauth_data(self, code, client_id, client_secret, state): ''' Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret ...
Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of the associated app Returns: A HSAccessTokenAuth...
Below is the the instruction that describes the task: ### Input: Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of...
def to_file(self, output_file, smooth_fwhm=0, outdtype=None): """Save the Numpy array created from to_matrix function to the output_file. Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want) data: Numpy array with shape N x prod(vol.shape) ...
Save the Numpy array created from to_matrix function to the output_file. Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want) data: Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors. mas...
Below is the the instruction that describes the task: ### Input: Save the Numpy array created from to_matrix function to the output_file. Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want) data: Numpy array with shape N x prod(vol.shape) ...
def run_thread(self, usnap=.2, daemon=True): """run thread with data """ # self.stream_data() # Unless other changes are made this would limit to localhost only. try: gps3_data_thread = Thread(target=self.unpack_data, args={usnap: usnap}, daemon=daemon) except TypeErr...
run thread with data
Below is the the instruction that describes the task: ### Input: run thread with data ### Response: def run_thread(self, usnap=.2, daemon=True): """run thread with data """ # self.stream_data() # Unless other changes are made this would limit to localhost only. try: gps3...
def plot_volume_exposures_longshort(longed_threshold, shorted_threshold, percentile, ax=None): """ Plots outputs of compute_volume_exposures as line graphs Parameters ---------- longed_threshold, shorted_threshold : pd.Series Series of longed and shorted ...
Plots outputs of compute_volume_exposures as line graphs Parameters ---------- longed_threshold, shorted_threshold : pd.Series Series of longed and shorted volume exposures (output of compute_volume_exposures). percentile : float Percentile to use when computing and plotting vo...
Below is the the instruction that describes the task: ### Input: Plots outputs of compute_volume_exposures as line graphs Parameters ---------- longed_threshold, shorted_threshold : pd.Series Series of longed and shorted volume exposures (output of compute_volume_exposures). percen...
def wait_for_states(self, timeout=40, *states): """ Wait until port reaches one of the requested states. :param timeout: max time to wait for requested port states. """ state = self.get_attribute('state') for _ in range(timeout): if state in states: ...
Wait until port reaches one of the requested states. :param timeout: max time to wait for requested port states.
Below is the the instruction that describes the task: ### Input: Wait until port reaches one of the requested states. :param timeout: max time to wait for requested port states. ### Response: def wait_for_states(self, timeout=40, *states): """ Wait until port reaches one of the requested states. ...
def shorten(self, url, custom_url = None, log_stat = False): ''' Shorten an URL using `is.gd - v.gd url shortener service <http://is.gd/developers.php>`_. :param url: URL that had to be shortened :type url: str. :param custom_url: if spec...
Shorten an URL using `is.gd - v.gd url shortener service <http://is.gd/developers.php>`_. :param url: URL that had to be shortened :type url: str. :param custom_url: if specified, the url generated will be http://is.gd/<custom_url> (or http://v.gd/<custom_ur...
Below is the the instruction that describes the task: ### Input: Shorten an URL using `is.gd - v.gd url shortener service <http://is.gd/developers.php>`_. :param url: URL that had to be shortened :type url: str. :param custom_url: if specified, the url g...
def surface_evaluate_barycentric(surface, point): """Image for :meth`.Surface.evaluate_barycentric` docstring.""" if NO_IMAGES: return ax = surface.plot(256) ax.plot( point[0, :], point[1, :], color="black", linestyle="None", marker="o" ) ax.axis("scaled") ax.set_xlim(-0.125...
Image for :meth`.Surface.evaluate_barycentric` docstring.
Below is the the instruction that describes the task: ### Input: Image for :meth`.Surface.evaluate_barycentric` docstring. ### Response: def surface_evaluate_barycentric(surface, point): """Image for :meth`.Surface.evaluate_barycentric` docstring.""" if NO_IMAGES: return ax = surface.plot(256)...
def get_max_network_adapters(self, chipset): """Maximum total number of network adapters associated with every :py:class:`IMachine` instance. in chipset of type :class:`ChipsetType` The chipset type to get the value for. return max_network_adapters of type int ...
Maximum total number of network adapters associated with every :py:class:`IMachine` instance. in chipset of type :class:`ChipsetType` The chipset type to get the value for. return max_network_adapters of type int The maximum total number of network adapters allowed.
Below is the the instruction that describes the task: ### Input: Maximum total number of network adapters associated with every :py:class:`IMachine` instance. in chipset of type :class:`ChipsetType` The chipset type to get the value for. return max_network_adapters of type int...
def _get_host(self): """ Returns the host address for an instance of Blob Store service from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) host = services['predix-blobstore'][0]['credentials...
Returns the host address for an instance of Blob Store service from environment inspection.
Below is the the instruction that describes the task: ### Input: Returns the host address for an instance of Blob Store service from environment inspection. ### Response: def _get_host(self): """ Returns the host address for an instance of Blob Store service from environment inspect...
def chart(self, x=None, y=None, chart_type=None, opts=None, style=None, label=None, options={}, **kwargs): """ Get a chart """ try: self.chart_obj = self._chart(x, y, chart_type, opts, style, label, options=options, **kwargs) except Exception as e: self.err(e, self.chart, "Can not create...
Get a chart
Below is the the instruction that describes the task: ### Input: Get a chart ### Response: def chart(self, x=None, y=None, chart_type=None, opts=None, style=None, label=None, options={}, **kwargs): """ Get a chart """ try: self.chart_obj = self._chart(x, y, chart_type, opts, style, label, ...
def sales_payment_summary(): ''' Summarises paid items and payments. ''' def value_or_zero(aggregate, key): return aggregate[key] or 0 def sum_amount(payment_set): a = payment_set.values("amount").aggregate(total=Sum("amount")) return value_or_zero(a, "total") headings = ["Cat...
Summarises paid items and payments.
Below is the the instruction that describes the task: ### Input: Summarises paid items and payments. ### Response: def sales_payment_summary(): ''' Summarises paid items and payments. ''' def value_or_zero(aggregate, key): return aggregate[key] or 0 def sum_amount(payment_set): a = pa...
def run_thread(self): """Run the main thread.""" self._run_thread = True self._thread.setDaemon(True) self._thread.start()
Run the main thread.
Below is the the instruction that describes the task: ### Input: Run the main thread. ### Response: def run_thread(self): """Run the main thread.""" self._run_thread = True self._thread.setDaemon(True) self._thread.start()
def _shock_create(self, h, shock_type, shock_index, shock_value, shock_dir, irf_intervals): """ Function creates shocks based on desired specification Parameters ---------- h : int How many steps ahead to forecast shock_type : None or str Type of shock; ...
Function creates shocks based on desired specification Parameters ---------- h : int How many steps ahead to forecast shock_type : None or str Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock) s...
Below is the the instruction that describes the task: ### Input: Function creates shocks based on desired specification Parameters ---------- h : int How many steps ahead to forecast shock_type : None or str Type of shock; options include None, 'Cov' (simula...
def update(self, session, title=None, bulletin=None, desc=None): '''taobao.shop.remainshowcase.get 获取卖家店铺剩余橱窗数量 目前只支持标题、公告和描述的更新''' request = TOPRequest('taobao.shop.remainshowcase.get') if title!=None: request['title'] = title if bulletin!=None: request['bulletin'] = bu...
taobao.shop.remainshowcase.get 获取卖家店铺剩余橱窗数量 目前只支持标题、公告和描述的更新
Below is the the instruction that describes the task: ### Input: taobao.shop.remainshowcase.get 获取卖家店铺剩余橱窗数量 目前只支持标题、公告和描述的更新 ### Response: def update(self, session, title=None, bulletin=None, desc=None): '''taobao.shop.remainshowcase.get 获取卖家店铺剩余橱窗数量 目前只支持标题、公告和描述的更新''' ...
def get_mac_acl_for_intf_output_interface_ingress_policy_policy_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") config = get_mac_acl_for_intf output = ET.SubElement(get_mac_acl_for_in...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_mac_acl_for_intf_output_interface_ingress_policy_policy_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_ma...
def get_repository_config(self, repository): """Get config dictionary for the given repository. If the repository section is not found in the config file, return ``None``. If the file is invalid, raise :exc:`configparser.Error`. Otherwise return a dictionary with: * `...
Get config dictionary for the given repository. If the repository section is not found in the config file, return ``None``. If the file is invalid, raise :exc:`configparser.Error`. Otherwise return a dictionary with: * ``'repository'`` -- the repository URL * ``'usern...
Below is the the instruction that describes the task: ### Input: Get config dictionary for the given repository. If the repository section is not found in the config file, return ``None``. If the file is invalid, raise :exc:`configparser.Error`. Otherwise return a dictionary with:...