code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def randn_ktensor(shape, rank, norm=None, random_state=None): """ Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor n...
Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor norm : float or None, optional (defaults: None) If not None, the fa...
Below is the the instruction that describes the task: ### Input: Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor norm :...
def get_url_base_from_url_token( self, url_api_token: str = "https://id.api.isogeo.com/oauth/token" ): """Returns the Isogeo API root URL (which is not included into credentials file) from the token URL (which is always included). :param url_api_token str: url to Isogeo API ID token...
Returns the Isogeo API root URL (which is not included into credentials file) from the token URL (which is always included). :param url_api_token str: url to Isogeo API ID token generator
Below is the the instruction that describes the task: ### Input: Returns the Isogeo API root URL (which is not included into credentials file) from the token URL (which is always included). :param url_api_token str: url to Isogeo API ID token generator ### Response: def get_url_base_from_url_token...
def qwarp_apply(dset_from,dset_warp,affine=None,warp_suffix='_warp',master='WARP',interp=None,prefix=None): '''applies the transform from a previous qwarp Uses the warp parameters from the dataset listed in ``dset_warp`` (usually the dataset name ends in ``_WARP``) to the dataset ``dset_from``. If a ``...
applies the transform from a previous qwarp Uses the warp parameters from the dataset listed in ``dset_warp`` (usually the dataset name ends in ``_WARP``) to the dataset ``dset_from``. If a ``.1D`` file is given in the ``affine`` parameter, it will be applied simultaneously with the qwarp. If ...
Below is the the instruction that describes the task: ### Input: applies the transform from a previous qwarp Uses the warp parameters from the dataset listed in ``dset_warp`` (usually the dataset name ends in ``_WARP``) to the dataset ``dset_from``. If a ``.1D`` file is given in the ``affine`` para...
def _count(self, cmd, collation=None, session=None): """Internal count helper.""" def _cmd(session, server, sock_info, slave_ok): res = self._command( sock_info, cmd, slave_ok, allowable_errors=["ns missing"], co...
Internal count helper.
Below is the the instruction that describes the task: ### Input: Internal count helper. ### Response: def _count(self, cmd, collation=None, session=None): """Internal count helper.""" def _cmd(session, server, sock_info, slave_ok): res = self._command( sock_info, ...
def subroute(self, *components): """ See `txspinneret.route.subroute`. This decorator can be stacked with itself to specify multiple routes with a single handler. """ def _factory(f): self._addRoute(f, subroute(*components)) return f retur...
See `txspinneret.route.subroute`. This decorator can be stacked with itself to specify multiple routes with a single handler.
Below is the the instruction that describes the task: ### Input: See `txspinneret.route.subroute`. This decorator can be stacked with itself to specify multiple routes with a single handler. ### Response: def subroute(self, *components): """ See `txspinneret.route.subroute`. ...
def doc_type(self, *doc_type, **kwargs): """ Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``Document``. You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead o...
Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``Document``. You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class. If no doc_type is supplied any info...
Below is the the instruction that describes the task: ### Input: Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``Document``. You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used i...
def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' packet = cls() # Convert to ConstBitStream (if not already provided) if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): ...
Parse the given packet and update properties accordingly
Below is the the instruction that describes the task: ### Input: Parse the given packet and update properties accordingly ### Response: def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' packet = cls() # Convert to ConstBitStrea...
def transform(self, traj): """ Maps an mdtraj Trajectory object to the selected output features Parameters ---------- traj : mdtraj Trajectory Trajectory object used as an input Returns ------- out : ndarray((T, n), dtype=float32) ...
Maps an mdtraj Trajectory object to the selected output features Parameters ---------- traj : mdtraj Trajectory Trajectory object used as an input Returns ------- out : ndarray((T, n), dtype=float32) Output features: For each of T time steps in t...
Below is the the instruction that describes the task: ### Input: Maps an mdtraj Trajectory object to the selected output features Parameters ---------- traj : mdtraj Trajectory Trajectory object used as an input Returns ------- out : ndarray((T, n), dtyp...
def _get_acf_peakheights(lags, acf, npeaks=20, searchinterval=1): '''This calculates the relative peak heights for first npeaks in ACF. Usually, the first peak or the second peak (if its peak height > first peak) corresponds to the correct lag. When we know the correct lag, the period is then:: ...
This calculates the relative peak heights for first npeaks in ACF. Usually, the first peak or the second peak (if its peak height > first peak) corresponds to the correct lag. When we know the correct lag, the period is then:: bestperiod = time[lags == bestlag] - time[0] Parameters ------...
Below is the the instruction that describes the task: ### Input: This calculates the relative peak heights for first npeaks in ACF. Usually, the first peak or the second peak (if its peak height > first peak) corresponds to the correct lag. When we know the correct lag, the period is then:: be...
def initialize(): """ Try to get EC2 instance-id and AZ if running on EC2 by querying http://169.254.169.254/latest/meta-data/. If not continue. """ global runtime_context try: runtime_context = {} r = urlopen('http://169.254.169.254/latest/meta-data/instance-id', timeout=1...
Try to get EC2 instance-id and AZ if running on EC2 by querying http://169.254.169.254/latest/meta-data/. If not continue.
Below is the the instruction that describes the task: ### Input: Try to get EC2 instance-id and AZ if running on EC2 by querying http://169.254.169.254/latest/meta-data/. If not continue. ### Response: def initialize(): """ Try to get EC2 instance-id and AZ if running on EC2 by querying http://...
def _parse_discovery_information( self, content): """* parse discovery information from one row on the TNS results page* **Key Arguments:** - ``content`` -- a table row from the TNS results page. **Return:** - ``discoveryData`` -- dictionary of r...
* parse discovery information from one row on the TNS results page* **Key Arguments:** - ``content`` -- a table row from the TNS results page. **Return:** - ``discoveryData`` -- dictionary of results - ``TNSId`` -- the unique TNS id for the transient
Below is the the instruction that describes the task: ### Input: * parse discovery information from one row on the TNS results page* **Key Arguments:** - ``content`` -- a table row from the TNS results page. **Return:** - ``discoveryData`` -- dictionary of results ...
def get_found_param(injfile, bankfile, trigfile, param, ifo, args=None): """ Translates some popular trigger parameters into functions that calculate them from an hdf found injection file Parameters ---------- injfile: hdf5 File object Injection file of format known to ANitz (DOCUMENTME...
Translates some popular trigger parameters into functions that calculate them from an hdf found injection file Parameters ---------- injfile: hdf5 File object Injection file of format known to ANitz (DOCUMENTME) bankfile: hdf5 File object or None Template bank file trigfile: hdf...
Below is the the instruction that describes the task: ### Input: Translates some popular trigger parameters into functions that calculate them from an hdf found injection file Parameters ---------- injfile: hdf5 File object Injection file of format known to ANitz (DOCUMENTME) bankfile: ...
def AgregarViaje(self, cuit_transportista=None, cuit_conductor=None, fecha_inicio_viaje=None, distancia_km=None, **kwargs): "Agrega la información referente al viaje del remito electrónico cárnico" self.remito['viaje'] = {'cuitTransportista': cuit_transportista, 'cuitCon...
Agrega la información referente al viaje del remito electrónico cárnico
Below is the the instruction that describes the task: ### Input: Agrega la información referente al viaje del remito electrónico cárnico ### Response: def AgregarViaje(self, cuit_transportista=None, cuit_conductor=None, fecha_inicio_viaje=None, distancia_km=None, **kwargs): "Agrega la información referente...
def getCountLT(self, item): """Return number of elements less than *item*.""" index = bisect.bisect_left(self._list, item) return index
Return number of elements less than *item*.
Below is the the instruction that describes the task: ### Input: Return number of elements less than *item*. ### Response: def getCountLT(self, item): """Return number of elements less than *item*.""" index = bisect.bisect_left(self._list, item) return index
def read_locations(filename): """Pull locations from a user's config file. Args: filename (str): Config file to parse Returns: dict: List of locations from config file """ data = ConfigParser() if filename == '-': data.read_file(sys.stdin) else: data.read(fi...
Pull locations from a user's config file. Args: filename (str): Config file to parse Returns: dict: List of locations from config file
Below is the the instruction that describes the task: ### Input: Pull locations from a user's config file. Args: filename (str): Config file to parse Returns: dict: List of locations from config file ### Response: def read_locations(filename): """Pull locations from a user's config fi...
def rest_add_filters(self, data): """ Adds list of dicts :param data: list of dicts :return: """ for _filter in data: filter_class = map_args_filter.get(_filter["opr"], None) if filter_class: self.add_filter(_filter["col"], fil...
Adds list of dicts :param data: list of dicts :return:
Below is the the instruction that describes the task: ### Input: Adds list of dicts :param data: list of dicts :return: ### Response: def rest_add_filters(self, data): """ Adds list of dicts :param data: list of dicts :return: """ for _filter in...
def _symlink_remote_lib(self, gopath, go_remote_lib, required_links): """Creates symlinks from the given gopath to the source files of the given remote lib. Also duplicates directory structure leading to source files of package within gopath, in order to provide isolation to the package. Adds the syml...
Creates symlinks from the given gopath to the source files of the given remote lib. Also duplicates directory structure leading to source files of package within gopath, in order to provide isolation to the package. Adds the symlinks to the source files to required_links.
Below is the the instruction that describes the task: ### Input: Creates symlinks from the given gopath to the source files of the given remote lib. Also duplicates directory structure leading to source files of package within gopath, in order to provide isolation to the package. Adds the symlinks to ...
def _http_status_in_category(status, category): """ Checks whether a HTTP status code is in the category denoted by the hundreds digit. """ assert category < 10, 'HTTP status category must be a one-digit int!' cat = category * 100 return status >= cat and status ...
Checks whether a HTTP status code is in the category denoted by the hundreds digit.
Below is the the instruction that describes the task: ### Input: Checks whether a HTTP status code is in the category denoted by the hundreds digit. ### Response: def _http_status_in_category(status, category): """ Checks whether a HTTP status code is in the category denoted by the ...
def get_payload(self): """Return Payload.""" return bytes( [self.major_version >> 8 & 255, self.major_version & 255, self.minor_version >> 8 & 255, self.minor_version & 255])
Return Payload.
Below is the the instruction that describes the task: ### Input: Return Payload. ### Response: def get_payload(self): """Return Payload.""" return bytes( [self.major_version >> 8 & 255, self.major_version & 255, self.minor_version >> 8 & 255, self.minor_version & 255])
def update(self, validate=False): """ Update the instance's state information by making a call to fetch the current instance attributes from the service. :type validate: bool :param validate: By default, if EC2 returns no data about the instance the upda...
Update the instance's state information by making a call to fetch the current instance attributes from the service. :type validate: bool :param validate: By default, if EC2 returns no data about the instance the update method returns quietly. If ...
Below is the the instruction that describes the task: ### Input: Update the instance's state information by making a call to fetch the current instance attributes from the service. :type validate: bool :param validate: By default, if EC2 returns no data about the in...
def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. co...
List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. v...
Below is the the instruction that describes the task: ### Input: List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: ...
def kernel(): """ Handle linux kernel update """ print('================================') print(' WARNING: upgrading the kernel') print('================================') time.sleep(5) print('-[kernel]----------') cmd('rpi-update', True) print(' >> You MUST reboot to load the new kernel <<')
Handle linux kernel update
Below is the the instruction that describes the task: ### Input: Handle linux kernel update ### Response: def kernel(): """ Handle linux kernel update """ print('================================') print(' WARNING: upgrading the kernel') print('================================') time.sleep(5) print('-[ker...
def add_lnTo(self, x, y): """Return a newly created `a:lnTo` subtree with end point *(x, y)*. The new `a:lnTo` element is appended to this `a:path` element. """ lnTo = self._add_lnTo() pt = lnTo._add_pt() pt.x, pt.y = x, y return lnTo
Return a newly created `a:lnTo` subtree with end point *(x, y)*. The new `a:lnTo` element is appended to this `a:path` element.
Below is the the instruction that describes the task: ### Input: Return a newly created `a:lnTo` subtree with end point *(x, y)*. The new `a:lnTo` element is appended to this `a:path` element. ### Response: def add_lnTo(self, x, y): """Return a newly created `a:lnTo` subtree with end point *(x, y)...
def faces(self, sites, permutation=None): """ Returns the list of faces of this coordination geometry. Each face is given as a list of its vertices coordinates. """ if permutation is None: coords = [site.coords for site in sites] else: coords = [si...
Returns the list of faces of this coordination geometry. Each face is given as a list of its vertices coordinates.
Below is the the instruction that describes the task: ### Input: Returns the list of faces of this coordination geometry. Each face is given as a list of its vertices coordinates. ### Response: def faces(self, sites, permutation=None): """ Returns the list of faces of this coordination geom...
def apply(self, topology, references_file=None, use_residue_map=True, assert_bond_params=True, assert_angle_params=True, assert_dihedral_params=True, assert_improper_params=False, *args, **kwargs): """Apply the force field to a molecular structure Parameters ...
Apply the force field to a molecular structure Parameters ---------- topology : openmm.app.Topology or parmed.Structure or mbuild.Compound Molecular structure to apply the force field to references_file : str, optional, default=None Name of file where force field...
Below is the the instruction that describes the task: ### Input: Apply the force field to a molecular structure Parameters ---------- topology : openmm.app.Topology or parmed.Structure or mbuild.Compound Molecular structure to apply the force field to references_file : s...
def process_tables(app, docname, source): """ Convert markdown tables to html, since recommonmark can't. This requires 3 steps: Snip out table sections from the markdown Convert them to html Replace the old markdown table with an html table This function is called by sphinx for each...
Convert markdown tables to html, since recommonmark can't. This requires 3 steps: Snip out table sections from the markdown Convert them to html Replace the old markdown table with an html table This function is called by sphinx for each document. `source` is a 1-item list. To update the do...
Below is the the instruction that describes the task: ### Input: Convert markdown tables to html, since recommonmark can't. This requires 3 steps: Snip out table sections from the markdown Convert them to html Replace the old markdown table with an html table This function is called by ...
def resolve_path(self, path, root_id='me/skydrive', objects=False, listdir_limit=500): '''Return id (or metadata) of an object, specified by chain (iterable or fs-style path string) of "name" attributes of its ancestors, or raises DoesNotExists error. Requires many calls to resolve each name in path, so u...
Return id (or metadata) of an object, specified by chain (iterable or fs-style path string) of "name" attributes of its ancestors, or raises DoesNotExists error. Requires many calls to resolve each name in path, so use with care. root_id parameter allows to specify path relative to some folder_id (d...
Below is the the instruction that describes the task: ### Input: Return id (or metadata) of an object, specified by chain (iterable or fs-style path string) of "name" attributes of its ancestors, or raises DoesNotExists error. Requires many calls to resolve each name in path, so use with care. root_...
def _select_ontology(self, line): """try to select an ontology NP: the actual load from FS is in <_load_ontology> """ try: var = int(line) # it's a string if var in range(1, len(self.all_ontologies)+1): self._load_ontology(self.all_ontologies[var-1]) exce...
try to select an ontology NP: the actual load from FS is in <_load_ontology>
Below is the the instruction that describes the task: ### Input: try to select an ontology NP: the actual load from FS is in <_load_ontology> ### Response: def _select_ontology(self, line): """try to select an ontology NP: the actual load from FS is in <_load_ontology> """ try: var = in...
def search_template_get(id, hosts=None, profile=None): ''' .. versionadded:: 2017.7.0 Obtain existing search template definition. id Template ID CLI example:: salt myminion elasticsearch.search_template_get mytemplate ''' es = _get_instance(hosts, profile) try: ...
.. versionadded:: 2017.7.0 Obtain existing search template definition. id Template ID CLI example:: salt myminion elasticsearch.search_template_get mytemplate
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2017.7.0 Obtain existing search template definition. id Template ID CLI example:: salt myminion elasticsearch.search_template_get mytemplate ### Response: def search_template_get(id, hosts=None, profi...
def download_source(version): """ Download Spark version. Uses same name as release tag without the leading 'v'. :param version: Version number to download. :return: None """ local_filename = 'v{}.zip'.format(Spark.svm_version_path(version)) Spark.download(Spark.s...
Download Spark version. Uses same name as release tag without the leading 'v'. :param version: Version number to download. :return: None
Below is the the instruction that describes the task: ### Input: Download Spark version. Uses same name as release tag without the leading 'v'. :param version: Version number to download. :return: None ### Response: def download_source(version): """ Download Spark version. Uses same...
def handle_no_start_state(self): """Handles the situation, when no start state exists during execution The method waits, until a transition is created. It then checks again for an existing start state and waits again, if this is not the case. It returns the None state if the the state machine w...
Handles the situation, when no start state exists during execution The method waits, until a transition is created. It then checks again for an existing start state and waits again, if this is not the case. It returns the None state if the the state machine was stopped.
Below is the the instruction that describes the task: ### Input: Handles the situation, when no start state exists during execution The method waits, until a transition is created. It then checks again for an existing start state and waits again, if this is not the case. It returns the None state i...
def SetPeSubsystem(fd, console=True): """Takes file like obj and returns (offset, value) for the PE subsystem.""" current_pos = fd.tell() fd.seek(0x3c) # _IMAGE_DOS_HEADER.e_lfanew header_offset = struct.unpack("<I", fd.read(4))[0] # _IMAGE_NT_HEADERS.OptionalHeader.Subsystem ( 0x18 + 0x44) subsystem_offse...
Takes file like obj and returns (offset, value) for the PE subsystem.
Below is the the instruction that describes the task: ### Input: Takes file like obj and returns (offset, value) for the PE subsystem. ### Response: def SetPeSubsystem(fd, console=True): """Takes file like obj and returns (offset, value) for the PE subsystem.""" current_pos = fd.tell() fd.seek(0x3c) # _IMAG...
def read(self): """ Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data structures: - idfobjects : list - model : list - idd_info : list - idd_index : dict """ ...
Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data structures: - idfobjects : list - model : list - idd_info : list - idd_index : dict
Below is the the instruction that describes the task: ### Input: Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data structures: - idfobjects : list - model : list - idd_info : list ...
def cli(env, identifier): """Remove SSL certificate.""" manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.remove_certificate(identifier)
Remove SSL certificate.
Below is the the instruction that describes the task: ### Input: Remove SSL certificate. ### Response: def cli(env, identifier): """Remove SSL certificate.""" manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbor...
def _ask_which_gist(self, matches): """ Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist """ # ask user which gist t...
Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist
Below is the the instruction that describes the task: ### Input: Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist ### Response: def _ask_which_...
def next_history(self, e): # (C-n) u'''Move forward through the history list, fetching the next command. ''' self._history.next_history(self.l_buffer) self.finalize()
u'''Move forward through the history list, fetching the next command.
Below is the the instruction that describes the task: ### Input: u'''Move forward through the history list, fetching the next command. ### Response: def next_history(self, e): # (C-n) u'''Move forward through the history list, fetching the next command. ''' self._history.next_h...
async def start_client(self, sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None): """Start a client WS conne...
Start a client WS connection on this socket. Returns: the AcceptConnection message.
Below is the the instruction that describes the task: ### Input: Start a client WS connection on this socket. Returns: the AcceptConnection message. ### Response: async def start_client(self, sock: anyio.abc.SocketStream, addr, ...
def get_presence(self, user_name): """ https://api.slack.com/methods/users.getPresence """ user_id = self.get_id_by_name(user_name) self.params.update({ 'user': user_id, }) return FromUrl('https://slack.com/api/users.getPresence', self._requests)(data=self...
https://api.slack.com/methods/users.getPresence
Below is the the instruction that describes the task: ### Input: https://api.slack.com/methods/users.getPresence ### Response: def get_presence(self, user_name): """ https://api.slack.com/methods/users.getPresence """ user_id = self.get_id_by_name(user_name) self.params.update({ ...
def is_url(): """ Validates that a fields value is a valid URL. """ # Stolen from Django regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost......
Validates that a fields value is a valid URL.
Below is the the instruction that describes the task: ### Input: Validates that a fields value is a valid URL. ### Response: def is_url(): """ Validates that a fields value is a valid URL. """ # Stolen from Django regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r...
def get_multi_causal_downstream(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]): """Get the union of all of the 2-level deep causal downstream subgraphs from the nbunch. :param pybel.BELGraph graph: A BEL graph :param nbunch: A BEL node or list of BEL nodes :return: A subgraph of the original B...
Get the union of all of the 2-level deep causal downstream subgraphs from the nbunch. :param pybel.BELGraph graph: A BEL graph :param nbunch: A BEL node or list of BEL nodes :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph
Below is the the instruction that describes the task: ### Input: Get the union of all of the 2-level deep causal downstream subgraphs from the nbunch. :param pybel.BELGraph graph: A BEL graph :param nbunch: A BEL node or list of BEL nodes :return: A subgraph of the original BEL graph :rtype: pybel....
def write_configs(self): """Generate the configurations needed for pipes.""" utils.banner("Generating Configs") if not self.runway_dir: app_configs = configs.process_git_configs(git_short=self.git_short) else: app_configs = configs.process_runway_configs(runway_di...
Generate the configurations needed for pipes.
Below is the the instruction that describes the task: ### Input: Generate the configurations needed for pipes. ### Response: def write_configs(self): """Generate the configurations needed for pipes.""" utils.banner("Generating Configs") if not self.runway_dir: app_configs = conf...
def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False): "Start to send response" if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.status = status self.disabledeflate = di...
Start to send response
Below is the the instruction that describes the task: ### Input: Start to send response ### Response: def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False): "Start to send response" if self._sendHeaders: raise HttpProtocolException('C...
def is_commentable(obj_or_class): """ :param obj_or_class: a class or instance """ if isinstance(obj_or_class, type): return issubclass(obj_or_class, Commentable) if not isinstance(obj_or_class, Commentable): return False if obj_or_class.id is None: return False re...
:param obj_or_class: a class or instance
Below is the the instruction that describes the task: ### Input: :param obj_or_class: a class or instance ### Response: def is_commentable(obj_or_class): """ :param obj_or_class: a class or instance """ if isinstance(obj_or_class, type): return issubclass(obj_or_class, Commentable) if ...
def get_sources(self, kind='all'): """ Extract the sources contained in the source models by optionally filtering and splitting them, depending on the passed parameter. """ assert kind in ('all', 'indep', 'mutex'), kind sources = [] for sm in self.source_models: ...
Extract the sources contained in the source models by optionally filtering and splitting them, depending on the passed parameter.
Below is the the instruction that describes the task: ### Input: Extract the sources contained in the source models by optionally filtering and splitting them, depending on the passed parameter. ### Response: def get_sources(self, kind='all'): """ Extract the sources contained in the source...
def return_document(self, doc_id, branch='master', commit_sha=None, return_WIP_map=False): """Return the blob[0] contents of the given doc_id, blob[1] the SHA1 of the HEAD of branch (or `commit_sha`) blob[2] dictionary of WIPs for this doc. If the doc_id does not exis...
Return the blob[0] contents of the given doc_id, blob[1] the SHA1 of the HEAD of branch (or `commit_sha`) blob[2] dictionary of WIPs for this doc. If the doc_id does not exist, it returns the empty string. If `commit_sha` is provided, that will be checked out and retu...
Below is the the instruction that describes the task: ### Input: Return the blob[0] contents of the given doc_id, blob[1] the SHA1 of the HEAD of branch (or `commit_sha`) blob[2] dictionary of WIPs for this doc. If the doc_id does not exist, it returns the empty string. ...
def retrieve_remote_content( id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None, ): """Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_k...
Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle a...
Below is the the instruction that describes the task: ### Input: Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used ...
def _aload32(ins): ''' Load a 32 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('call __ILOAD32') output.append('push de') output.append('push hl') REQUIRES.add('iload32.asm') ...
Load a 32 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
Below is the the instruction that describes the task: ### Input: Load a 32 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ### Response: def _aload32(ins): ''' Load a 32 bit value from a memory address If 2nd arg. start with '*', it is always t...
def _print_single_file(self, path, apps_models): """ Print apps_models which contains a list of 2-tuples containing apps and their models into a single file. """ if path: outfile = codecs.open(path, 'w', encoding='utf-8') self._print = lambda s: outfile.wr...
Print apps_models which contains a list of 2-tuples containing apps and their models into a single file.
Below is the the instruction that describes the task: ### Input: Print apps_models which contains a list of 2-tuples containing apps and their models into a single file. ### Response: def _print_single_file(self, path, apps_models): """ Print apps_models which contains a list of 2-tuples co...
def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0,...
Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value ...
Below is the the instruction that describes the task: ### Input: Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to...
def _execute_hooks(self, element): """ Executes finalize hooks """ if self.hooks and self.finalize_hooks: self.param.warning( "Supply either hooks or finalize_hooks not both, " "using hooks and ignoring finalize_hooks.") hooks = self.ho...
Executes finalize hooks
Below is the the instruction that describes the task: ### Input: Executes finalize hooks ### Response: def _execute_hooks(self, element): """ Executes finalize hooks """ if self.hooks and self.finalize_hooks: self.param.warning( "Supply either hooks or fi...
def view_servers(self): """ Requires: account ID (taken from Client object) Returns: a list of Server objects Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Get """ endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/acco...
Requires: account ID (taken from Client object) Returns: a list of Server objects Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Get
Below is the the instruction that describes the task: ### Input: Requires: account ID (taken from Client object) Returns: a list of Server objects Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Get ### Response: def view_servers(self): """ Requires: a...
def do_mumble(self, args): """Mumbles what you tell me to.""" repetitions = args.repeat or 1 for i in range(min(repetitions, self.maxrepeats)): output = [] if random.random() < .33: output.append(random.choice(self.MUMBLE_FIRST)) for word in ar...
Mumbles what you tell me to.
Below is the the instruction that describes the task: ### Input: Mumbles what you tell me to. ### Response: def do_mumble(self, args): """Mumbles what you tell me to.""" repetitions = args.repeat or 1 for i in range(min(repetitions, self.maxrepeats)): output = [] if ...
def fill_transaction_defaults(web3, transaction): """ if web3 is None, fill as much as possible while offline """ defaults = {} for key, default_getter in TRANSACTION_DEFAULTS.items(): if key not in transaction: if callable(default_getter): if web3 is not None: ...
if web3 is None, fill as much as possible while offline
Below is the the instruction that describes the task: ### Input: if web3 is None, fill as much as possible while offline ### Response: def fill_transaction_defaults(web3, transaction): """ if web3 is None, fill as much as possible while offline """ defaults = {} for key, default_getter in TRANS...
def typedefs( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of typedef declarations, that are matched defined criteria""" return ( ...
returns a set of typedef declarations, that are matched defined criteria
Below is the the instruction that describes the task: ### Input: returns a set of typedef declarations, that are matched defined criteria ### Response: def typedefs( self, name=None, function=None, header_dir=None, header_file=None, re...
def issimp(s, full=False): """ Detect text is whether Simplified Chinese or Traditional Chinese. Returns True for Simplified; False for Traditional; None for unknown. If full=False, it returns once first simplified- or traditional-only character is encountered, so it's for quick and rough identifica...
Detect text is whether Simplified Chinese or Traditional Chinese. Returns True for Simplified; False for Traditional; None for unknown. If full=False, it returns once first simplified- or traditional-only character is encountered, so it's for quick and rough identification; else, it compares the count a...
Below is the the instruction that describes the task: ### Input: Detect text is whether Simplified Chinese or Traditional Chinese. Returns True for Simplified; False for Traditional; None for unknown. If full=False, it returns once first simplified- or traditional-only character is encountered, so it's ...
def safe_add_file(filename, app): """ Adds files to builder resources only, if the given filename was not already registered. Needed mainly for tests to avoid multiple registration of the same file and therefore also multiple execution of e.g. a javascript file during page load. :param filename: fi...
Adds files to builder resources only, if the given filename was not already registered. Needed mainly for tests to avoid multiple registration of the same file and therefore also multiple execution of e.g. a javascript file during page load. :param filename: filename to remove :param app: app object ...
Below is the the instruction that describes the task: ### Input: Adds files to builder resources only, if the given filename was not already registered. Needed mainly for tests to avoid multiple registration of the same file and therefore also multiple execution of e.g. a javascript file during page load. ...
def _get_erred_shared_settings_module(self): """ Returns a LinkList based module which contains link to shared service setting instances in ERRED state. """ result_module = modules.LinkList(title=_('Shared provider settings in erred state')) result_module.template = 'admin/dashbo...
Returns a LinkList based module which contains link to shared service setting instances in ERRED state.
Below is the the instruction that describes the task: ### Input: Returns a LinkList based module which contains link to shared service setting instances in ERRED state. ### Response: def _get_erred_shared_settings_module(self): """ Returns a LinkList based module which contains link to shared servi...
def execute(self, timeSeries): """Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :r...
Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :rtype: TimeSeries :raise: Ra...
Below is the the instruction that describes the task: ### Input: Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth...
def build_variant_query(self, query=None, category='snv', variant_type=['clinical']): """Build a mongo query across multiple cases. Translate query options from a form into a complete mongo query dictionary. Beware that unindexed queries against a large variant collection will be extrem...
Build a mongo query across multiple cases. Translate query options from a form into a complete mongo query dictionary. Beware that unindexed queries against a large variant collection will be extremely slow. Currently indexed query options: hgnc_symbols rank_sco...
Below is the the instruction that describes the task: ### Input: Build a mongo query across multiple cases. Translate query options from a form into a complete mongo query dictionary. Beware that unindexed queries against a large variant collection will be extremely slow. Currently...
def read_10x_h5(filename, genome=None, gex_only=True) -> AnnData: """Read 10x-Genomics-formatted hdf5 file. Parameters ---------- filename : `str` | :class:`~pathlib.Path` Filename. genome : `str`, optional (default: ``None``) Filter expression to this genes within this genome. For ...
Read 10x-Genomics-formatted hdf5 file. Parameters ---------- filename : `str` | :class:`~pathlib.Path` Filename. genome : `str`, optional (default: ``None``) Filter expression to this genes within this genome. For legacy 10x h5 files, this must be provided if the data contains m...
Below is the the instruction that describes the task: ### Input: Read 10x-Genomics-formatted hdf5 file. Parameters ---------- filename : `str` | :class:`~pathlib.Path` Filename. genome : `str`, optional (default: ``None``) Filter expression to this genes within this genome. For lega...
def plot_rank(data, var_names=None, coords=None, bins=None, ref_line=True, figsize=None, axes=None): """Plot rank order statistics of chains. From the paper: Rank plots are histograms of the ranked posterior draws (ranked over all chains) plotted separately for each chain. If all of the chains are targ...
Plot rank order statistics of chains. From the paper: Rank plots are histograms of the ranked posterior draws (ranked over all chains) plotted separately for each chain. If all of the chains are targeting the same posterior, we expect the ranks in each chain to be uniform, whereas if one chain has a ...
Below is the the instruction that describes the task: ### Input: Plot rank order statistics of chains. From the paper: Rank plots are histograms of the ranked posterior draws (ranked over all chains) plotted separately for each chain. If all of the chains are targeting the same posterior, we expect ...
def load_any_file(filename): """ Attempts to load filename by trial-and-error Returns: file: A DataFile descendant, whose specific class depends on the file format detected, or None if the file canonot be loaded """ import f311 # Splits attempts using ((binary X text) file) cri...
Attempts to load filename by trial-and-error Returns: file: A DataFile descendant, whose specific class depends on the file format detected, or None if the file canonot be loaded
Below is the the instruction that describes the task: ### Input: Attempts to load filename by trial-and-error Returns: file: A DataFile descendant, whose specific class depends on the file format detected, or None if the file canonot be loaded ### Response: def load_any_file(filename): """...
def remove(self): ''' Remove this environment ''' self.run_hook('preremove') utils.rmtree(self.path) self.run_hook('postremove')
Remove this environment
Below is the the instruction that describes the task: ### Input: Remove this environment ### Response: def remove(self): ''' Remove this environment ''' self.run_hook('preremove') utils.rmtree(self.path) self.run_hook('postremove')
def _init(): """ Internal function to install the module finder. """ global finder if finder is None: finder = ModuleFinder() if finder not in sys.meta_path: sys.meta_path.insert(0, finder)
Internal function to install the module finder.
Below is the the instruction that describes the task: ### Input: Internal function to install the module finder. ### Response: def _init(): """ Internal function to install the module finder. """ global finder if finder is None: finder = ModuleFinder() if finder not in sys.meta_pa...
def _remove_untraceable(self): """Remove from the tracer those wires that CompiledSimulation cannot track. Create _probe_mapping for wires only traceable via probes. """ self._probe_mapping = {} wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)} self....
Remove from the tracer those wires that CompiledSimulation cannot track. Create _probe_mapping for wires only traceable via probes.
Below is the the instruction that describes the task: ### Input: Remove from the tracer those wires that CompiledSimulation cannot track. Create _probe_mapping for wires only traceable via probes. ### Response: def _remove_untraceable(self): """Remove from the tracer those wires that CompiledSimul...
def npgettext(self, context, singular, plural, num, domain=None, **variables): """Like :meth:`ngettext` but with a context.""" variables.setdefault('num', num) t = self.get_translations(domain) return t.unpgettext(context, singular, plural, num) % variables
Like :meth:`ngettext` but with a context.
Below is the the instruction that describes the task: ### Input: Like :meth:`ngettext` but with a context. ### Response: def npgettext(self, context, singular, plural, num, domain=None, **variables): """Like :meth:`ngettext` but with a context.""" variables.setdefault('num', num) t = self.g...
def get_service(self): """ Returns a BigQuery service object. """ http_authorized = self._authorize() return build( 'bigquery', 'v2', http=http_authorized, cache_discovery=False)
Returns a BigQuery service object.
Below is the the instruction that describes the task: ### Input: Returns a BigQuery service object. ### Response: def get_service(self): """ Returns a BigQuery service object. """ http_authorized = self._authorize() return build( 'bigquery', 'v2', http=http_autho...
def is_true(value=None): ''' Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj) returns True ''' # Fir...
Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj) returns True
Below is the the instruction that describes the task: ### Input: Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj...
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :par...
Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked wit...
Below is the the instruction that describes the task: ### Input: Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The e...
def __lock_density_if_defined(self, stack: dict): """lock (True) the density lock if the density has been been defined during initialization Store the resulting dictionary into density_lock Parameters: =========== stack: dictionary (optional) if not provided, the entir...
lock (True) the density lock if the density has been been defined during initialization Store the resulting dictionary into density_lock Parameters: =========== stack: dictionary (optional) if not provided, the entire stack will be used
Below is the the instruction that describes the task: ### Input: lock (True) the density lock if the density has been been defined during initialization Store the resulting dictionary into density_lock Parameters: =========== stack: dictionary (optional) if not provided, t...
def laplacian_pca(self, coordinates, num_dims=None, beta=0.5): '''Graph-Laplacian PCA (CVPR 2013). coordinates : (n,d) array-like, assumed to be mean-centered. beta : float in [0,1], scales how much PCA/LapEig contributes. Returns an approximation of input coordinates, ala PCA.''' X = np.atleast_2d(...
Graph-Laplacian PCA (CVPR 2013). coordinates : (n,d) array-like, assumed to be mean-centered. beta : float in [0,1], scales how much PCA/LapEig contributes. Returns an approximation of input coordinates, ala PCA.
Below is the the instruction that describes the task: ### Input: Graph-Laplacian PCA (CVPR 2013). coordinates : (n,d) array-like, assumed to be mean-centered. beta : float in [0,1], scales how much PCA/LapEig contributes. Returns an approximation of input coordinates, ala PCA. ### Response: def laplaci...
def get_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list): """ ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
Get a list of tensors in the default graph by a list of names. Args: names (list):
Below is the the instruction that describes the task: ### Input: Get a list of tensors in the default graph by a list of names. Args: names (list): ### Response: def get_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list):...
def path_list(self, sep=os.pathsep): ''' Return list of Path objects. ''' from pathlib import Path return [ Path(pathstr) for pathstr in self.split(sep) ]
Return list of Path objects.
Below is the the instruction that describes the task: ### Input: Return list of Path objects. ### Response: def path_list(self, sep=os.pathsep): ''' Return list of Path objects. ''' from pathlib import Path return [ Path(pathstr) for pathstr in self.split(sep) ]
def run_command(self, config_file, sources): """ :param str config_file: The name of config file. :param list sources: The list with source files. """ config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() ...
:param str config_file: The name of config file. :param list sources: The list with source files.
Below is the the instruction that describes the task: ### Input: :param str config_file: The name of config file. :param list sources: The list with source files. ### Response: def run_command(self, config_file, sources): """ :param str config_file: The name of config file. :param l...
def is_wildcard(self): """Return ``True`` if this identifier contains a wildcard.""" _, token = self.token_next_by(t=T.Wildcard) return token is not None
Return ``True`` if this identifier contains a wildcard.
Below is the the instruction that describes the task: ### Input: Return ``True`` if this identifier contains a wildcard. ### Response: def is_wildcard(self): """Return ``True`` if this identifier contains a wildcard.""" _, token = self.token_next_by(t=T.Wildcard) return token is not None
def load_all(self): """ Force all reports to be loaded and parsed instead of lazy loading on demand. :returns: ``self`` or ``None`` if load fails """ try: self.toi.load_all() self.rosters.load_all() #self.summary.load_all() ...
Force all reports to be loaded and parsed instead of lazy loading on demand. :returns: ``self`` or ``None`` if load fails
Below is the the instruction that describes the task: ### Input: Force all reports to be loaded and parsed instead of lazy loading on demand. :returns: ``self`` or ``None`` if load fails ### Response: def load_all(self): """ Force all reports to be loaded and parsed instead of lazy...
def remove_child_books(self, book_id): """Removes all children from a book. arg: book_id (osid.id.Id): the ``Id`` of a book raise: NotFound - ``book_id`` not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request rai...
Removes all children from a book. arg: book_id (osid.id.Id): the ``Id`` of a book raise: NotFound - ``book_id`` not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure ...
Below is the the instruction that describes the task: ### Input: Removes all children from a book. arg: book_id (osid.id.Id): the ``Id`` of a book raise: NotFound - ``book_id`` not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete ...
def erase_lines(n=1): """ Erases n lines from the screen and moves the cursor up to follow """ for _ in range(n): print(codes.cursor["up"], end="") print(codes.cursor["eol"], end="")
Erases n lines from the screen and moves the cursor up to follow
Below is the the instruction that describes the task: ### Input: Erases n lines from the screen and moves the cursor up to follow ### Response: def erase_lines(n=1): """ Erases n lines from the screen and moves the cursor up to follow """ for _ in range(n): print(codes.cursor["up"], end="") ...
def _quantityToReal(self, quantity): """ Convert a quantity, either spelled-out or numeric, to a float @type quantity: string @param quantity: quantity to parse to float @rtype: int @return: the quantity as an float, defaulting to 0.0 """ if not qua...
Convert a quantity, either spelled-out or numeric, to a float @type quantity: string @param quantity: quantity to parse to float @rtype: int @return: the quantity as an float, defaulting to 0.0
Below is the the instruction that describes the task: ### Input: Convert a quantity, either spelled-out or numeric, to a float @type quantity: string @param quantity: quantity to parse to float @rtype: int @return: the quantity as an float, defaulting to 0.0 ### Response: def...
def update_list(self, picklist, list_id): """UpdateList. [Preview API] Updates a list. :param :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>` picklist: :param str list_id: The ID of the list :rtype: :class:`<PickList> <azure.devops.v5_0.work_ite...
UpdateList. [Preview API] Updates a list. :param :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>` picklist: :param str list_id: The ID of the list :rtype: :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>`
Below is the the instruction that describes the task: ### Input: UpdateList. [Preview API] Updates a list. :param :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>` picklist: :param str list_id: The ID of the list :rtype: :class:`<PickList> <azure.devo...
def get_ax3d_fig_plt(ax=None, **kwargs): """ Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the `matplotlib` figure and create the Axes3D else we return the current active figure. Args: kwargs: keyword arguments are passed to plt.figur...
Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the `matplotlib` figure and create the Axes3D else we return the current active figure. Args: kwargs: keyword arguments are passed to plt.figure if ax is not None. Returns: ax: :class...
Below is the the instruction that describes the task: ### Input: Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the `matplotlib` figure and create the Axes3D else we return the current active figure. Args: kwargs: keyword arguments are pas...
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Linear mean functions :return: NxQ1xQ2 """ with params_as_tensors_for(mean1, mean2): e_xxt = p.cov + (p.mu[:, :, None] * p.mu[:,...
Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Linear mean functions :return: NxQ1xQ2
Below is the the instruction that describes the task: ### Input: Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Linear mean functions :return: NxQ1xQ2 ### Response: def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectati...
def _set_as_int(self, addr, val, numBytes = 1): """Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes.""" if not isinstance(v...
Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes.
Below is the the instruction that describes the task: ### Input: Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes. ### Response: def _...
def HasPendingTasks(self): """Determines if there are tasks running or in need of retrying. Returns: bool: True if there are tasks that are active, ready to be merged or need to be retried. """ with self._lock: self._AbandonInactiveProcessingTasks() if self._tasks_processin...
Determines if there are tasks running or in need of retrying. Returns: bool: True if there are tasks that are active, ready to be merged or need to be retried.
Below is the the instruction that describes the task: ### Input: Determines if there are tasks running or in need of retrying. Returns: bool: True if there are tasks that are active, ready to be merged or need to be retried. ### Response: def HasPendingTasks(self): """Determines if there a...
def raw_cookies(self): '''Raw access to cookies''' cookie_data = self.environ.get('HTTP_COOKIE', '') cookies = SimpleCookie() if not cookie_data: return cookies cookies.load(cookie_data) return cookies
Raw access to cookies
Below is the the instruction that describes the task: ### Input: Raw access to cookies ### Response: def raw_cookies(self): '''Raw access to cookies''' cookie_data = self.environ.get('HTTP_COOKIE', '') cookies = SimpleCookie() if not cookie_data: return cookies c...
def get_source_file(filename, include_no_ext=False): """given a python module's file name return the matching source file name (the filename will be returned identically if it's already an absolute path to a python source file...) :type filename: str :param filename: python module's file name ...
given a python module's file name return the matching source file name (the filename will be returned identically if it's already an absolute path to a python source file...) :type filename: str :param filename: python module's file name :raise NoSourceFile: if no source file exists on the file s...
Below is the the instruction that describes the task: ### Input: given a python module's file name return the matching source file name (the filename will be returned identically if it's already an absolute path to a python source file...) :type filename: str :param filename: python module's file n...
def devices(self): """Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances. """ devices = [] count = self.lib.tdGetNumberOfDevices() for i in range(count): device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)...
Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances.
Below is the the instruction that describes the task: ### Input: Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances. ### Response: def devices(self): """Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances. ...
def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'): """ Cruise control with PI controller and hill disturbance. This function returns various system function configurations for a the cruise control Case Study example found in the supplementary article. The plant model is obtained by the li...
Cruise control with PI controller and hill disturbance. This function returns various system function configurations for a the cruise control Case Study example found in the supplementary article. The plant model is obtained by the linearizing the equations of motion and the controller contains a ...
Below is the the instruction that describes the task: ### Input: Cruise control with PI controller and hill disturbance. This function returns various system function configurations for a the cruise control Case Study example found in the supplementary article. The plant model is obtained by the l...
def _get_ess(sample_array): """Compute the effective sample size for a 2D array.""" shape = sample_array.shape if len(shape) != 2: raise TypeError("Effective sample size calculation requires 2 dimensional arrays.") n_chain, n_draws = shape if n_chain <= 1: raise TypeError("Effective ...
Compute the effective sample size for a 2D array.
Below is the the instruction that describes the task: ### Input: Compute the effective sample size for a 2D array. ### Response: def _get_ess(sample_array): """Compute the effective sample size for a 2D array.""" shape = sample_array.shape if len(shape) != 2: raise TypeError("Effective sample s...
def visualize_cam_with_losses(input_tensor, losses, seed_input, penultimate_layer, grad_modifier=None): """Generates a gradient based class activation map (CAM) by using positive gradients of `input_tensor` with respect to weighted `losses`. For details on grad-CAM, see the paper: [Grad-CAM: Why did yo...
Generates a gradient based class activation map (CAM) by using positive gradients of `input_tensor` with respect to weighted `losses`. For details on grad-CAM, see the paper: [Grad-CAM: Why did you say that? Visual Explanations from Deep Networks via Gradient-based Localization] (https://arxiv.org/pdf/...
Below is the the instruction that describes the task: ### Input: Generates a gradient based class activation map (CAM) by using positive gradients of `input_tensor` with respect to weighted `losses`. For details on grad-CAM, see the paper: [Grad-CAM: Why did you say that? Visual Explanations from Deep ...
def is_element_present(self, strategy, locator): """Checks whether an element is present. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target element. :typ...
Checks whether an element is present. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target element. :type strategy: str :type locator: str :return: ...
Below is the the instruction that describes the task: ### Input: Checks whether an element is present. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target element. ...
def purge_service(self, service_id): """Purge everything from a service.""" content = self._fetch("/service/%s/purge_all" % service_id, method="POST") return self._status(content)
Purge everything from a service.
Below is the the instruction that describes the task: ### Input: Purge everything from a service. ### Response: def purge_service(self, service_id): """Purge everything from a service.""" content = self._fetch("/service/%s/purge_all" % service_id, method="POST") return self._status(content)
def run(self): """Run the progress printing loop.""" last_status = '' # lambda is used to avoid http://bugs.python.org/issue30473 in py36 start_times = defaultdict(lambda: datetime.datetime.now()) max_stage_id = -1 status = self.sc.statusTracker() while True: ...
Run the progress printing loop.
Below is the the instruction that describes the task: ### Input: Run the progress printing loop. ### Response: def run(self): """Run the progress printing loop.""" last_status = '' # lambda is used to avoid http://bugs.python.org/issue30473 in py36 start_times = defaultdict(lambda: ...
def dragEnterEvent( self, event ): """ Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDragEvent> """ filt = self.dragDropFilter() if ( not filt ): super(XCalendarWidget, self).dragE...
Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDragEvent>
Below is the the instruction that describes the task: ### Input: Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDragEvent> ### Response: def dragEnterEvent( self, event ): """ Processes the drag drop event using the ...
def decode_sql(self, sql): """Base64 decode a string. This should only be used for sql in calls. :param str sql: The base64 encoded form of the original utf-8 string :return str: The decoded utf-8 string """ # JSON is defined as using "unicode", we'll go a step further and ...
Base64 decode a string. This should only be used for sql in calls. :param str sql: The base64 encoded form of the original utf-8 string :return str: The decoded utf-8 string
Below is the the instruction that describes the task: ### Input: Base64 decode a string. This should only be used for sql in calls. :param str sql: The base64 encoded form of the original utf-8 string :return str: The decoded utf-8 string ### Response: def decode_sql(self, sql): """Base64 ...
def stop_capture(self, port_number): """ Stops a packet capture. :param port_number: port number """ if not self._ethernet_adapter.port_exists(port_number): raise VPCSError("Port {port_number} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter...
Stops a packet capture. :param port_number: port number
Below is the the instruction that describes the task: ### Input: Stops a packet capture. :param port_number: port number ### Response: def stop_capture(self, port_number): """ Stops a packet capture. :param port_number: port number """ if not self._ethernet_adapte...
def concat_excel_reports(addresses, output_file_name, endpoint, report_type, retry, api_key, api_secret, files_path): """Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses. Args: addresses: A list of (addr...
Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses. Args: addresses: A list of (address, zipcode) tuples output_file_name: A file name for the Excel output endpoint: One of 'value_report' or 'rental_report' rep...
Below is the the instruction that describes the task: ### Input: Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses. Args: addresses: A list of (address, zipcode) tuples output_file_name: A file name for the Excel output ...
def bin_for_range( start, end, offsets=None ): """Find the smallest bin that can contain interval (start,end)""" if offsets is None: offsets = BIN_OFFSETS start_bin, end_bin = start, max(start, end - 1) start_bin >>= BIN_FIRST_SHIFT end_bin >>= BIN_FIRST_SHIFT for offset in offsets: ...
Find the smallest bin that can contain interval (start,end)
Below is the the instruction that describes the task: ### Input: Find the smallest bin that can contain interval (start,end) ### Response: def bin_for_range( start, end, offsets=None ): """Find the smallest bin that can contain interval (start,end)""" if offsets is None: offsets = BIN_OFFSETS s...
def get_next_appointment(self, appointment_group_ids=None): """ Get next appointment. Return the next appointment available to sign up for. The appointment is returned in a one-element array. If no future appointments are available, an empty array is returned. """...
Get next appointment. Return the next appointment available to sign up for. The appointment is returned in a one-element array. If no future appointments are available, an empty array is returned.
Below is the the instruction that describes the task: ### Input: Get next appointment. Return the next appointment available to sign up for. The appointment is returned in a one-element array. If no future appointments are available, an empty array is returned. ### Response: def get_ne...
def _rewrite_col(self, col): """Django >= 1.7 column name rewriting""" if isinstance(col, Col): new_name = rewrite_lookup_key(self.model, col.target.name) if col.target.name != new_name: new_field = self.model._meta.get_field(new_name) if col.targe...
Django >= 1.7 column name rewriting
Below is the the instruction that describes the task: ### Input: Django >= 1.7 column name rewriting ### Response: def _rewrite_col(self, col): """Django >= 1.7 column name rewriting""" if isinstance(col, Col): new_name = rewrite_lookup_key(self.model, col.target.name) if co...