code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def bounds(self): """ Return the axis aligned bounding box of the current path. Returns ---------- bounds: (2, dimension) float, (min, max) coordinates """ # get the exact bounds of each entity # some entities (aka 3- point Arc) have bounds that can't ...
Return the axis aligned bounding box of the current path. Returns ---------- bounds: (2, dimension) float, (min, max) coordinates
def weighted_minkowski(x, y, w=_mock_identity, p=2): """A weighted version of Minkowski distance. ..math:: D(x, y) = \left(\sum_i w_i |x_i - y_i|^p\right)^{\frac{1}{p}} If weights w_i are inverse standard deviations of data in each dimension then this represented a standardised Minkowski dista...
A weighted version of Minkowski distance. ..math:: D(x, y) = \left(\sum_i w_i |x_i - y_i|^p\right)^{\frac{1}{p}} If weights w_i are inverse standard deviations of data in each dimension then this represented a standardised Minkowski distance (and is equivalent to standardised Euclidean distanc...
def dict_strict_update(base_dict, update_dict): """ This function updates base_dict with update_dict if and only if update_dict does not contain keys that are not already in base_dict. It is essentially a more strict interpretation of the term "updating" the dict. If update_dict contains keys that ...
This function updates base_dict with update_dict if and only if update_dict does not contain keys that are not already in base_dict. It is essentially a more strict interpretation of the term "updating" the dict. If update_dict contains keys that are not in base_dict, a RuntimeError is raised. :param ...
def _lookup_enum_in_ns(namespace, value): """Return the attribute of namespace corresponding to value.""" for attribute in dir(namespace): if getattr(namespace, attribute) == value: return attribute
Return the attribute of namespace corresponding to value.
def iter_predict(self, X, include_init=False): """Returns the predictions for ``X`` at every stage of the boosting procedure. Args: X (array-like or sparse matrix of shape (n_samples, n_features): The input samples. Sparse matrices are accepted only if they are supported by ...
Returns the predictions for ``X`` at every stage of the boosting procedure. Args: X (array-like or sparse matrix of shape (n_samples, n_features): The input samples. Sparse matrices are accepted only if they are supported by the weak model. include_init (bool, default=Fa...
async def deserialize(self, data: dict, silent=True): ''' Deserializes a Python ``dict`` into the model by assigning values to their respective fields. Ignores data attributes that do not match one of the Model's fields. Ignores data attributes who's matching fields are declared with the...
Deserializes a Python ``dict`` into the model by assigning values to their respective fields. Ignores data attributes that do not match one of the Model's fields. Ignores data attributes who's matching fields are declared with the ``readonly`` attribute Validates the data after import. O...
def _parse_json(self, json, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' features = json['features'] if features == []: return None def parse_feature(feature): location = feature['place_name'] place = feature['text'...
Returns location, (latitude, longitude) from json feed.
def _ssl_agent(self): """ Get a Twisted Agent that performs Client SSL authentication for Koji. """ # Load "cert" into a PrivateCertificate. certfile = self.lookup(self.profile, 'cert') certfile = os.path.expanduser(certfile) with open(certfile) as certfp: ...
Get a Twisted Agent that performs Client SSL authentication for Koji.
def get_fuzzed(self, indent=False, utf8=False): """ Return the fuzzed object """ try: if "array" in self.json: return self.fuzz_elements(dict(self.json))["array"] else: return self.fuzz_elements(dict(self.json)) except Excep...
Return the fuzzed object
def encode_list(cls, value): """ Encodes a list *value* into a string via base64 encoding. """ encoded = base64.b64encode(six.b(" ".join(str(v) for v in value) or "-")) return encoded.decode("utf-8") if six.PY3 else encoded
Encodes a list *value* into a string via base64 encoding.
def _get_parameter_values(template_dict, parameter_overrides): """ Construct a final list of values for CloudFormation template parameters based on user-supplied values, default values provided in template, and sane defaults for pseudo-parameters. Parameters ---------- t...
Construct a final list of values for CloudFormation template parameters based on user-supplied values, default values provided in template, and sane defaults for pseudo-parameters. Parameters ---------- template_dict : dict SAM template dictionary parameter_override...
def word_break(el, max_width=40, avoid_elements=_avoid_word_break_elements, avoid_classes=_avoid_word_break_classes, break_character=unichr(0x200b)): """ Breaks any long words found in the body of the text (not attributes). Doesn't effect any of the tags in avoi...
Breaks any long words found in the body of the text (not attributes). Doesn't effect any of the tags in avoid_elements, by default ``<textarea>`` and ``<pre>`` Breaks words by inserting &#8203;, which is a unicode character for Zero Width Space character. This generally takes up no space in rende...
def _build_command_chain(self, command): """ Builds execution chain including all intercepters and the specified command. :param command: the command to build a chain. """ next = command for intercepter in reversed(self._intercepters): next = InterceptedComma...
Builds execution chain including all intercepters and the specified command. :param command: the command to build a chain.
def _create_binary_mathfunction(name, doc=""): """ Create a binary mathfunction by name""" def _(col1, col2): sc = SparkContext._active_spark_context # For legacy reasons, the arguments here can be implicitly converted into floats, # if they are not columns or strings. if isinsta...
Create a binary mathfunction by name
def disk_check_size(ctx, param, value): """ Validation callback for disk size parameter.""" if value: # if we've got a prefix if isinstance(value, tuple): val = value[1] else: val = value if val % 1024: raise click.ClickException('Size must be ...
Validation callback for disk size parameter.
def vspec(data): """ Takes the vector mean of replicate measurements at a given step """ vdata, Dirdata, step_meth = [], [], [] tr0 = data[0][0] # set beginning treatment data.append("Stop") k, R = 1, 0 for i in range(k, len(data)): Dirdata = [] if data[i][0] != tr0: ...
Takes the vector mean of replicate measurements at a given step
def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: ...
Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context.
def validate_split_runs_file(split_runs_file): """Check if structure of file is as expected and return dictionary linking names to run_IDs.""" try: content = [l.strip() for l in split_runs_file.readlines()] if content[0].upper().split('\t') == ['NAME', 'RUN_ID']: return {c.split('\t'...
Check if structure of file is as expected and return dictionary linking names to run_IDs.
def umi_transform(data): """ transform each read by identifying the barcode and UMI for each read and putting the information in the read name """ fqfiles = data["files"] fqfiles.extend(list(repeat("", 4-len(fqfiles)))) fq1, fq2, fq3, fq4 = fqfiles umi_dir = os.path.join(dd.get_work_dir(...
transform each read by identifying the barcode and UMI for each read and putting the information in the read name
def execute(self, *args, **kwargs): """ See :py:func:`silverberg.client.CQLClient.execute` """ num_clients = len(self._seed_clients) start_client = (self._client_idx + 1) % num_clients def _client_error(failure, client_i): failure.trap(ConnectError) ...
See :py:func:`silverberg.client.CQLClient.execute`
def __start_experiment(self, parameters): """ Start an experiment by capturing the state of the code :param parameters: a dictionary containing the parameters of the experiment :type parameters: dict :return: the tag representing this experiment :rtype: TagReference ...
Start an experiment by capturing the state of the code :param parameters: a dictionary containing the parameters of the experiment :type parameters: dict :return: the tag representing this experiment :rtype: TagReference
def save(state, filename=None, desc='', extra=None): """ Save the current state with extra information (for example samples and LL from the optimization procedure). Parameters ---------- state : peri.states.ImageState the state object which to save filename : string if prov...
Save the current state with extra information (for example samples and LL from the optimization procedure). Parameters ---------- state : peri.states.ImageState the state object which to save filename : string if provided, will override the default that is constructed based on ...
def clone(self, population): """ Copy the holder just enough to be able to run a new simulation without modifying the original simulation. """ new = empty_clone(self) new_dict = new.__dict__ for key, value in self.__dict__.items(): if key not in ('populat...
Copy the holder just enough to be able to run a new simulation without modifying the original simulation.
def align_rna(job, fastqs, univ_options, star_options): """ A wrapper for the entire rna alignment subgraph. :param list fastqs: The input fastqs for alignment :param dict univ_options: Dict of universal options used by almost all tools :param dict star_options: Options specific to star :return...
A wrapper for the entire rna alignment subgraph. :param list fastqs: The input fastqs for alignment :param dict univ_options: Dict of universal options used by almost all tools :param dict star_options: Options specific to star :return: Dict containing input bam and the generated index (.bam.bai) :...
def get_requirements(): """Parse a requirements.txt file and return as a list.""" with open(os.path.join(topdir, 'requirements.txt')) as fin: lines = fin.readlines() lines = [line.strip() for line in lines] return lines
Parse a requirements.txt file and return as a list.
def createTable(dbconn, pd): """Creates a database table for the given PacketDefinition.""" cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields) sql = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols)) dbconn.execute(sql) dbconn.commit()
Creates a database table for the given PacketDefinition.
def _set_base_path_env(): # type: () -> None """Sets the environment variable SAGEMAKER_BASE_DIR as ~/sagemaker_local/{timestamp}/opt/ml Returns: (bool): indicating whe """ local_config_dir = os.path.join(os.path.expanduser('~'), 'sagemaker_local', 'jobs', ...
Sets the environment variable SAGEMAKER_BASE_DIR as ~/sagemaker_local/{timestamp}/opt/ml Returns: (bool): indicating whe
def logging_set_filter(name, filter_def, ttl, **kwargs): """ Set local filter. """ ctx = Context(**kwargs) ctx.execute_action('logging:set_filter', **{ 'logging_service': ctx.repo.create_secure_service('logging'), 'logger_name': name, 'filter_def': filter_def, 'ttl': ...
Set local filter.
def to_struct(model): """Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict`` """ model.validate() resp = {} for _, name, field in model.iterate_with_name(): value = field.__get__(model) if value is None: continue ...
Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict``
def get_review_average(obj): """Returns the review average for an object.""" total = 0 reviews = get_reviews(obj) if not reviews: return False for review in reviews: average = review.get_average_rating() if average: total += review.get_average_rating() if tota...
Returns the review average for an object.
def results(self, Snwp): r""" Returns the phase configuration at the specified non-wetting phase (invading phase) saturation. Parameters ---------- Snwp : scalar, between 0 and 1 The network saturation for which the phase configuration is desired....
r""" Returns the phase configuration at the specified non-wetting phase (invading phase) saturation. Parameters ---------- Snwp : scalar, between 0 and 1 The network saturation for which the phase configuration is desired. Returns -------...
def post(action, params=None, version=6): """ For the documentation, see https://foosoft.net/projects/anki-connect/ :param str action: :param dict params: :param int version: :return: """ if params is None: params = dict() to_send = { ...
For the documentation, see https://foosoft.net/projects/anki-connect/ :param str action: :param dict params: :param int version: :return:
def RecreateInstanceDisks(r, instance, disks=None, nodes=None): """Recreate an instance's disks. @type instance: string @param instance: Instance name @type disks: list of int @param disks: List of disk indexes @type nodes: list of string @param nodes: New instance nodes, if relocation is d...
Recreate an instance's disks. @type instance: string @param instance: Instance name @type disks: list of int @param disks: List of disk indexes @type nodes: list of string @param nodes: New instance nodes, if relocation is desired @rtype: string @return: job id
def heap_item(clock, record, shard): """Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.""" # Primary ordering is by event creation time. # However, creation time is *approximate* and has whole-second resolution. # This means two events in the same shard within one second can't b...
Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.
def json(self): """ Return a JSON-serializeable object containing station metadata.""" return { "elevation": self.elevation, "latitude": self.latitude, "longitude": self.longitude, "icao_code": self.icao_code, "name": self.name, "qu...
Return a JSON-serializeable object containing station metadata.
def _wrap_key(function, args, kws): ''' get the key from the function input. ''' return hashlib.md5(pickle.dumps((_from_file(function) + function.__name__, args, kws))).hexdigest()
get the key from the function input.
def notify( self, method_name: str, *args: Any, trim_log_values: Optional[bool] = None, validate_against_schema: Optional[bool] = None, **kwargs: Any ) -> Response: """ Send a JSON-RPC request, without expecting a response. Args: m...
Send a JSON-RPC request, without expecting a response. Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log ...
def enable_one_shot_process_breakpoints(self, dwProcessId): """ Enables for one shot all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """ # enable code breakpoints for one shot for bp in self.get_proc...
Enables for one shot all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID.
def trim_wavs(org_wav_dir=ORG_WAV_DIR, tgt_wav_dir=TGT_WAV_DIR, org_xml_dir=ORG_XML_DIR): """ Extracts sentence-level transcriptions, translations and wavs from the Na Pangloss XML and WAV files. But otherwise doesn't preprocess them.""" logging.info("Trimming wavs...") if ...
Extracts sentence-level transcriptions, translations and wavs from the Na Pangloss XML and WAV files. But otherwise doesn't preprocess them.
def concatenate(self, other): """ Concatenate this line string with another one. This will add a line segment between the end point of this line string and the start point of `other`. Parameters ---------- other : imgaug.augmentables.lines.LineString or ndarray ...
Concatenate this line string with another one. This will add a line segment between the end point of this line string and the start point of `other`. Parameters ---------- other : imgaug.augmentables.lines.LineString or ndarray \ or iterable of tuple of number ...
def duplicate(self): """Return a copy of the current Data Collection.""" collection = self.__class__(self.header.duplicate(), self.values, self.datetimes) collection._validated_a_period = self._validated_a_period return collection
Return a copy of the current Data Collection.
def sg_get_context(): r"""Get current context information Returns: tf.sg_opt class object which contains all context information """ global _context # merge current context res = tf.sg_opt() for c in _context: res += c return res
r"""Get current context information Returns: tf.sg_opt class object which contains all context information
def parse_interface(iface): """ Returns a docco section for the given interface. :Parameters: iface Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params' """ sections = [ ] docs = iface['comment'] code = '<span class="k">interface</span> <span class="gs">%s</...
Returns a docco section for the given interface. :Parameters: iface Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params'
def contains(self, time: datetime.datetime, inclusive: bool = True) -> bool: """ Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? """ i...
Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks?
def write_msr(address, value): """ Set the contents of the specified MSR (Machine Specific Register). @type address: int @param address: MSR to write. @type value: int @param value: Contents to write on the MSR. @raise WindowsError: Raises an exce...
Set the contents of the specified MSR (Machine Specific Register). @type address: int @param address: MSR to write. @type value: int @param value: Contents to write on the MSR. @raise WindowsError: Raises an exception on error. @raise NotImplementedError...
def users_with_birthday(self, month, day): """Return a list of user objects who have a birthday on a given date.""" users = User.objects.filter(properties___birthday__month=month, properties___birthday__day=day) results = [] for user in users: # TODO: permissions system ...
Return a list of user objects who have a birthday on a given date.
def _parse_posts(self, raw_posts): """Parse posts and returns in order.""" parsed_posts = self.parse_json(raw_posts) # Posts are not sorted. The order is provided by # 'order' key. for post_id in parsed_posts['order']: yield parsed_posts['posts'][post_id]
Parse posts and returns in order.
def dashed(requestContext, seriesList, dashLength=5): """ Takes one metric or a wildcard seriesList, followed by a float F. Draw the selected metrics with a dotted line with segments of length F If omitted, the default length of the segments is 5.0 Example:: &target=dashed(server01.instan...
Takes one metric or a wildcard seriesList, followed by a float F. Draw the selected metrics with a dotted line with segments of length F If omitted, the default length of the segments is 5.0 Example:: &target=dashed(server01.instance01.memory.free,2.5)
def add_perfdata(self, *args, **kwargs): """ add a perfdata to the internal perfdata list arguments: the same arguments as for Perfdata() """ self._perfdata.append(Perfdata(*args, **kwargs))
add a perfdata to the internal perfdata list arguments: the same arguments as for Perfdata()
def _url_to_epub( self): """*generate the epub book from a URL* """ self.log.debug('starting the ``_url_to_epub`` method') from polyglot import htmlCleaner cleaner = htmlCleaner( log=self.log, settings=self.settings, url=self.urlOr...
*generate the epub book from a URL*
def predict(self, predict_set ): """ This method accepts a list of Instances Eg: list_of_inputs = [ Instance([0.12, 0.54, 0.84]), Instance([0.15, 0.29, 0.49]) ] """ predict_data = np.array( [instance.features for instance in predict_set ] ) ret...
This method accepts a list of Instances Eg: list_of_inputs = [ Instance([0.12, 0.54, 0.84]), Instance([0.15, 0.29, 0.49]) ]
def is_ancestor_of_family(self, id_, family_id): """Tests if an ``Id`` is an ancestor of a family. arg: id (osid.id.Id): an ``Id`` arg: family_id (osid.id.Id): the ``Id`` of a family return: (boolean) - ``true`` if this ``id`` is an ancestor of ``family_id,`` ``fa...
Tests if an ``Id`` is an ancestor of a family. arg: id (osid.id.Id): an ``Id`` arg: family_id (osid.id.Id): the ``Id`` of a family return: (boolean) - ``true`` if this ``id`` is an ancestor of ``family_id,`` ``false`` otherwise raise: NotFound - ``family_id`` is ...
def convert_iris(directory, output_directory, output_filename='iris.hdf5'): """Convert the Iris dataset to HDF5. Converts the Iris dataset to an HDF5 dataset compatible with :class:`fuel.datasets.Iris`. The converted dataset is saved as 'iris.hdf5'. This method assumes the existence of the file `ir...
Convert the Iris dataset to HDF5. Converts the Iris dataset to an HDF5 dataset compatible with :class:`fuel.datasets.Iris`. The converted dataset is saved as 'iris.hdf5'. This method assumes the existence of the file `iris.data`. Parameters ---------- directory : str Directory in w...
def partial_ratio(s1, s2): """"Return the ratio of the most similar substring as a number between 0 and 100.""" s1, s2 = utils.make_type_consistent(s1, s2) if len(s1) <= len(s2): shorter = s1 longer = s2 else: shorter = s2 longer = s1 m = SequenceMatcher(None, s...
Return the ratio of the most similar substring as a number between 0 and 100.
def set_power_supplies(self, power_supplies): """ Sets the 2 power supplies with 0 = off, 1 = on. :param power_supplies: list of 2 power supplies. Example: [1, 0] = first power supply is on, second is off. """ power_supply_id = 0 for power_supply in power_suppli...
Sets the 2 power supplies with 0 = off, 1 = on. :param power_supplies: list of 2 power supplies. Example: [1, 0] = first power supply is on, second is off.
def list_namespaces(self): ''' List the service bus namespaces defined on the account. ''' response = self._perform_get( self._get_path('services/serviceBus/Namespaces/', None), None) return _MinidomXmlToObject.convert_response_to_feeds( respo...
List the service bus namespaces defined on the account.
def on_backward_end(self, **kwargs): "Clip the gradient before the optimizer step." if self.clip: nn.utils.clip_grad_norm_(self.learn.model.parameters(), self.clip)
Clip the gradient before the optimizer step.
def getport(self, default=None): """Return the port subcomponent of the URI authority as an :class:`int`, or `default` if the original URI reference did not contain a port or if the port was empty. """ port = self.port if port: return int(port) else: ...
Return the port subcomponent of the URI authority as an :class:`int`, or `default` if the original URI reference did not contain a port or if the port was empty.
def entity_data(self, entity_type, entity_id, history_index): """Return the data dict for an entity at a specific index of its history. """ return self.entity_history(entity_type, entity_id)[history_index]
Return the data dict for an entity at a specific index of its history.
def add_petabencana_layer(self): """Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods """ from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog dialog = PetaBencanaDialog(se...
Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods
def get_for_site(cls, site): """Return the 'main menu' instance for the provided site""" instance, created = cls.objects.get_or_create(site=site) return instance
Return the 'main menu' instance for the provided site
def auto_forward(auto=True): """ Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool """ global __auto_forward_state prev = __auto_forward_state __auto_forward_s...
Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool
def next(self): """ Returns the next result. If no result is availble within the specified (during construction) "timeout" then a ``PiperError`` which wraps a ``TimeoutError`` is **returned**. If the result is a ``WorkerError`` it is also wrapped in a ``PiperError`` ...
Returns the next result. If no result is availble within the specified (during construction) "timeout" then a ``PiperError`` which wraps a ``TimeoutError`` is **returned**. If the result is a ``WorkerError`` it is also wrapped in a ``PiperError`` and is returned or raised if "debug"...
def create(dataset, target, feature=None, model = 'resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER...
Create a :class:`ImageClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string, or int Name of the column containing the target variable. The values in this column m...
def force_leave(self, node): """Force a failed gossip member into the left state. https://www.nomadproject.io/docs/http/agent-force-leave.html returns: 200 status code raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNo...
Force a failed gossip member into the left state. https://www.nomadproject.io/docs/http/agent-force-leave.html returns: 200 status code raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadException
def feature_path(self, gff_path): """Load a GFF file with information on a single sequence and store features in the ``features`` attribute Args: gff_path: Path to GFF file. """ if not gff_path: self.feature_dir = None self.feature_file = None ...
Load a GFF file with information on a single sequence and store features in the ``features`` attribute Args: gff_path: Path to GFF file.
def post(self, route: str(), callback: object()): """ Binds a POST route with the given callback :rtype: object """ self.__set_route('post', {route: callback}) return RouteMapping
Binds a POST route with the given callback :rtype: object
def getWorksheet(self): """Returns the Worksheet to which this analysis belongs to, or None """ worksheet = self.getBackReferences('WorksheetAnalysis') if not worksheet: return None if len(worksheet) > 1: logger.error( "Analysis %s is assig...
Returns the Worksheet to which this analysis belongs to, or None
def get_frequency_dict(lang, wordlist='best', match_cutoff=30): """ Get a word frequency list as a dictionary, mapping tokens to frequencies as floating-point probabilities. """ freqs = {} pack = get_frequency_list(lang, wordlist, match_cutoff) for index, bucket in enumerate(pack): f...
Get a word frequency list as a dictionary, mapping tokens to frequencies as floating-point probabilities.
def create(self, instance, parameters, existing=True): """Create an instance Args: instance (AtlasServiceInstance.Instance): Existing or New instance parameters (dict): Parameters for the instance Keyword Arguments: existing (bool): True ...
Create an instance Args: instance (AtlasServiceInstance.Instance): Existing or New instance parameters (dict): Parameters for the instance Keyword Arguments: existing (bool): True (use an existing cluster), False (create a new cluster) ...
def select_by_visible_text(self, text): """ Performs search of selected item from Web List @params text - string visible text """ xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text)) opts = self.find_elements_by_xpath(xpath) matched = F...
Performs search of selected item from Web List @params text - string visible text
def get_under_hollow(self): """ Return HCP if an atom is present below the adsorbate in the subsurface layer and FCC if not""" C0 = self.B[-1:] * (3, 3, 1) ads_pos = C0.positions[4] C = self.get_subsurface_layer() * (3, 3, 1) ret = 'FCC' if np.any([np.linalg.no...
Return HCP if an atom is present below the adsorbate in the subsurface layer and FCC if not
def cross_signal(s1, s2, continuous=0): """ return a signal with the following 1 : when all values of s1 cross all values of s2 -1 : when all values of s2 cross below all values of s2 0 : if s1 < max(s2) and s1 > min(s2) np.nan : if s1 or s2 contains np.nan at position s1: Series, DataFrame, f...
return a signal with the following 1 : when all values of s1 cross all values of s2 -1 : when all values of s2 cross below all values of s2 0 : if s1 < max(s2) and s1 > min(s2) np.nan : if s1 or s2 contains np.nan at position s1: Series, DataFrame, float, int, or tuple(float|int) s2: Series, D...
def _plot_simple_fault(self, source, border='k-', border_width=1.0): """ Plots the simple fault source as a composite of the fault trace and the surface projection of the fault. :param source: Fault source as instance of :class: mtkSimpleFaultSource :param str border:...
Plots the simple fault source as a composite of the fault trace and the surface projection of the fault. :param source: Fault source as instance of :class: mtkSimpleFaultSource :param str border: Line properties of border (see matplotlib documentation for detail) ...
def textFromHTML(html): """ Cleans and parses text from the given HTML. """ cleaner = lxml.html.clean.Cleaner(scripts=True) cleaned = cleaner.clean_html(html) return lxml.html.fromstring(cleaned).text_content()
Cleans and parses text from the given HTML.
def get(self, key, value=None): "x.get(k[,d]) -> x[k] if k in x, else d. d defaults to None." _key = self._prepare_key(key) prefix, node = self._get_node_by_key(_key) if prefix==_key and node.value is not None: return self._unpickle_value(node.value) else: ...
x.get(k[,d]) -> x[k] if k in x, else d. d defaults to None.
def _gser(a,x): "Series representation of Gamma. NumRec sect 6.1." ITMAX=100 EPS=3.e-7 gln=lgamma(a) assert(x>=0),'x < 0 in gser' if x == 0 : return 0,gln ap = a delt = sum = 1./a for i in range(ITMAX): ap=ap+1. delt=delt*x/ap sum=sum+delt if abs(del...
Series representation of Gamma. NumRec sect 6.1.
def initialize(self, argv=None): """initialize the app""" super(BaseParallelApplication, self).initialize(argv) self.to_work_dir() self.reinit_logging()
initialize the app
def attach(self, lun_or_snap, skip_hlu_0=False): """ Attaches lun, snap or member snap of cg snap to host. Don't pass cg snapshot in as `lun_or_snap`. :param lun_or_snap: the lun, snap, or a member snap of cg snap :param skip_hlu_0: whether to skip hlu 0 :return: the hlu number...
Attaches lun, snap or member snap of cg snap to host. Don't pass cg snapshot in as `lun_or_snap`. :param lun_or_snap: the lun, snap, or a member snap of cg snap :param skip_hlu_0: whether to skip hlu 0 :return: the hlu number
def image_props(event): """ Get information for a pick event on an ``AxesImage`` artist. Returns a dict of "i" & "j" index values of the image for the point clicked, and "z": the (uninterpolated) value of the image at i,j. Parameters ----------- event : PickEvent The pick event to p...
Get information for a pick event on an ``AxesImage`` artist. Returns a dict of "i" & "j" index values of the image for the point clicked, and "z": the (uninterpolated) value of the image at i,j. Parameters ----------- event : PickEvent The pick event to process Returns -------- ...
async def find( self, *, types=None, data=None, countries=None, post=False, strict=False, dnsbl=None, limit=0, **kwargs ): """Gather and check proxies from providers or from a passed data. :ref:`Example of usage <proxyb...
Gather and check proxies from providers or from a passed data. :ref:`Example of usage <proxybroker-examples-find>`. :param list types: Types (protocols) that need to be check on support by proxy. Supported: HTTP, HTTPS, SOCKS4, SOCKS5, CONNECT:80, CONNECT:25 And lev...
def whoami(ctx, opts): """Retrieve your current authentication status.""" click.echo("Retrieving your authentication status from the API ... ", nl=False) context_msg = "Failed to retrieve your authentication status!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with mayb...
Retrieve your current authentication status.
def apply_parallel(func: Callable, data: List[Any], cpu_cores: int = None) -> List[Any]: """ Apply function to list of elements. Automatically determines the chunk size. """ if not cpu_cores: cpu_cores = cpu_count() try: chunk_size = ceil(l...
Apply function to list of elements. Automatically determines the chunk size.
def check_classes(self, scope=-1): """ Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked. """ for entry in self[scope].values(): if entry.class_ is None: syntax_error(entry...
Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked.
def make_default_options_response(self): """This method is called to create the default `OPTIONS` response. This can be changed through subclassing to change the default behavior of `OPTIONS` responses. .. versionadded:: 0.7 """ adapter = _request_ctx_stack.top.url_adapt...
This method is called to create the default `OPTIONS` response. This can be changed through subclassing to change the default behavior of `OPTIONS` responses. .. versionadded:: 0.7
def reindex_repo_dev_panel(self, project, repository): """ Reindex all of the Jira issues related to this repository, including branches and pull requests. This automatically happens as part of an upgrade, and calling this manually should only be required if something unforeseen happens ...
Reindex all of the Jira issues related to this repository, including branches and pull requests. This automatically happens as part of an upgrade, and calling this manually should only be required if something unforeseen happens and the index becomes out of sync. The authenticated user must have...
def get(self, name, **kwargs): """Retrieves a :py:class:`Parameter` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`Parameter` with key-word arguments and insert...
Retrieves a :py:class:`Parameter` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`Parameter` with key-word arguments and insert it to self. Parameters -...
def preprocess(S, coloring_method=None): """Preprocess splitting functions. Parameters ---------- S : csr_matrix Strength of connection matrix method : string Algorithm used to compute the vertex coloring: * 'MIS' - Maximal Independent Set * 'JP' - Jones-Pla...
Preprocess splitting functions. Parameters ---------- S : csr_matrix Strength of connection matrix method : string Algorithm used to compute the vertex coloring: * 'MIS' - Maximal Independent Set * 'JP' - Jones-Plassmann (parallel) * 'LDF' - Largest-...
def get_thread(self, thread_id, update_if_cached=True, raise_404=False): """Get a thread from 4chan via 4chan API. Args: thread_id (int): Thread ID update_if_cached (bool): Whether the thread should be updated if it's already in our cache raise_404 (bool): Raise an E...
Get a thread from 4chan via 4chan API. Args: thread_id (int): Thread ID update_if_cached (bool): Whether the thread should be updated if it's already in our cache raise_404 (bool): Raise an Exception if thread has 404'd Returns: :class:`basc_py4chan.Thre...
def smooth(polylines): """ smooth every polyline using spline interpolation """ for c in polylines: if len(c) < 9: # smoothing wouldn't make sense here continue x = c[:, 0] y = c[:, 1] t = np.arange(x.shape[0], dtype=float) t /= t[-1] ...
smooth every polyline using spline interpolation
def map_concepts_to_indicators( self, n: int = 1, min_temporal_res: Optional[str] = None ): """ Map each concept node in the AnalysisGraph instance to one or more tangible quantities, known as 'indicators'. Args: n: Number of matches to keep min_temporal_res:...
Map each concept node in the AnalysisGraph instance to one or more tangible quantities, known as 'indicators'. Args: n: Number of matches to keep min_temporal_res: Minimum temporal resolution that the indicators must have data for.
def send_stream_tail(self): """ Send stream tail via the transport. """ with self.lock: if not self._socket or self._hup: logger.debug(u"Cannot send stream closing tag: already closed") return data = self._serializer.emit_tail() ...
Send stream tail via the transport.
def pack(self, value=None): """Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a sw...
Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a switch, here we also call :meth:`...
def register_metrics(self, metrics_collector, interval): """Registers its metrics to a given metrics collector with a given interval""" for field, metrics in self.metrics.items(): metrics_collector.register_metric(field, metrics, interval)
Registers its metrics to a given metrics collector with a given interval
def transform(self, Y): r"""Compute all pairwise distances between `self.X_fit_` and `Y`. Parameters ---------- y : array-like, shape = (n_samples_y, n_features) Returns ------- kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_) Kernel matrix...
r"""Compute all pairwise distances between `self.X_fit_` and `Y`. Parameters ---------- y : array-like, shape = (n_samples_y, n_features) Returns ------- kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_) Kernel matrix. Values are normalized to lie w...
def run_recipe_timed(task, recipe, rinput): """Run the recipe and count the time it takes.""" _logger.info('running recipe') now1 = datetime.datetime.now() task.state = 1 task.time_start = now1 # result = recipe(rinput) _logger.info('result: %r', result) task.result = result # ...
Run the recipe and count the time it takes.
def __fade_in(self): """ Starts the Widget fade in. """ self.__timer.stop() self.__vector = self.__fade_speed self.__timer.start()
Starts the Widget fade in.
def __replace_capall(sentence): """here we replace all instances of #CAPALL and cap the entire sentence. Don't believe that CAPALL is buggy anymore as it forces all uppercase OK? :param _sentence: """ # print "\nReplacing CAPITALISE: " if sentence is not None: while sentence.find...
here we replace all instances of #CAPALL and cap the entire sentence. Don't believe that CAPALL is buggy anymore as it forces all uppercase OK? :param _sentence:
def decorate_set_on_listener(prototype): """ Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)") """ # noinspection PyDictCreation,PyP...
Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)")
def list_members(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None): """ Returns the members of a list. List id or (slug and (owner_screen_name or owner_id)) are required """ assert list_id or (slug and (owner_screen_name or owner_id)) url = 'https://a...
Returns the members of a list. List id or (slug and (owner_screen_name or owner_id)) are required