code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
async def extract_rows(self, file_or_name, **reader_kwargs): """ Extract `self.sample_size` rows from the CSV file and analyze their data-types. :param str file_or_name: A string filename or a file handle. :param reader_kwargs: Arbitrary parameters to pass to the CSV reader. ...
Extract `self.sample_size` rows from the CSV file and analyze their data-types. :param str file_or_name: A string filename or a file handle. :param reader_kwargs: Arbitrary parameters to pass to the CSV reader. :returns: A 2-tuple containing a list of headers and list of rows ...
def my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'): """ Return all the loan notes you've already invested in. By default it'll return 100 results at a time. Parameters ---------- start_index : int, optional The result index ...
Return all the loan notes you've already invested in. By default it'll return 100 results at a time. Parameters ---------- start_index : int, optional The result index to start on. By default only 100 records will be returned at a time, so use this to start at a later in...
def var_set(session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: for name, value in session.variables.items(): session.write_line("{0}={1}".format(name, value)) else: for name, valu...
Sets the given variables or prints the current ones. "set answer=42"
def _soi(self, orb): """Evaluate the need for SOI transition, by comparing the radial distance between the considered body and the spacecraft If therer is no body in sight, default to central body. """ for body in self.alt: soi = self.SOI[body.name] sph ...
Evaluate the need for SOI transition, by comparing the radial distance between the considered body and the spacecraft If therer is no body in sight, default to central body.
def _get_iq_handler(self, iq_type, payload): """Get an <iq/> handler for given iq type and payload.""" key = (payload.__class__, payload.handler_key) logger.debug("looking up iq {0} handler for {1!r}, key: {2!r}" .format(iq_type, payload, key)) logger.debug("...
Get an <iq/> handler for given iq type and payload.
def spi_write(self, data): """Write a stream of bytes to a SPI device.""" data_out = array.array('B', data) data_in = array.array('B', (0,) * len(data_out)) ret = api.py_aa_spi_write(self.handle, len(data_out), data_out, len(data_in), data_in) _raise_error_if_nega...
Write a stream of bytes to a SPI device.
def recalculate(self): """ Recalcualtes the slider scene for this widget. """ # recalculate the scene geometry scene = self.scene() w = self.calculateSceneWidth() scene.setSceneRect(0, 0, w, self.height()) # recalculate the item layout ...
Recalcualtes the slider scene for this widget.
def stop(self): """ Stop the node gracefully. Raise if any stop-time error occurred on any subtask """ if self.stop_event.ready(): # not started return # Needs to come before any greenlets joining self.stop_event.set() # Filters must be uninstalled after the alarm ...
Stop the node gracefully. Raise if any stop-time error occurred on any subtask
def findFrequentSequentialPatterns(self, dataset): """ .. note:: Experimental Finds the complete set of frequent sequential patterns in the input sequences of itemsets. :param dataset: A dataframe containing a sequence column which is `ArrayType(ArrayType(T))` t...
.. note:: Experimental Finds the complete set of frequent sequential patterns in the input sequences of itemsets. :param dataset: A dataframe containing a sequence column which is `ArrayType(ArrayType(T))` type, T is the item type for the input dataset. :return: A `Data...
def t_NUMBER(self, t): r'-?[0-9]+' t.value = int(t.value) neg = 0 if t.value < 0: neg = 1 val = abs(t.value) if val <= UNSIGNED32_MAX: if neg: t.type = 'NEGATIVENUMBER' elif val <= UNSIGNED64_MAX: if neg: ...
r'-?[0-9]+
def challenger_by_queue(self, region, queue): """ Get the challenger league for a given queue. :param string region: the region to execute this request on :param string queue: the queue to get the challenger players for :returns: LeagueListDTO """ url, quer...
Get the challenger league for a given queue. :param string region: the region to execute this request on :param string queue: the queue to get the challenger players for :returns: LeagueListDTO
def invalidate(self, callback=True): # type: (bool) -> bool """ Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid """ with self._lock...
Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid
def call(self, action, payload): """ Make an XML-RPC call to the server. This method will automatically authenticate the call with self.api_key, if that is set. returns: deferred that when fired returns a dict with data from this XML-RPC call. """ if sel...
Make an XML-RPC call to the server. This method will automatically authenticate the call with self.api_key, if that is set. returns: deferred that when fired returns a dict with data from this XML-RPC call.
def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): """Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation...
Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: wheth...
def assertFileTypeEqual(self, filename, extension, msg=None): '''Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str I...
Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` ...
def read(bar, offset, size): """Read PCI data register. Parameters ---------- bar : BaseAddressRegister BAR to read. offset : int Address offset in BAR to read. size : int Data size to read. Returns ------- bytes Data read from ...
Read PCI data register. Parameters ---------- bar : BaseAddressRegister BAR to read. offset : int Address offset in BAR to read. size : int Data size to read. Returns ------- bytes Data read from BAR Examples ------...
def render_scene(self): "render scene one time" self.init_gl() # should be a no-op after the first frame is rendered SDL_GL_MakeCurrent ( self.window, self.context ) self.renderer.render_scene() # Done rendering # SDL_GL_SwapWindow(self.window) glFlush()
render scene one time
def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. ...
This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the ...
def detail(request, action_id): """ ``Action`` detail view (pretty boring, mainly used for get_absolute_url) """ return render( request, 'actstream/detail.html', { 'action': get_object_or_404(models.Action, pk=action_id) } )
``Action`` detail view (pretty boring, mainly used for get_absolute_url)
def update_or_create(cls, filter_key=None, with_status=False, **kwargs): """ Update or create the element. If the element exists, update it using the kwargs provided if the provided kwargs after resolving differences from existing values. When comparing values, strings and ints are compa...
Update or create the element. If the element exists, update it using the kwargs provided if the provided kwargs after resolving differences from existing values. When comparing values, strings and ints are compared directly. If a list is provided and is a list of strings, it will be com...
def create_grade(self, grade_form): """Creates a new ``Grade``. arg: grade_form (osid.grading.GradeForm): the form for this ``Grade`` return: (osid.grading.Grade) - the new ``Grade`` raise: IllegalState - ``grade_form`` already used in a create transa...
Creates a new ``Grade``. arg: grade_form (osid.grading.GradeForm): the form for this ``Grade`` return: (osid.grading.Grade) - the new ``Grade`` raise: IllegalState - ``grade_form`` already used in a create transaction raise: InvalidArgument - one or ...
def normalize_errorlevel(error, accept_none=False): """\ Returns a constant for the provided error level. This function returns ``None`` if the provided parameter is ``None`` and `accept_none` is set to ``True`` (default: ``False``). If `error` is ``None`` and `accept_none` is ``False`` or if the p...
\ Returns a constant for the provided error level. This function returns ``None`` if the provided parameter is ``None`` and `accept_none` is set to ``True`` (default: ``False``). If `error` is ``None`` and `accept_none` is ``False`` or if the provided parameter cannot be mapped to a valid QR Code e...
def request_release_milestone_payment(session, milestone_id): """ Release a milestone payment """ params_data = { 'action': 'request_release', } # PUT /api/projects/0.1/milestones/{milestone_id}/?action=release endpoint = 'milestones/{}'.format(milestone_id) response = make_put_r...
Release a milestone payment
def predict_features(self, df_features, df_target, idx=0, C=.1, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): add...
For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): additional options for algorithms C (float): Penalty parameter of the error t...
def _calculate_Hfr_coal(self, T): """ Calculate the enthalpy flow rate of the stream at the specified temperature, in the case of it being coal. :param T: Temperature. [°C] :returns: Enthalpy flow rate. [kWh/h] """ m_C = 0 # kg/h m_H = 0 # kg/h ...
Calculate the enthalpy flow rate of the stream at the specified temperature, in the case of it being coal. :param T: Temperature. [°C] :returns: Enthalpy flow rate. [kWh/h]
def serialize(self): """This function serialize items into a simple dict object. It is used when transferring data to other daemons over the network (http) Here is the generic function that simply serialize each item of the items object :return: Dictionary containing item's uuid as key...
This function serialize items into a simple dict object. It is used when transferring data to other daemons over the network (http) Here is the generic function that simply serialize each item of the items object :return: Dictionary containing item's uuid as key and item as value :rtyp...
def hidden_next_pages(self): """Check if the next pages where sliced. Example: >>> map(lambda i: _SlicedPaginator(i, 6, 3).hidden_next_pages(), range(1, 7)) [True, True, True, True, False, False] >>> map(lambda i: _SlicedPaginator(i, 7, 3).hidden_next_pages(), range(1, 8...
Check if the next pages where sliced. Example: >>> map(lambda i: _SlicedPaginator(i, 6, 3).hidden_next_pages(), range(1, 7)) [True, True, True, True, False, False] >>> map(lambda i: _SlicedPaginator(i, 7, 3).hidden_next_pages(), range(1, 8)) [True, True, True, True, True...
def postActivate_(self): """Whatever you need to do after creating the shmem client """ if (self.requiredGPU_MB(self.required_mb)): self.analyzer = YoloV3TinyAnalyzer(verbose = self.verbose) else: self.warning_message = "WARNING: not enough GPU memory!" ...
Whatever you need to do after creating the shmem client
def _socketpair_compat(): """TCP/IP socketpair including Windows support""" listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listensock.bind(("127.0.0.1", 0)) listensock.listen(1) iface, port = lis...
TCP/IP socketpair including Windows support
def validate(self, document): '''Check if the selected template exists.''' template = document.text if template not in self.builtin_templates: raise ValidationError( message=f'Template {template} not found. ' + f'Available templates are: {", ".join(s...
Check if the selected template exists.
def listen(d, save_dir='report'): ''' Depreciated ''' warnings.warn( "Using report.listen is deprecated, use report.Report(d, save_dir) instead.", ExtDeprecationWarning, stacklevel=2 ) Report(d, save_dir)
Depreciated
def process_columns(self, columns): """ Handle provided columns and if necessary, convert columns to a list for internal strage. :columns: A sequence of columns for the table. Can be list, comma -delimited string, or IntEnum. """ if type(columns) == list: ...
Handle provided columns and if necessary, convert columns to a list for internal strage. :columns: A sequence of columns for the table. Can be list, comma -delimited string, or IntEnum.
def schnorr_partial_combine(self, schnorr_sigs): """Combine multiple Schnorr partial signatures.""" if not HAS_SCHNORR: raise Exception("secp256k1_schnorr not enabled") assert len(schnorr_sigs) > 0 sig64 = ffi.new('char [64]') sig64sin = [] for sig in schnorr...
Combine multiple Schnorr partial signatures.
def line(self, *args): """ Called one at a time for each dataset args are of the form:: <data set n line thickness>, <length of line segment>, <length of blank segment> APIPARAM: chls """ self.lines.append(','.join(['%.1f'%x for x in ma...
Called one at a time for each dataset args are of the form:: <data set n line thickness>, <length of line segment>, <length of blank segment> APIPARAM: chls
def fix_var_name(var_name): """Clean up and apply standard formatting to variable names.""" name = var_name.strip() for char in '(). /#,': name = name.replace(char, '_') name = name.replace('+', 'pos_') name = name.replace('-', 'neg_') if name.endswith('_'): name = name[:-1] ...
Clean up and apply standard formatting to variable names.
def compare(self, other): """ Compares the version with another Parameters ---------- other : Version The version to compare to """ if self._req != other._req: raise ArcanaUsageError( "Can't compare versions of different re...
Compares the version with another Parameters ---------- other : Version The version to compare to
def index_name(model, *field_names, **kwargs): """ Returns the name of the index existing on field_names, or raises KeyError if no such index exists. """ if not len(field_names): raise ValueError("At least one field name required") using = kwargs.pop('using', DEFAULT_DB_ALIAS) if len...
Returns the name of the index existing on field_names, or raises KeyError if no such index exists.
def list_tar (archive, compression, cmd, verbosity, interactive): """List a TAR archive.""" cmdlist = [cmd, '--list'] add_tar_opts(cmdlist, compression, verbosity) cmdlist.extend(["--file", archive]) return cmdlist
List a TAR archive.
def lemmas(self): """Returns the synset's lemmas/variants' literal represantions. Returns ------- list of Lemmas List of its variations' literals as Lemma objects. """ return [lemma("%s.%s"%(self.name,variant.literal)) for variant in self._raw_...
Returns the synset's lemmas/variants' literal represantions. Returns ------- list of Lemmas List of its variations' literals as Lemma objects.
def run(self): """ Start monitoring operation policy files. """ self.initialize_tracking_structures() if self.live_monitoring: self.logger.info("Starting up the operation policy file monitor.") while not self.halt_trigger.is_set(): time.sl...
Start monitoring operation policy files.
def prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names): """ prepare kernel string for compilation Prepends the kernel with a series of C preprocessor defines specific to this kernel instance: * the thread block dimensions * the grid dimensions * tunab...
prepare kernel string for compilation Prepends the kernel with a series of C preprocessor defines specific to this kernel instance: * the thread block dimensions * the grid dimensions * tunable parameters Additionally the name of kernel is replace with an instance specific name. This i...
def to_ufo_propagate_font_anchors(self, ufo): """Copy anchors from parent glyphs' components to the parent.""" processed = set() for glyph in ufo: _propagate_glyph_anchors(self, ufo, glyph, processed)
Copy anchors from parent glyphs' components to the parent.
def store_mail(mbx, mail): """ stores given mail in mailbox. If mailbox is maildir, set the S-flag and return path to newly added mail. Oherwise this will return `None`. :param mbx: mailbox to use :type mbx: :class:`mailbox.Mailbox` :param mail: the mail to store ...
stores given mail in mailbox. If mailbox is maildir, set the S-flag and return path to newly added mail. Oherwise this will return `None`. :param mbx: mailbox to use :type mbx: :class:`mailbox.Mailbox` :param mail: the mail to store :type mail: :class:`email.message.Message` or ...
def delete_file_and_sync_source(self, owner, id, name, **kwargs): """ Delete a file Delete a single file from a dataset by their name, including files added via URL. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `ca...
Delete a file Delete a single file from a dataset by their name, including files added via URL. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def ca...
def signature(name: str) -> Optional[Tuple]: """ Return the file or URL signature for name :param name: :return: """ return url_signature(name) if is_url(name) else file_signature(name) if is_file(name) else None
Return the file or URL signature for name :param name: :return:
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The co...
def exists(self, **kwargs): """Some objects when deleted still return when called by their direct URI, this is a known issue in 11.6.0. """ if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'): return self._exists_11_6(**kwargs) else: return super(Ne...
Some objects when deleted still return when called by their direct URI, this is a known issue in 11.6.0.
def get_relative_path(self, domain, locale): """ Gets the relative file path using the template. @type domain: str @param domain: The domain @type locale: str @param locale: The locale @rtype: string @return: The relative file path """ r...
Gets the relative file path using the template. @type domain: str @param domain: The domain @type locale: str @param locale: The locale @rtype: string @return: The relative file path
def document_type2marc(self, key, value): """Populate the ``980`` MARC field.""" if value in DOCUMENT_TYPE_REVERSE_MAP and DOCUMENT_TYPE_REVERSE_MAP[value]: return {'a': DOCUMENT_TYPE_REVERSE_MAP[value]}
Populate the ``980`` MARC field.
def extended_path(self): """ Add prefix \\?\ to every absolute path, so that it's a "extended-length" path, that should be longer than 259 characters (called: "MAX_PATH") see: https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath """ if self.is_absolute()...
Add prefix \\?\ to every absolute path, so that it's a "extended-length" path, that should be longer than 259 characters (called: "MAX_PATH") see: https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath
def sort_catalogue_chronologically(self): ''' Sorts the catalogue into chronological order ''' dec_time = self.get_decimal_time() idx = np.argsort(dec_time) if np.all((idx[1:] - idx[:-1]) > 0.): # Catalogue was already in chronological order return...
Sorts the catalogue into chronological order
def _transform_col(self, x, i): """Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels. """ return x.fillna(NAN_INT).map(sel...
Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels.
async def server_reflexive_candidate(protocol, stun_server): """ Query STUN server to obtain a server-reflexive candidate. """ # lookup address loop = asyncio.get_event_loop() stun_server = ( await loop.run_in_executor(None, socket.gethostbyname, stun_server[0]), stun_server[1]) ...
Query STUN server to obtain a server-reflexive candidate.
def DEFAULT_NULLVALUE(test): """ Returns a null value for each of various kinds of test values. **Parameters** **test** : bool, int, float or string Value to test. **Returns** **null** : element in `[False, 0, 0.0, '']` Null value c...
Returns a null value for each of various kinds of test values. **Parameters** **test** : bool, int, float or string Value to test. **Returns** **null** : element in `[False, 0, 0.0, '']` Null value corresponding to the given test value: ...
def combine_tensors_and_multiply(combination: str, tensors: List[torch.Tensor], weights: torch.nn.Parameter) -> torch.Tensor: """ Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate fu...
Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate function from ``combine_tensors`` because we try to avoid instantiating large intermediate tensors during the combination, which is possible because we know that we're going to be multiplying by a w...
def cli(): """Command line utility to HTTP enable (publish) a dataset.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "dataset_uri", help="Dtool dataset URI" ) parser.add_argument( "-q", "--quiet", action="store_true", he...
Command line utility to HTTP enable (publish) a dataset.
def getMetadata(self, objectId=None, **filters): """ Request metadata about a text or a collection :param objectId: Filter for some object identifier :param filters: Kwargs parameters. URN and Inv are available :return: GetCapabilities CTS API request response """ filter...
Request metadata about a text or a collection :param objectId: Filter for some object identifier :param filters: Kwargs parameters. URN and Inv are available :return: GetCapabilities CTS API request response
def _process_all_1(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts` in one process." tok = self.tok_func(self.lang) if self.special_cases: tok.add_special_cases(self.special_cases) return [self.process_text(str(t), tok) for t in texts]
Process a list of `texts` in one process.
def get_instance(self, payload): """ Build an instance of TaskChannelInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelIn...
Build an instance of TaskChannelInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance
def map_new(w: int, h: int) -> tcod.map.Map: """Return a :any:`tcod.map.Map` with a width and height. .. deprecated:: 4.5 Use the :any:`tcod.map` module for working with field-of-view, or :any:`tcod.path` for working with path-finding. """ return tcod.map.Map(w, h)
Return a :any:`tcod.map.Map` with a width and height. .. deprecated:: 4.5 Use the :any:`tcod.map` module for working with field-of-view, or :any:`tcod.path` for working with path-finding.
def execute_order(self, order_params, private_key): """ This function executes the order created before it and signs the transaction to be submitted to the blockchain. Execution of this function is as follows:: execute_order(order_params=create_order, private_key=kp) The ex...
This function executes the order created before it and signs the transaction to be submitted to the blockchain. Execution of this function is as follows:: execute_order(order_params=create_order, private_key=kp) The expected return result for this function is the same as the execute_order ...
def interp_S_t(S, t, z, z_new, p=None): ''' Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`. Args ---- S: ndarray CTD salinities t: ndarray CTD temperatures z: ndarray CTD Depths, must be a strictly increasing or decreasing 1-D array, and its ...
Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`. Args ---- S: ndarray CTD salinities t: ndarray CTD temperatures z: ndarray CTD Depths, must be a strictly increasing or decreasing 1-D array, and its length must match the last dimension of `S` and ...
def wait(self, timeout_ms=None): """Block until this command has completed. Args: timeout_ms: Timeout, in milliseconds, to wait. Returns: Output of the command if it complete and self.stdout is a StringIO object or was passed in as None. Returns True if the command completed but stdou...
Block until this command has completed. Args: timeout_ms: Timeout, in milliseconds, to wait. Returns: Output of the command if it complete and self.stdout is a StringIO object or was passed in as None. Returns True if the command completed but stdout was provided (and was not a StringIO o...
def create_decl_string( return_type, arguments_types, with_defaults=True): """ Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :clas...
Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t`
def get_value_ddist(self, attr_name, attr_value): """ Returns the class value probability distribution of the given attribute value. """ assert not self.tree.data.is_continuous_class, \ "Discrete distributions are only maintained for " + \ "discrete class ...
Returns the class value probability distribution of the given attribute value.
def handle_join(self, params): """ Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or '_'. """ channel_names = params.split(' ', 1)[0] # Ignore keys for channel_name in channel_names.split(','): r...
Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or '_'.
def update_model(self, sentences, update_labels_bool): ''' takes a list of sentenes and updates an existing model. Vectors will be callable through self.model[label] update_labels_bool: boolean that says whether to train the model (self.model.train_words = True) or simply to ge...
takes a list of sentenes and updates an existing model. Vectors will be callable through self.model[label] update_labels_bool: boolean that says whether to train the model (self.model.train_words = True) or simply to get vectors for the documents (self.model.train_words = False) s...
def join_path(fname:PathOrStr, path:PathOrStr='.')->Path: "Return `Path(path)/Path(fname)`, `path` defaults to current dir." return Path(path)/Path(fname)
Return `Path(path)/Path(fname)`, `path` defaults to current dir.
def _xlimrev(self): ''' reverse xrange''' xmax,xmin=pyl.xlim() pyl.xlim(xmin,xmax)
reverse xrange
def relevant_transcripts(self, var_g): """return list of transcripts accessions (strings) for given variant, selected by genomic overlap""" tx = self.hdp.get_tx_for_region(var_g.ac, self.alt_aln_method, var_g.posedit.pos.start.base, var_g.posedit.pos.end.b...
return list of transcripts accessions (strings) for given variant, selected by genomic overlap
def group_indices(groupid_list): """ groups indicies of each item in ``groupid_list`` Args: groupid_list (list): list of group ids SeeAlso: vt.group_indices - optimized numpy version ut.apply_grouping CommandLine: python -m utool.util_alg --test-group_indices ...
groups indicies of each item in ``groupid_list`` Args: groupid_list (list): list of group ids SeeAlso: vt.group_indices - optimized numpy version ut.apply_grouping CommandLine: python -m utool.util_alg --test-group_indices python3 -m utool.util_alg --test-group_ind...
def vhosts(): ''' Show the settings as parsed from the config file (currently only shows the virtualhost settings) (``apachectl -S``). Because each additional virtual host adds to the execution time, this command may require a long timeout be specified by using ``-t 10``. CLI Example: ...
Show the settings as parsed from the config file (currently only shows the virtualhost settings) (``apachectl -S``). Because each additional virtual host adds to the execution time, this command may require a long timeout be specified by using ``-t 10``. CLI Example: .. code-block:: bash ...
def is_younger(path, age): """ :param str|None path: Path to file :param int|float age: How many seconds to consider the file too old :return bool: True if file exists and is younger than 'age' seconds """ try: return time.time() - os.path.getmtime(path) < age except (OSError, TypeE...
:param str|None path: Path to file :param int|float age: How many seconds to consider the file too old :return bool: True if file exists and is younger than 'age' seconds
def nrows(self): """Number of rows in the dataframe (int).""" if not self._ex._cache.nrows_valid(): self._ex._cache.flush() self._frame(fill_cache=True) return self._ex._cache.nrows
Number of rows in the dataframe (int).
def lookup(self, iterable, gather=False): """Call the lookup on the root node with the given parameters. Args iterable(index or key): Used to retrive nodes from tree gather(bool): this is passed down to the root node lookup Notes: max_edit_distance and match...
Call the lookup on the root node with the given parameters. Args iterable(index or key): Used to retrive nodes from tree gather(bool): this is passed down to the root node lookup Notes: max_edit_distance and match_threshold come from the init
def get_formatter(self, handler): """ Return formatters according to handler. All handlers are the same format, except syslog. We omit time when syslogging. """ if isinstance(handler, logging.handlers.SysLogHandler): formatter = '[%(levelname)-9s]' el...
Return formatters according to handler. All handlers are the same format, except syslog. We omit time when syslogging.
def appendRecords(self, records, progressCB=None): """ Saves multiple records in the underlying storage. :param records: array of records as in :meth:`~.FileRecordStream.appendRecord` :param progressCB: (function) callback to report progress """ for record in records: ...
Saves multiple records in the underlying storage. :param records: array of records as in :meth:`~.FileRecordStream.appendRecord` :param progressCB: (function) callback to report progress
def _from_binary_b_ace(cls, binary_stream): """See base class.""" ''' Access rights flags - 4 SID - n ''' access_flags = cls._REPR.unpack(binary_stream[:cls._REPR.size])[0] sid = SID.create_from_binary(binary_stream[cls._REPR.size:]) nw_obj = cls((ACEAccessFlags(access_flags), sid)) ...
See base class.
def visible_suite_paths(cls, paths=None): """Get a list of paths to suites that are visible on $PATH. Returns: List of str. """ suite_paths = [] if paths is None: paths = os.getenv("PATH", "").split(os.pathsep) for path in paths: if pa...
Get a list of paths to suites that are visible on $PATH. Returns: List of str.
def set_initial_state(self, initial_state, initial_frames): """Sets the state that will be used on next reset.""" self.env.set_initial_state(initial_state, initial_frames) self._initial_frames = initial_frames
Sets the state that will be used on next reset.
def get_proficiency_lookup_session(self): """Gets the OsidSession associated with the proficiency lookup service. return: (osid.learning.ProficiencyLookupSession) - a ProficiencyLookupSession raise: OperationFailed - unable to complete request raise: Unimplemen...
Gets the OsidSession associated with the proficiency lookup service. return: (osid.learning.ProficiencyLookupSession) - a ProficiencyLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_proficiency_lookup() is false ...
def _merge_data_trace_events(self, event): """! @brief Look for pairs of data trace events and merge.""" if isinstance(event, events.TraceDataTraceEvent): # Record the first data trace event. if self._pending_data_trace is None: self._pending_data_trace = event ...
! @brief Look for pairs of data trace events and merge.
def delete_site(self, site_name, replacement_site=None): """ Remove site with name site_name from self.sites. If the site belonged to a location, remove it from the location's site list. If the site had any samples, change sample.site to "". """ site = self.find_by_name(s...
Remove site with name site_name from self.sites. If the site belonged to a location, remove it from the location's site list. If the site had any samples, change sample.site to "".
def isobaric_to_ambient_temperature(self, data): """ Calculates temperature from isobaric temperature. Parameters ---------- data: DataFrame Must contain columns pressure, temperature_iso, temperature_dew_iso. Input temperature in K. Returns ...
Calculates temperature from isobaric temperature. Parameters ---------- data: DataFrame Must contain columns pressure, temperature_iso, temperature_dew_iso. Input temperature in K. Returns ------- temperature : Series Temperature in K
def _in_class(self, node): """Find if callable is function or method.""" # Move left one indentation level and check if that callable is a class indent = self._get_indent(node) for indent_dict in reversed(self._indent_stack): # pragma: no branch if (indent_dict["level"] < in...
Find if callable is function or method.
def check_auth(username, pwd): """This function is called to check if a username / password combination is valid. """ cfg = get_current_config() return username == cfg["dashboard_httpauth"].split( ":")[0] and pwd == cfg["dashboard_httpauth"].split(":")[1]
This function is called to check if a username / password combination is valid.
def group_indices(self): """ Return group indices """ # No groups if not self.plydata_groups: return np.ones(len(self), dtype=int) grouper = self.groupby() indices = np.empty(len(self), dtype=int) for i, (_, idx) in enumerate(sorted(grouper.in...
Return group indices
def get_parent_books(self, book_id): """Gets the parent books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the parent books of the ``id`` raise: NotFound - a ``Book`` identifi...
Gets the parent books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the parent books of the ``id`` raise: NotFound - a ``Book`` identified by ``Id is`` not found raise: NullAr...
def Rscript_cmd(): """Retrieve path to locally installed Rscript or first in PATH. Prefers Rscript version installed via conda to a system version. """ rscript = which(os.path.join(get_bcbio_bin(), "Rscript")) if rscript: return rscript else: return which("Rscript")
Retrieve path to locally installed Rscript or first in PATH. Prefers Rscript version installed via conda to a system version.
def add_epoch_number(batch: Batch, epoch: int) -> Batch: """ Add the epoch number to the batch instances as a MetadataField. """ for instance in batch.instances: instance.fields['epoch_num'] = MetadataField(epoch) return batch
Add the epoch number to the batch instances as a MetadataField.
def syncImage(img, current, session): """Add or updated the Image.""" def _img_str(i): return "%s - %s" % (i.type, i.description) for db_img in current.images: img_info = (img.type, img.md5, img.size) db_img_info = (db_img.type, db_img.md5, db_img.size) if db_img_info == im...
Add or updated the Image.
def get_query_tables(query): """ :type query str :rtype: list[str] """ tables = [] last_keyword = None last_token = None table_syntax_keywords = [ # SELECT queries 'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'ON', # INSERT queries 'I...
:type query str :rtype: list[str]
def git_clone(sub_repo, branch, commit = None, cwd = None, no_submodules = False): ''' This clone mimicks the way Travis-CI clones a project's repo. So far Travis-CI is the most limiting in the sense of only fetching partial history of the repo. ''' if not cwd: ...
This clone mimicks the way Travis-CI clones a project's repo. So far Travis-CI is the most limiting in the sense of only fetching partial history of the repo.
def _process_filters(filter_dictionary): """ We have a filter_dictionary - this means that if the field is included and matches, then we can include, OR if the field is undefined, then we assume it is safe to include """ def filter_item(field): """ format elasticsearch filter to pass if ...
We have a filter_dictionary - this means that if the field is included and matches, then we can include, OR if the field is undefined, then we assume it is safe to include
def create_git_ref(self, ref, sha): """ :calls: `POST /repos/:owner/:repo/git/refs <http://developer.github.com/v3/git/refs>`_ :param ref: string :param sha: string :rtype: :class:`github.GitRef.GitRef` """ assert isinstance(ref, (str, unicode)), ref asser...
:calls: `POST /repos/:owner/:repo/git/refs <http://developer.github.com/v3/git/refs>`_ :param ref: string :param sha: string :rtype: :class:`github.GitRef.GitRef`
def run(self, x): """ Function for batch usage of already trained and tested MLP. **Args:** * `x` : input array (2-dimensional array). Every row represents one input vector (features). **Returns:** * `y`: output vector (n-dimensional array). Every ...
Function for batch usage of already trained and tested MLP. **Args:** * `x` : input array (2-dimensional array). Every row represents one input vector (features). **Returns:** * `y`: output vector (n-dimensional array). Every row represents output (out...
def unassign_agent_from_resource(self, agent_id, resource_id): """Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not ...
Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not found or ``agent_id`` not assigned to ``resource_id`` ...
def _on_mouse_moved(self, event): """ mouse moved callback """ if event.modifiers() & Qt.ControlModifier: self._select_word_under_mouse_cursor() else: self._remove_decoration() self.editor.set_mouse_cursor(Qt.IBeamCursor) self._previous_cursor_star...
mouse moved callback
def add_users(self, category): """Add users to 'banned', 'contributor', or 'moderator'.""" mapping = {'banned': 'ban', 'contributor': 'make_contributor', 'moderator': 'make_moderator'} if category not in mapping: print('{!r} is not a valid option for --add'.format...
Add users to 'banned', 'contributor', or 'moderator'.
def transform(self): '''P⃗,Q⃗,W⃗''' i = self.inclination Ω = self.longitude_of_ascending_node ω = self.argument_of_periapsis si = sin(i) ci = cos(i) sΩ = sin(Ω) cΩ = cos(Ω) sω = sin(ω) cω = cos(ω) Q = np.array([ [-sΩ*...
P⃗,Q⃗,W⃗