code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def filter_by_analysis_period(self, analysis_period): """Filter the Data Collection based on an analysis period. Args: analysis period: A Ladybug analysis period Return: A new Data Collection with filtered data """ _filtered_data = self.filter_by_months(a...
Filter the Data Collection based on an analysis period. Args: analysis period: A Ladybug analysis period Return: A new Data Collection with filtered data
def runDeferred(self, deferred): """ Run the callables in C{deferred} using their associated scope stack. """ for handler, scope, offset in deferred: self.scopeStack = scope self.offset = offset handler()
Run the callables in C{deferred} using their associated scope stack.
def initialize_weights(self): """Randomly initializes the visible-to-hidden connections.""" n = self._outputSize m = self._inputSize self._Q = self._random.sample((n,m)) # Normalize the weights of each units for i in range(n): self._Q[i] /= np.sqrt( np.dot(s...
Randomly initializes the visible-to-hidden connections.
def discard(self, value): """Remove element *value* from the set if it is present.""" # Raise TypeError if value is not hashable hash(value) self.redis.srem(self.key, self._pickle(value))
Remove element *value* from the set if it is present.
def _check_d1_characters(name): # type: (bytes) -> None ''' A function to check that a name only uses d1 characters as defined by ISO9660. Parameters: name - The name to check. Returns: Nothing. ''' bytename = bytearray(name) for char in bytename: if char not in _allow...
A function to check that a name only uses d1 characters as defined by ISO9660. Parameters: name - The name to check. Returns: Nothing.
def controller(self): """ Check if multiple controllers are connected. :returns: Return the controller_id of the active controller. :rtype: string """ if hasattr(self, 'controller_id'): if len(self.controller_info['controllers']) > 1: raise T...
Check if multiple controllers are connected. :returns: Return the controller_id of the active controller. :rtype: string
def _get_bucket(self, bucket_name): '''get a bucket based on a bucket name. If it doesn't exist, create it. Parameters ========== bucket_name: the name of the bucket to get (or create). It should not contain google, and should be all lowercase with - ...
get a bucket based on a bucket name. If it doesn't exist, create it. Parameters ========== bucket_name: the name of the bucket to get (or create). It should not contain google, and should be all lowercase with - or underscores.
def listen(self, event): """Request that the Controller listen for and dispatch an event. Note: Even if the module that requested the listening is later unloaded, the Controller will continue to dispatch the event, there just might not be anything that cares about it. That's okay. ...
Request that the Controller listen for and dispatch an event. Note: Even if the module that requested the listening is later unloaded, the Controller will continue to dispatch the event, there just might not be anything that cares about it. That's okay.
def _get_grouper(obj, key=None, axis=0, level=None, sort=True, observed=False, mutated=False, validate=True): """ create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. This may be composed of multiple Grouping objects, indicating multip...
create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. This may be composed of multiple Grouping objects, indicating multiple groupers Groupers are ultimately index mappings. They can originate as: index mappings, keys to columns, functions, or Groupers...
def _prodterm_prime(lexer): """Return a product term' expression, eliminates left recursion.""" tok = next(lexer) # '&' FACTOR PRODTERM' if isinstance(tok, OP_and): factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return facto...
Return a product term' expression, eliminates left recursion.
def get_wcs(self, data_x, data_y): """Return (re_deg, dec_deg) for the (data_x, data_y) position based on any WCS associated with the loaded image. """ img = self.fitsimage.get_image() ra, dec = img.pixtoradec(data_x, data_y) return ra, dec
Return (re_deg, dec_deg) for the (data_x, data_y) position based on any WCS associated with the loaded image.
def set_table_cb(self, viewer, table): """Display the given table object.""" self.clear() tree_dict = OrderedDict() # Extract data as astropy table a_tab = table.get_data() # Fill masked values, if applicable try: a_tab = a_tab.filled() excep...
Display the given table object.
def disable_svc_notifications(self, service): """Disable notifications for a service Format of the line that triggers function call:: DISABLE_SVC_NOTIFICATIONS;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service ...
Disable notifications for a service Format of the line that triggers function call:: DISABLE_SVC_NOTIFICATIONS;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None
def list_resources(self, device_id): """List all resources registered to a connected device. .. code-block:: python >>> for r in api.list_resources(device_id): print(r.name, r.observable, r.uri) None,True,/3/0/1 Update,False,/5/0/3 .....
List all resources registered to a connected device. .. code-block:: python >>> for r in api.list_resources(device_id): print(r.name, r.observable, r.uri) None,True,/3/0/1 Update,False,/5/0/3 ... :param str device_id: The ID of the d...
def run_model(self, model_run, run_url): """Run model by sending message to RabbitMQ queue containing the run end experiment identifier. Messages are persistent to ensure that a worker will process process the run request at some point. Throws a EngineException if communication with the...
Run model by sending message to RabbitMQ queue containing the run end experiment identifier. Messages are persistent to ensure that a worker will process process the run request at some point. Throws a EngineException if communication with the server fails. Parameters ---------...
def warning(self, *msg): """ Prints a warning """ label = colors.yellow("WARNING") self._msg(label, *msg)
Prints a warning
def endpoints(self): """ Gets the Endpoints API client. Returns: Endpoints: """ if not self.__endpoints: self.__endpoints = Endpoints(self.__connection) return self.__endpoints
Gets the Endpoints API client. Returns: Endpoints:
def lithospheric_stress(step, trench, ridge, time): """calculate stress in the lithosphere""" timestep = step.isnap base_lith = step.geom.rcmb + 1 - 0.105 stressfld = step.fields['sII'][0, :, :, 0] stressfld = np.ma.masked_where(step.geom.r_mesh[0] < base_lith, stressfld) # stress integration ...
calculate stress in the lithosphere
def collect(self): """Publish all mdstat metrics.""" def traverse(d, metric_name=''): """ Traverse the given nested dict using depth-first search. If a value is reached it will be published with a metric name consisting of the hierarchically concatenated ...
Publish all mdstat metrics.
def aggregationToMonthsSeconds(interval): """ Return the number of months and seconds from an aggregation dict that represents a date and time. Interval is a dict that contain one or more of the following keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds', 'microseconds'...
Return the number of months and seconds from an aggregation dict that represents a date and time. Interval is a dict that contain one or more of the following keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds', 'microseconds'. For example: :: aggregationMicrosecon...
def address_checksum_and_decode(addr: str) -> Address: """ Accepts a string address and turns it into binary. Makes sure that the string address provided starts is 0x prefixed and checksummed according to EIP55 specification """ if not is_0x_prefixed(addr): raise InvalidAddress('Add...
Accepts a string address and turns it into binary. Makes sure that the string address provided starts is 0x prefixed and checksummed according to EIP55 specification
def contour(z, x=None, y=None, v=5, xlbl=None, ylbl=None, title=None, cfntsz=10, lfntsz=None, intrp='bicubic', alpha=0.5, cmap=None, vmin=None, vmax=None, fgsz=None, fgnm=None, fig=None, ax=None): """ Contour plot of a 2D surface. If a figure object is specified then the plot is draw...
Contour plot of a 2D surface. If a figure object is specified then the plot is drawn in that figure, and ``fig.show()`` is not called. The figure is closed on key entry 'q'. Parameters ---------- z : array_like 2d array of data to plot x : array_like, optional (default None) Val...
def check_honeypot(func=None, field_name=None): """ Check request.POST for valid honeypot field. Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if not specified. """ # hack to reverse arguments if called with str param if isinstance(func, six.string_types): ...
Check request.POST for valid honeypot field. Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if not specified.
def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier, prettyname, device): """ Calulates the difference between to point, and scales is to per second. """ if time_delta < 0: return value = (value_delta / time_delta) * multi...
Calulates the difference between to point, and scales is to per second.
def azimuth(lons1, lats1, lons2, lats2): """ Calculate the azimuth between two points or two collections of points. Parameters are the same as for :func:`geodetic_distance`. Implements an "alternative formula" from http://williams.best.vwh.net/avform.htm#Crs :returns: Azimuth as an an...
Calculate the azimuth between two points or two collections of points. Parameters are the same as for :func:`geodetic_distance`. Implements an "alternative formula" from http://williams.best.vwh.net/avform.htm#Crs :returns: Azimuth as an angle between direction to north from first point and ...
def __locate_scubainit(self): '''Determine path to scubainit binary ''' pkg_path = os.path.dirname(__file__) self.scubainit_path = os.path.join(pkg_path, 'scubainit') if not os.path.isfile(self.scubainit_path): raise ScubaError('scubainit not found at "{}"'.format(se...
Determine path to scubainit binary
def GetStartTime(self, problems=problems_module.default_problem_reporter): """Return the first time of the trip. TODO: For trips defined by frequency return the first time of the first trip.""" cursor = self._schedule._connection.cursor() cursor.execute( 'SELECT arrival_secs,departure_secs FROM ...
Return the first time of the trip. TODO: For trips defined by frequency return the first time of the first trip.
def sample(self, N=1): """Sample N trajectories from the posterior. Note ---- Performs the forward step in case it has not been performed. """ if not self.filt: self.forward() paths = np.empty((len(self.filt), N), np.int) paths[-1, ...
Sample N trajectories from the posterior. Note ---- Performs the forward step in case it has not been performed.
def StrIndexOf(input_string, substring, startIndex, bitlength): """ Return True if the concrete value of the input_string ends with suffix otherwise false. :param input_string: the string we want to check :param substring: the substring we want to find the index :param startIndex: the index to ...
Return True if the concrete value of the input_string ends with suffix otherwise false. :param input_string: the string we want to check :param substring: the substring we want to find the index :param startIndex: the index to start searching at :param bitlength: bitlength of the bitvector represen...
def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' def...
This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module.
def accuracy_helper(egg, match='exact', distance='euclidean', features=None): """ Computes proportion of words recalled Parameters ---------- egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If ...
Computes proportion of words recalled Parameters ---------- egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If exact, the presented and recalled items must be identical (default). If best, the recalled item ...
def align_bam(in_bam, ref_file, names, align_dir, data): """Perform direct alignment of an input BAM file with BWA using pipes. This avoids disk IO by piping between processes: - samtools sort of input BAM to queryname - bedtools conversion to interleaved FASTQ - bwa-mem alignment - samtool...
Perform direct alignment of an input BAM file with BWA using pipes. This avoids disk IO by piping between processes: - samtools sort of input BAM to queryname - bedtools conversion to interleaved FASTQ - bwa-mem alignment - samtools conversion to BAM - samtools sort to coordinate
def _CallWindowsNetCommand(parameters): ''' Call Windows NET command, used to acquire/configure network services settings. :param parameters: list of command line parameters :return: command output ''' import subprocess popen = subprocess.Popen(["net"] + parameters, stdout=subprocess.PIPE,...
Call Windows NET command, used to acquire/configure network services settings. :param parameters: list of command line parameters :return: command output
def register(self, token, regexp): """Register a token. Args: token (Token): the token class to register regexp (str): the regexp for that token """ self._tokens.append((token, re.compile(regexp)))
Register a token. Args: token (Token): the token class to register regexp (str): the regexp for that token
def turn_right(self, angle_degrees, rate=RATE): """ Turn to the right, staying on the spot :param angle_degrees: How far to turn (degrees) :param rate: The trurning speed (degrees/second) :return: """ flight_time = angle_degrees / rate self.start_turn_ri...
Turn to the right, staying on the spot :param angle_degrees: How far to turn (degrees) :param rate: The trurning speed (degrees/second) :return:
def walk_dependencies(root, visitor): """ Call visitor on root and all dependencies reachable from it in breadth first order. Args: root (component): component function or class visitor (function): signature is `func(component, parent)`. The call on root is `visitor(root, N...
Call visitor on root and all dependencies reachable from it in breadth first order. Args: root (component): component function or class visitor (function): signature is `func(component, parent)`. The call on root is `visitor(root, None)`.
def activities(self, *args, **kwargs): """Retrieve activities belonging to this scope. See :class:`pykechain.Client.activities` for available parameters. """ if self._client.match_app_version(label='wim', version='<2.0.0', default=True): return self._client.activities(*args,...
Retrieve activities belonging to this scope. See :class:`pykechain.Client.activities` for available parameters.
def delete(self, ids): """ Method to delete vlan's by their ids :param ids: Identifiers of vlan's :return: None """ url = build_uri_with_ids('api/v3/vlan/%s/', ids) return super(ApiVlan, self).delete(url)
Method to delete vlan's by their ids :param ids: Identifiers of vlan's :return: None
def execute(self): """"Run Checkstyle on all found non-synthetic source files.""" python_tgts = self.context.targets( lambda tgt: isinstance(tgt, (PythonTarget)) ) if not python_tgts: return 0 interpreter_cache = PythonInterpreterCache.global_instance() with self.invalidated(self.get...
Run Checkstyle on all found non-synthetic source files.
def add_details(file_name, title, artist, album, lyrics=""): ''' Adds the details to song ''' tags = EasyMP3(file_name) tags["title"] = title tags["artist"] = artist tags["album"] = album tags.save() tags = ID3(file_name) uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc'...
Adds the details to song
def lower_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts...
Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_camel("...
def __send_command( self, name, args=None, withcontent=False, extralines=None, nblines=-1): """Send a command to the server. If args is not empty, we concatenate the given command with the content of this list. If extralines is not empty, they are sent one by one...
Send a command to the server. If args is not empty, we concatenate the given command with the content of this list. If extralines is not empty, they are sent one by one to the server. (CLRF are automatically appended to them) We wait for a response just after the command has be...
def avail_sizes(call=None): ''' Return a dict of all available VM sizes on the cloud provider with relevant data. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ...
Return a dict of all available VM sizes on the cloud provider with relevant data.
def log_likelihood_pairwise(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 for winner, loser in data: loglik -= np.logaddexp(0, -(params[winner] - params[loser])) return loglik
Compute the log-likelihood of model parameters.
def read(self, size=None): """ Read a specified number of bytes from the file descriptor This method emulates the normal file descriptor's ``read()`` method and restricts the total number of bytes readable. If file descriptor is not present (e.g., ``close()`` method had been ca...
Read a specified number of bytes from the file descriptor This method emulates the normal file descriptor's ``read()`` method and restricts the total number of bytes readable. If file descriptor is not present (e.g., ``close()`` method had been called), ``ValueError`` is raised. ...
def file_root_name(name): """ Returns the root name of a file from a full file path. It will not raise an error if the result is empty, but an warning will be issued. """ base = os.path.basename(name) root = os.path.splitext(base)[0] if not root: warning = 'file_root_name return...
Returns the root name of a file from a full file path. It will not raise an error if the result is empty, but an warning will be issued.
def synthesize_software_module_info(modules, module_types): """ This function takes as input a dictionary of `modules` (mapping module IDs to :class:`~openag.models.SoftwareModule` objects) and a dictionary of `module_types` (mapping module type IDs to :class:`~openag.models.FirmwareModuleType` obje...
This function takes as input a dictionary of `modules` (mapping module IDs to :class:`~openag.models.SoftwareModule` objects) and a dictionary of `module_types` (mapping module type IDs to :class:`~openag.models.FirmwareModuleType` objects). For each module, it synthesizes the information in that module...
def setupArgparse(): """Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespac...
Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespace of arguments
def update_wish_list_by_id(cls, wish_list_id, wish_list, **kwargs): """Update WishList Update attributes of WishList This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_wish_list_by_id(wish...
Update WishList Update attributes of WishList This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_wish_list_by_id(wish_list_id, wish_list, async=True) >>> result = thread.get() :pa...
def is_job_config(config): """ Check whether given dict of config is job config """ try: # Every job has name if config['config']['job']['name'] is not None: return True except KeyError: return False except TypeError: return False except IndexError...
Check whether given dict of config is job config
def update(self, iterable={}, **kwargs): """ Updates recursively a self with a given iterable. TODO: rewrite this ugly stuff """ def _merge(a, *args): for key, value in itertools.chain(*args): if key in a and isinstance(value, (dict, Conf)): ...
Updates recursively a self with a given iterable. TODO: rewrite this ugly stuff
def _load_enums(root): """Returns {name: Enum}""" out = collections.OrderedDict() for elem in root.findall('enums/enum'): name = elem.attrib['name'] value = elem.attrib['value'] comment = elem.get('comment') out[name] = Enum(name, value, comment) return out
Returns {name: Enum}
def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): """ Alters either the weight or the edge_properties of an edge in the MoleculeGraph. :param from_index: int :param to_index: int :param new_weight: alter_edge does n...
Alters either the weight or the edge_properties of an edge in the MoleculeGraph. :param from_index: int :param to_index: int :param new_weight: alter_edge does not require that weight be altered. As such, by default, this is None. If weight is to be changed, it should be...
def cmd(send, msg, args): """Gets a random Reddit post. Syntax: {command} [subreddit] """ if msg and not check_exists(msg): send("Non-existant subreddit.") return subreddit = msg if msg else None send(random_post(subreddit, args['config']['api']['bitlykey']))
Gets a random Reddit post. Syntax: {command} [subreddit]
def query(self, coords, return_sigma=False): """ Returns r-band extinction, A_r, at the given coordinates. Can also return uncertainties. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. return_sigma (Optional[:obj:`bool`]): If ``True...
Returns r-band extinction, A_r, at the given coordinates. Can also return uncertainties. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. return_sigma (Optional[:obj:`bool`]): If ``True``, returns the uncertainty in extinction as well...
def makepipecomponent(idf, pname): """make a pipe component generate inlet outlet names""" apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname) apipe.Inlet_Node_Name = "%s_inlet" % (pname,) apipe.Outlet_Node_Name = "%s_outlet" % (pname,) return apipe
make a pipe component generate inlet outlet names
def _match_files_flat_hierarchy(self, text_files, audio_files): """ Match audio and text files in flat hierarchies. Two files match if their names, once removed the file extension, are the same. Examples: :: foo/text/a.txt foo/audio/a.mp3 => match: ["a", "f...
Match audio and text files in flat hierarchies. Two files match if their names, once removed the file extension, are the same. Examples: :: foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"] foo/text/a.txt foo/audio/b.mp3 => no ...
def parse_requested_expands(query_key, request): """ Extracts the value of the expand query string parameter from a request. Supports comma separated lists. :param query_key: The name query string parameter. :param request: Request instance. :return: List of strings representing the values of t...
Extracts the value of the expand query string parameter from a request. Supports comma separated lists. :param query_key: The name query string parameter. :param request: Request instance. :return: List of strings representing the values of the expand query string value.
def _scalar_power(self, f, p, out): """Compute ``p``-th power of ``f`` for ``p`` scalar.""" # Avoid infinite recursions by making a copy of the function f_copy = f.copy() def pow_posint(x, n): """Power function for positive integer ``n``, out-of-place.""" if isin...
Compute ``p``-th power of ``f`` for ``p`` scalar.
def find_pulls(self, testpulls=None): """Finds a list of new pull requests that need to be processed. :arg testpulls: a list of tserver.FakePull instances so we can test the code functionality without making live requests to github. """ #We check all the repositories installed...
Finds a list of new pull requests that need to be processed. :arg testpulls: a list of tserver.FakePull instances so we can test the code functionality without making live requests to github.
def toggle_buttons(self): """Turn buttons on and off.""" all_time_on = self.all_time.get_value() all_chan_on = self.all_chan.get_value() self.times['beg'].setEnabled(not all_time_on) self.times['end'].setEnabled(not all_time_on) self.idx_chan.setEnabled(not all_chan_on)
Turn buttons on and off.
def get_selinux_status(): """ get SELinux status of host :return: string, one of Enforced, Permissive, Disabled """ getenforce_command_exists() # alternatively, we could read directly from /sys/fs/selinux/{enforce,status}, but status is # empty (why?) and enforce doesn't tell whether SELinu...
get SELinux status of host :return: string, one of Enforced, Permissive, Disabled
def update(self, *args, **kwargs): """ Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: ...
Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: All keyword arguments are stored in header direct...
def to_designspace_instances(self): """Write instance data from self.font to self.designspace.""" for instance in self.font.instances: if self.minimize_glyphs_diffs or ( is_instance_active(instance) and _is_instance_included_in_family(self, instance) ): _to_de...
Write instance data from self.font to self.designspace.
def insured_losses(losses, deductible, insured_limit): """ :param losses: an array of ground-up loss ratios :param float deductible: the deductible limit in fraction form :param float insured_limit: the insured limit in fraction form Compute insured losses for the given asset and losses, from the p...
:param losses: an array of ground-up loss ratios :param float deductible: the deductible limit in fraction form :param float insured_limit: the insured limit in fraction form Compute insured losses for the given asset and losses, from the point of view of the insurance company. For instance: >>> i...
def on_data(self, raw_data): """Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection. """ data = json.loads(raw_data) message_type = data['meta'].get('type...
Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection.
def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"): """ A context manager for convenience in writing a file or directory in an atomic way. Set up a temporary name, then rename it after the operation is done, optionally making a backup of the previous file or director...
A context manager for convenience in writing a file or directory in an atomic way. Set up a temporary name, then rename it after the operation is done, optionally making a backup of the previous file or directory, if present.
def stupid_hack(most=10, wait=None): """Return a random time between 1 - 10 Seconds.""" # Stupid Hack For Public Cloud so it is not overwhelmed with API requests. if wait is not None: time.sleep(wait) else: time.sleep(random.randrange(1, most))
Return a random time between 1 - 10 Seconds.
def read_pl_dataset(infile): """ Description: Read from disk a Plackett-Luce dataset. Parameters: infile: open file object from which to read the dataset """ m, n = [int(i) for i in infile.readline().split(',')] gamma = np.array([float(f) for f in infile.readline().spli...
Description: Read from disk a Plackett-Luce dataset. Parameters: infile: open file object from which to read the dataset
def get_livestate(self): """Get the SatelliteLink live state. The live state is a tuple information containing a state identifier and a message, where: state is: - 0 for an up and running satellite - 1 if the satellite is not reachale - 2 if the satellite...
Get the SatelliteLink live state. The live state is a tuple information containing a state identifier and a message, where: state is: - 0 for an up and running satellite - 1 if the satellite is not reachale - 2 if the satellite is dead - 3 else (not a...
def validate(self, validator=None, skip_relations=False): """Validate a GTFS :param validator: a ValidationReport :param (bool) skip_relations: skip validation of relations between entities (e.g. stop_times to stops) :return: """ validator = validation.make_validator(validator) self.log('Lo...
Validate a GTFS :param validator: a ValidationReport :param (bool) skip_relations: skip validation of relations between entities (e.g. stop_times to stops) :return:
def delete_feed(self, pid): """Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLi...
Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a...
def save(self) -> None: """Saves model to the save_path, provided in config. The directory is already created by super().__init__, which is called in __init__ of this class""" path = str(self.save_path.absolute()) log.info('[saving model to {}]'.format(path)) self._net.save(path)
Saves model to the save_path, provided in config. The directory is already created by super().__init__, which is called in __init__ of this class
def from_url(cls, url, **kwargs): """Create a client from a url.""" url = urllib3.util.parse_url(url) if url.host: kwargs.setdefault('host', url.host) if url.port: kwargs.setdefault('port', url.port) if url.scheme == 'https': kwargs.setdefaul...
Create a client from a url.
def LockRetryWrapper(self, subject, retrywrap_timeout=1, retrywrap_max_timeout=10, blocking=True, lease_time=None): """Retry a DBSubjectLock until it succeeds. Args: subject: The subject whi...
Retry a DBSubjectLock until it succeeds. Args: subject: The subject which the lock applies to. retrywrap_timeout: How long to wait before retrying the lock. retrywrap_max_timeout: The maximum time to wait for a retry until we raise. blocking: If False, raise on first lock failure. ...
def parse_uci(self, uci: str) -> Move: """ Parses the given move in UCI notation. Supports both Chess960 and standard UCI notation. The returned move is guaranteed to be either legal or a null move. :raises: :exc:`ValueError` if the move is invalid or illegal in the ...
Parses the given move in UCI notation. Supports both Chess960 and standard UCI notation. The returned move is guaranteed to be either legal or a null move. :raises: :exc:`ValueError` if the move is invalid or illegal in the current position (but not a null move).
def add_prefix_from_pool(arg, opts): """ Add prefix using from-pool to NIPAP """ args = {} # sanity checking if 'from-pool' in opts: res = Pool.list({ 'name': opts['from-pool'] }) if len(res) == 0: print("No pool named '%s' found." % opts['from-pool'], file=sys.stderr) ...
Add prefix using from-pool to NIPAP
def _parse_vars_tbl(self, var_tbl): """Parse a table of variable bindings (dictionary with key = variable name)""" # Find the length of each variable to infer T T = self._check_forward_mode_input_dict(var_tbl) # The shape of X based on T and m shape = (T, 1) # Initializ...
Parse a table of variable bindings (dictionary with key = variable name)
def _find_proj_root(): # type: () -> Optional[str] """ Find the project path by going up the file tree. This will look in the current directory and upwards for the pelconf file (.yaml or .py) """ proj_files = frozenset(('pelconf.py', 'pelconf.yaml')) curr = os.getcwd() while curr.start...
Find the project path by going up the file tree. This will look in the current directory and upwards for the pelconf file (.yaml or .py)
def enclosing_frame(frame=None, level=2): """Get an enclosing frame that skips decorator code""" frame = frame or sys._getframe(level) while frame.f_globals.get('__name__') == __name__: frame = frame.f_back return frame
Get an enclosing frame that skips decorator code
def save_file(self, obj): # pylint: disable=too-many-branches """Save a file""" try: import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute except ImportError: import io as pystringIO # pylint: disable=reimported if not hasattr(obj, 'name') or not hasattr(obj,...
Save a file
def checkpoint(self, message, header=None, delay=0, **kwargs): """Send a message to the current recipe destination. This can be used to keep a state for longer processing tasks. :param delay: Delay transport of message by this many seconds """ if not self.transport: r...
Send a message to the current recipe destination. This can be used to keep a state for longer processing tasks. :param delay: Delay transport of message by this many seconds
def do_struct(self, subcmd, opts, message): """${cmd_name}: get the structure of the specified message ${cmd_usage} ${cmd_option_list} """ client = MdClient(self.maildir, filesystem=self.filesystem) as_json = getattr(opts, "json", False) client.getstruct(message,...
${cmd_name}: get the structure of the specified message ${cmd_usage} ${cmd_option_list}
def feature_enabled(self, feature_name): """ Indicates whether the specified feature is enabled for the CPC of this partition. The HMC must generally support features, and the specified feature must be available for the CPC. For a list of available features, see section...
Indicates whether the specified feature is enabled for the CPC of this partition. The HMC must generally support features, and the specified feature must be available for the CPC. For a list of available features, see section "Features" in the :term:`HMC API`, or use the :meth:...
def file_loc(): """Return file and line number""" import sys import inspect try: raise Exception except: file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:]) line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno return "{}:{}".format(fil...
Return file and line number
def setup_panel_params(self, coord): """ Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate """ if not self.panel_scales_x: raise PlotnineError('Missing an x scale') if not...
Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate
def as_error(self) : "fills in and returns an Error object that reports the specified error name and message." result = dbus.Error.init() result.set(self.args[0], self.args[1]) return \ result
fills in and returns an Error object that reports the specified error name and message.
def get_for_model(self, obj): """Returns the tags for a specific model/content type.""" qs = Tag.objects.language(get_language()) qs = qs.filter( tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj)) # NOQA return qs.distinct()
Returns the tags for a specific model/content type.
def delete_pool(name): """Delete pool.""" try: pool = pool_api.delete_pool(name=name) except AirflowException as err: _log.error(err) response = jsonify(error="{}".format(err)) response.status_code = err.status_code return response else: return jsonify(poo...
Delete pool.
def serialize(script_string): ''' str -> bytearray ''' string_tokens = script_string.split() serialized_script = bytearray() for token in string_tokens: if token == 'OP_CODESEPARATOR' or token == 'OP_PUSHDATA4': raise NotImplementedError('{} is a bad idea.'.format(token)) ...
str -> bytearray
def get_substrates(self, material_id, number=50, orient=None): """ Get a substrate list for a material id. The list is in order of increasing elastic energy if a elastic tensor is available for the material_id. Otherwise the list is in order of increasing matching area. ...
Get a substrate list for a material id. The list is in order of increasing elastic energy if a elastic tensor is available for the material_id. Otherwise the list is in order of increasing matching area. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'. ...
def main(): """Define the CLI inteface/commands.""" arguments = docopt(__doc__) cfg_filename = pkg_resources.resource_filename( 'knowledge_base', 'config/virtuoso.ini' ) kb = KnowledgeBase(cfg_filename) # the user has issued a `find` command if arguments["find"]: sea...
Define the CLI inteface/commands.
def one(self, command, params=None): """ Возвращает первую строку ответа, полученного через query > db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID}) :param command: SQL запрос :param params: Параметры для prepared statements :rtype: dict """ ...
Возвращает первую строку ответа, полученного через query > db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID}) :param command: SQL запрос :param params: Параметры для prepared statements :rtype: dict
def create_actor_delaunay(pts, color, **kwargs): """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloat...
Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list...
def subdevicenames(self) -> Tuple[str, ...]: """A |tuple| containing the (sub)device names. Property |NetCDFVariableFlat.subdevicenames| clarifies which row of |NetCDFVariableAgg.array| contains which time series. For 0-dimensional series like |lland_inputs.Nied|, the plain devi...
A |tuple| containing the (sub)device names. Property |NetCDFVariableFlat.subdevicenames| clarifies which row of |NetCDFVariableAgg.array| contains which time series. For 0-dimensional series like |lland_inputs.Nied|, the plain device names are returned >>> from hydpy.core.examp...
def get_array_for_fit(observables: dict, track_pt_bin: int, jet_pt_bin: int) -> histogram.Histogram1D: """ Get a Histogram1D associated with the selected jet and track pt bins. This is often used to retrieve data for fitting. Args: observables (dict): The observables from which the hist should be ...
Get a Histogram1D associated with the selected jet and track pt bins. This is often used to retrieve data for fitting. Args: observables (dict): The observables from which the hist should be retrieved. track_pt_bin (int): Track pt bin of the desired hist. jet_ptbin (int): Jet pt bin of...
def get(self, *args, **kwargs): """Retrieve a collection of objects""" self.before_get(args, kwargs) qs = QSManager(request.args, self.schema) objects_count, objects = self.get_collection(qs, kwargs) schema_kwargs = getattr(self, 'get_schema_kwargs', dict()) schema_kwa...
Retrieve a collection of objects
def upload_image(vol, img, offset, parallel=1, manual_shared_memory_id=None, manual_shared_memory_bbox=None, manual_shared_memory_order='F'): """Upload img to vol with offset. This is the primary entry point for uploads.""" global NON_ALIGNED_WRITE if not np.issubdtype(img.dtype, np.dtype(vol.dtype).type): ...
Upload img to vol with offset. This is the primary entry point for uploads.
def tuning_config(tuner, inputs, job_name=None): """Export Airflow tuning config from an estimator Args: tuner (sagemaker.tuner.HyperparameterTuner): The tuner to export tuning config from. inputs: Information about the training data. Please refer to the ``fit()`` method of the ...
Export Airflow tuning config from an estimator Args: tuner (sagemaker.tuner.HyperparameterTuner): The tuner to export tuning config from. inputs: Information about the training data. Please refer to the ``fit()`` method of the associated estimator in the tuner, as this can take any ...
def _add_trits(left, right): # type: (int, int) -> int """ Adds two individual trits together. The result is always a single trit. """ res = left + right return res if -2 < res < 2 else (res < 0) - (res > 0)
Adds two individual trits together. The result is always a single trit.