code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def open(self): """ Open TCP socket and set it as escpos device """ self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket for %s" % self.host
Open TCP socket and set it as escpos device
def constraints(self): """ Constraints applied to the population. """ try: return self._constraints except AttributeError: self._constraints = ConstraintDict() return self._constraints
Constraints applied to the population.
def load_config(self, **kwargs): """Load the configuration for the user or seed it with defaults. :return: Boolean if successful """ virgin_config = False if not os.path.exists(CONFIG_PATH): virgin_config = True os.makedirs(CONFIG_PATH) if not os....
Load the configuration for the user or seed it with defaults. :return: Boolean if successful
def format(collection, **params): """Truns a python object into a ZIP file.""" binary = io.BytesIO() with zipfile.ZipFile(binary, 'w') as zip_: now = datetime.datetime.utcnow().timetuple() for filename, content in collection: content_type, encoding = mimetypes.guess_type(filename...
Truns a python object into a ZIP file.
def getAllPlatformNamesByTag (mode = None): """Returns the platforms in the framework grouped by tags. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"]. """ tags = {} allPlatformsList = getAllPlatformObjects(mode) # Iterating the list of...
Returns the platforms in the framework grouped by tags. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"].
def next(self): """Advances to and returns the next token or returns EndOfFile""" self.index += 1 t = self.peek() if not self.depth: self._cut() return t
Advances to and returns the next token or returns EndOfFile
def triangle(self, x1, y1, x2, y2, x3, y3, color="black", outline=False, outline_color="black"): """ Draws a triangle between 3 points :param int x1: The x position of the starting point. :param int y1: The y position of the starting point. :param int x...
Draws a triangle between 3 points :param int x1: The x position of the starting point. :param int y1: The y position of the starting point. :param int x2: The x position of the middle point. :param int y2: The y position of the middle p...
def wheel(self, clear_load): ''' Send a master control function back to the wheel system ''' # All wheel ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load) # Authenticate auth_check = self.loadauth.check_authen...
Send a master control function back to the wheel system
def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """ def decorator(listener): self.listeners[event].append(listener) return listener return decorator
Create a listener from a decorated function. :param event: Event to listen to.
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the Bezier component """ if not self.points: return gc.save_state() try: gc.set_fill_color(self.pen.fill_color_) gc.set_line_width(self.pen.line_width) gc.set_stroke_color(sel...
Draws the Bezier component
def rison(schema=None): """ Use this decorator to parse URI *Rison* arguments to a python data structure, your method gets the data structure on kwargs['rison']. Response is HTTP 400 if *Rison* is not correct:: class ExampleApi(BaseApi): @expose('/ris...
Use this decorator to parse URI *Rison* arguments to a python data structure, your method gets the data structure on kwargs['rison']. Response is HTTP 400 if *Rison* is not correct:: class ExampleApi(BaseApi): @expose('/risonjson') @rison() ...
def add_filter(self, filter_id, description): """ Add a filter line to the header. Arguments: filter_id (str): The id of the filter line description (str): A description of the info line """ filter_line = '##FILTER=<ID={0},Description="{1}">'.format( ...
Add a filter line to the header. Arguments: filter_id (str): The id of the filter line description (str): A description of the info line
def give_satellite_json(self): """Get the json information for a satellite. This to provide information that will be exposed by a daemon on its HTTP interface. :return: dictionary of information common to all the links :rtype: dict """ daemon_properties = ['type', 'name...
Get the json information for a satellite. This to provide information that will be exposed by a daemon on its HTTP interface. :return: dictionary of information common to all the links :rtype: dict
def as_strings(self): """Return the entire Conf as nginx config strings.""" ret = [] for x in self.children: if isinstance(x, (Key, Comment)): ret.append(x.as_strings) else: for y in x.as_strings: ret.append(y) i...
Return the entire Conf as nginx config strings.
def parse_environment_file_list(names, world_size=(60, 60)): """ Extract information about spatial resources from all environment files in a list. Arguments: names - a list of strings representing the paths to the environment files. world_size - a tuple representing the x and y coordinates of t...
Extract information about spatial resources from all environment files in a list. Arguments: names - a list of strings representing the paths to the environment files. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a dictionary in ...
def gen_stats(datain): """**Calculate lightning statitics and return a dictionary** Using a raw data in certain time interval calculate mean, std, min, max value for detection error or number of stations. :paramter datain: vector with detection error or number of stations :Example: >>> gen_s...
**Calculate lightning statitics and return a dictionary** Using a raw data in certain time interval calculate mean, std, min, max value for detection error or number of stations. :paramter datain: vector with detection error or number of stations :Example: >>> gen_stats(lighning_data['#sta'])
def InjectionStatistics(campaign=0, clobber=False, model='nPLD', plot=True, show=True, **kwargs): ''' Computes and plots the statistics for injection/recovery tests. :param int campaign: The campaign number. Default 0 :param str model: The :py:obj:`everest` model name :param...
Computes and plots the statistics for injection/recovery tests. :param int campaign: The campaign number. Default 0 :param str model: The :py:obj:`everest` model name :param bool plot: Default :py:obj:`True` :param bool show: Show the plot? Default :py:obj:`True`. \ If :py:obj:`False`, retur...
def create_redis_client(self): """Create a redis client.""" return ray.services.create_redis_client( self._redis_address, self._ray_params.redis_password)
Create a redis client.
def run(self): """The target routine called to start thread activity.""" idle_watchers = [] while True: try: if self._work_queue.empty() and len(idle_watchers) > 0: for watcher in idle_watchers: try: ...
The target routine called to start thread activity.
def cmd_speech(self, args): '''speech commands''' usage = "usage: speech <say>" if len(args) < 1: print(usage) return if args[0] == "say": if len(args) < 2: print("usage: speech say <text to say>") return se...
speech commands
def state_reachable(subsystem): """Return whether a state can be reached according to the network's TPM.""" # If there is a row `r` in the TPM such that all entries of `r - state` are # between -1 and 1, then the given state has a nonzero probability of being # reached from some state. # First we ta...
Return whether a state can be reached according to the network's TPM.
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first ti...
Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into thi...
def handleLogOutput(self, output): """ Write outputs to output tap file. :param outputs: (iter) some outputs. """ #raise Exception('MULTI-LINE DUMMY\nMULTI-LINE DUMMY') if self._tapFileOut is not None: for k in range(len(output)): print >> self._tapFileOut, output[k], print ...
Write outputs to output tap file. :param outputs: (iter) some outputs.
def info(self, text): """ Posts an info message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their ti...
Posts an info message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time...
def export_capacities(self): """ List Mimetypes that current object can export to """ return [export for cls in getmro(type(self)) if hasattr(cls, "EXPORT_TO") for export in cls.EXPORT_TO]
List Mimetypes that current object can export to
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]: """ Takes gold and predicted answer sets and first finds a greedy 1-1 alignment between them and gets maximum metric values over all the answers """ f1_scores = [] for gold_index, gold_item in enumerate(gold): ...
Takes gold and predicted answer sets and first finds a greedy 1-1 alignment between them and gets maximum metric values over all the answers
def UpdateMedia(self, media_link, readable_stream, options=None): """Updates a media and returns it. :param str media_link: The link to the media. :param (file-like stream object) readable_stream: :param dict options: The request options for the request. ...
Updates a media and returns it. :param str media_link: The link to the media. :param (file-like stream object) readable_stream: :param dict options: The request options for the request. :return: The updated Media. :rtype: str or f...
def add_flags(self, flag_name, flags, target_name=None, configuration_name=None): """ Adds the given flags to the flag_name section of the target on the configurations :param flag_name: name of the flag to be added the values to :param flags: A string or array of strings :param t...
Adds the given flags to the flag_name section of the target on the configurations :param flag_name: name of the flag to be added the values to :param flags: A string or array of strings :param target_name: Target name or list of target names to add the flag to or None for every target :p...
def _get_style_id_from_style(self, style, style_type): """ Return the id of *style*, or |None| if it is the default style of *style_type*. Raises |ValueError| if style is not of *style_type*. """ if style.type != style_type: raise ValueError( "assigned...
Return the id of *style*, or |None| if it is the default style of *style_type*. Raises |ValueError| if style is not of *style_type*.
def find_atoms_near_atom(self, source_atom, search_radius, atom_hit_cache = set(), atom_names_to_include = set(), atom_names_to_exclude = set(), restrict_to_CA = False): '''It is advisable to set up and use an atom hit cache object. This reduces the number of distance calculations and gives better performance. ...
It is advisable to set up and use an atom hit cache object. This reduces the number of distance calculations and gives better performance. See find_sidechain_atoms_within_radius_of_residue_objects for an example of how to set this up e.g. atom_hit_cache = set() for x in some_loo...
def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
test if object is dict like
def set_headline(self, level, message, timestamp=None, now_reference=None): """Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An option...
Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An optional monotonic value in seconds for when the message was created now_referenc...
def geopy_geolocator(): '''Lazy loader for geocoder from geopy. This currently loads the `Nominatim` geocode and returns an instance of it, taking ~2 us. ''' global geolocator if geolocator is None: try: from geopy.geocoders import Nominatim except ImportError: ...
Lazy loader for geocoder from geopy. This currently loads the `Nominatim` geocode and returns an instance of it, taking ~2 us.
def project(v, n): """ Project Vector v onto plane with normal vector n. """ return v - matmul(v, n) * n / (norm(n) ** 2.0)
Project Vector v onto plane with normal vector n.
def _modem_sm(self): """Handle modem response state machine.""" import datetime read_timeout = READ_IDLE_TIMEOUT while self.ser: try: resp = self.read(read_timeout) except (serial.SerialException, SystemExit, TypeError): _LOGGER.de...
Handle modem response state machine.
def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None, num_readers=1): """Contruct batches of training or evaluation examples from the image dataset. Args: dataset: instance of Dataset class specifying the dataset. See dataset.py for details. batch_size: integer ...
Contruct batches of training or evaluation examples from the image dataset. Args: dataset: instance of Dataset class specifying the dataset. See dataset.py for details. batch_size: integer train: boolean num_preprocess_threads: integer, total number of preprocessing threads num_readers: int...
def opensignals_hierarchy(root=None, update=False, clone=False): """ Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically. ---------- Parameters ---------- root : None or str The file path where the OpenSignalsTools Environment will be stored. updat...
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically. ---------- Parameters ---------- root : None or str The file path where the OpenSignalsTools Environment will be stored. update : bool If True the old files will be replaced by the new ones. ...
def early_stop(stopping_rounds, maximize=False, verbose=True): """Create a callback that activates early stoppping. Validation error needs to decrease at least every **stopping_rounds** round(s) to continue training. Requires at least one item in **evals**. If there's more than one, will use the la...
Create a callback that activates early stoppping. Validation error needs to decrease at least every **stopping_rounds** round(s) to continue training. Requires at least one item in **evals**. If there's more than one, will use the last. Returns the model from the last iteration (not the best one). ...
def transformer_revnet_big(): """Base hparams for TransformerRevnet.""" hparams = transformer_revnet_base() # The TransformerRevnet uses significantly less memory than the Transformer. # Increase batch size and model size. hparams.batch_size *= 2 hparams.hidden_size *= 2 hparams.num_heads *= 2 hparams....
Base hparams for TransformerRevnet.
def error_response(self, exception): # type: (Exception) -> Tuple[Callback, Error] """Create an Error Response object to signal an error""" response = Error(id=self.id, message=exception) log.exception("Exception raised for request %s", self) return self.callback, response
Create an Error Response object to signal an error
def compute_stability_classification(self, predicted_data, record, dataframe_record): '''Calculate the stability classification for this case.''' stability_classification, stability_classication_x_cutoff, stability_classication_y_cutoff = None, self.stability_classication_x_cutoff, self.stability_classi...
Calculate the stability classification for this case.
def log_ndtr(x, series_order=3, name="log_ndtr"): """Log Normal distribution function. For details of the Normal distribution function see `ndtr`. This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or using an asymptotic series. Specifically: - For `x > upper_segment`, use the appro...
Log Normal distribution function. For details of the Normal distribution function see `ndtr`. This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or using an asymptotic series. Specifically: - For `x > upper_segment`, use the approximation `-ndtr(-x)` based on `log(1-x) ~= -x, x <<...
def getEdges(self, fromVol): """ Return the edges available from fromVol. """ return [ self.toObj.diff(diff) for diff in self._client.getEdges(self.toArg.vol(fromVol)) ]
Return the edges available from fromVol.
def random_samples(self, n): """ Returns a random sampling of given size from the existing samples. :param n: Number of samples :return: :class:`pandas.DataFrame` of length ``n`` with random samples. """ samples = self.samples inds = rand...
Returns a random sampling of given size from the existing samples. :param n: Number of samples :return: :class:`pandas.DataFrame` of length ``n`` with random samples.
def update_app(AppId=None, Name=None, Description=None, DataSources=None, Type=None, AppSource=None, Domains=None, EnableSsl=None, SslConfiguration=None, Attributes=None, Environment=None): """ Updates a specified app. See also: AWS API Documentation :example: response = client.update_app( ...
Updates a specified app. See also: AWS API Documentation :example: response = client.update_app( AppId='string', Name='string', Description='string', DataSources=[ { 'Type': 'string', 'Arn': 'string', 'Database...
def _rename_file(self, line=""): """Rename an ontology 2016-04-11: not a direct command anymore """ if not self.all_ontologies: self._help_nofiles() else: out = [] for each in self.all_ontologies: if line in each: ...
Rename an ontology 2016-04-11: not a direct command anymore
async def update_activity(self, context: TurnContext, activity: Activity): """ Replaces an activity that was previously sent to a channel. It should be noted that not all channels support this feature. :param context: :param activity: :return: """ try: ...
Replaces an activity that was previously sent to a channel. It should be noted that not all channels support this feature. :param context: :param activity: :return:
def chpl_type_name(self): """Returns iterator or method or '' depending on object type.""" if not self.objtype.endswith('method'): return '' elif self.objtype.startswith('iter'): return 'iterator' elif self.objtype == 'method': return 'method' ...
Returns iterator or method or '' depending on object type.
def parse_nate_sims(path): ''' parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly for every particle in the simulation at t=0. The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles. :return: ''' ...
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly for every particle in the simulation at t=0. The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles. :return:
def stop(context): """Stop application server. """ config = context.obj["config"] pidfile = select(config, "application.pidfile", DEFAULT_PIDFILE) daemon_stop(pidfile)
Stop application server.
def neighbours(self, v, distance=None, fetch_vector_filters=None, vector_filters=None): """ Hashes vector v, collects all candidate vectors from the matching buckets in storage, applys the (optional) distance function and finally t...
Hashes vector v, collects all candidate vectors from the matching buckets in storage, applys the (optional) distance function and finally the (optional) filter function to construct the returned list of either (vector, data, distance) tuples or (vector, data) tuples.
def set_sni_params(self, name, cert, key, ciphers=None, client_ca=None, wildcard=False): """Allows setting Server Name Identification (virtual hosting for SSL nodes) params. * http://uwsgi.readthedocs.io/en/latest/SNI.html :param str|unicode name: Node/server/host name. :param str|uni...
Allows setting Server Name Identification (virtual hosting for SSL nodes) params. * http://uwsgi.readthedocs.io/en/latest/SNI.html :param str|unicode name: Node/server/host name. :param str|unicode cert: Certificate file. :param str|unicode key: Private key file. :param str|...
def yVal_xml(self): """ Return the ``<c:yVal>`` element for this series as unicode text. This element contains the Y values for this series. """ return self._yVal_tmpl.format(**{ 'nsdecls': '', 'numRef_xml': self.numRef_xml( self._series...
Return the ``<c:yVal>`` element for this series as unicode text. This element contains the Y values for this series.
def dbfpack(fn, usecols=None): """Return a ChannelPack instance loaded with dbf data file fn. This is a lazy function to get a loaded instance, using pulldbf module.""" loadfunc = pulldbf.dbf_asdict cp = ChannelPack(loadfunc) cp.load(fn, usecols) names = pulldbf.channel_names(fn, usecols) ...
Return a ChannelPack instance loaded with dbf data file fn. This is a lazy function to get a loaded instance, using pulldbf module.
def gen(function): """ Allows using a generator to chain together reversible actions. This decorator may be added to a generator that yields reversible actions (any object with a ``.forwards()`` and ``.backwards()`` method). These may be constructed manually or via :py:func:`reversible.action`. The...
Allows using a generator to chain together reversible actions. This decorator may be added to a generator that yields reversible actions (any object with a ``.forwards()`` and ``.backwards()`` method). These may be constructed manually or via :py:func:`reversible.action`. The decorated function, when c...
def setDerivedTypeContents(self, extensions=None, restrictions=None): """For derived types set appropriate parameter and """ if extensions: ofwhat = list(self.ofwhat) if type(extensions) in _seqtypes: ofwhat += list(extensions) else: ...
For derived types set appropriate parameter and
def __manage_connections(self, ccallbacks=None): """This runs as the main connection management greenlet.""" _logger.info("Running client.") # Create message-handler. if self.__message_handler_cls is not None: # TODO(dustin): Move this to another thread if we can mix multithreading wi...
This runs as the main connection management greenlet.
def classify(self, dataset): """ Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ...
Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ---------- dataset : SFrame ...
def _setAttr(self, attr, value): """ Subclasses may override this method. If a subclass does not override this method, it must implement '_set_attributeName' methods for all Info methods. """ meth = "_set_%s" % attr if not hasattr(self, meth): ...
Subclasses may override this method. If a subclass does not override this method, it must implement '_set_attributeName' methods for all Info methods.
def switch_to_plain_text(self): """Switch to plain text mode""" self.rich_help = False self.plain_text.show() self.rich_text.hide() self.plain_text_action.setChecked(True)
Switch to plain text mode
def _already_cutoff_filtered(in_file, filter_type): """Check if we have a pre-existing cutoff-based filter file from previous VQSR failure. """ filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type) return utils.file_exists(filter_file)
Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
def validate_django_compatible_with_python(): """ Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be comp...
Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be compatible.
def _populate_profile_from_group_memberships(self, profile): """ Populate the given profile object from AUTH_LDAP_PROFILE_FLAGS_BY_GROUP. Returns True if the profile was modified. """ save_profile = False for field, group_dns in self.settings.PROFILE_FLAGS_BY_GROUP.items...
Populate the given profile object from AUTH_LDAP_PROFILE_FLAGS_BY_GROUP. Returns True if the profile was modified.
def make_serviceitem_name(name, condition='is', negate=False, preserve_case=False): """ Create a node for ServiceItem/name :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/name' content_type = 'string' content = name ii_n...
Create a node for ServiceItem/name :return: A IndicatorItem represented as an Element node
def declare(self, context=None): """ Use self.definition to declare the table in the schema. """ try: sql, uses_external = declare(self.full_table_name, self.definition, context) if uses_external: sql = sql.format(external_table=self.external_table...
Use self.definition to declare the table in the schema.
def copy(self): """Return a copy of the polynomial.""" return Poly(self.A.copy(), self.dim, self.shape, self.dtype)
Return a copy of the polynomial.
def z(self,*args,**kwargs): """ NAME: z PURPOSE: return vertical height INPUT: t - (optional) time at which to get the vertical height ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to over...
NAME: z PURPOSE: return vertical height INPUT: t - (optional) time at which to get the vertical height ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to override Object-wide default for using a physical sc...
def get_ticker(self): """Return the latest ticker information. :return: Latest ticker information. :rtype: dict """ self._log('get ticker') return self._rest_client.get( endpoint='/ticker', params={'book': self.name} )
Return the latest ticker information. :return: Latest ticker information. :rtype: dict
def push_state(self): """ Push a copy of the topmost state on top of the state stack, returns the new top. """ new = dict(self.states[-1]) self.states.append(new) return self.state
Push a copy of the topmost state on top of the state stack, returns the new top.
def normalize(email_address, resolve=True): """Return the normalized email address, removing :param str email_address: The normalized email address :param bool resolve: Resolve the domain :rtype: str """ address = utils.parseaddr(email_address) local_part, domain_part = address[1].lower()....
Return the normalized email address, removing :param str email_address: The normalized email address :param bool resolve: Resolve the domain :rtype: str
def serialize_header(self, pyobj, typecode=None, **kw): '''Serialize a Python object in SOAP-ENV:Header, make sure everything in Header unique (no #href). Must call serialize first to create a document. Parameters: pyobjs -- instances to serialize in SOAP Header ...
Serialize a Python object in SOAP-ENV:Header, make sure everything in Header unique (no #href). Must call serialize first to create a document. Parameters: pyobjs -- instances to serialize in SOAP Header typecode -- default typecode
def read(filename): """ reads a Horn SAT formula from a text file :file format: # comment A # clause with unique positive literal :- A # clause with unique negative literal A :- B, C, D # clause where A is positive and B,C,D negative # variables are strings without ...
reads a Horn SAT formula from a text file :file format: # comment A # clause with unique positive literal :- A # clause with unique negative literal A :- B, C, D # clause where A is positive and B,C,D negative # variables are strings without spaces
def radviz(self, column_names, transforms=dict(), **kwargs): """ Radviz plot. Useful for exploratory visualization, a radviz plot can show multivariate data in 2D. Conceptually, the variables (here, specified in `column_names`) are distributed evenly around the unit circle. Th...
Radviz plot. Useful for exploratory visualization, a radviz plot can show multivariate data in 2D. Conceptually, the variables (here, specified in `column_names`) are distributed evenly around the unit circle. Then each point (here, each row in the dataframe) is attached to each ...
def _acquire(self, uuid_path): """ Lease a free network for the given uuid path Args: uuid_path (str): Path to the uuid file of a :class:`lago.Prefix` Returns: netaddr.IPNetwork: Which represents the selected subnet Raises: LagoSubnetLeaseEx...
Lease a free network for the given uuid path Args: uuid_path (str): Path to the uuid file of a :class:`lago.Prefix` Returns: netaddr.IPNetwork: Which represents the selected subnet Raises: LagoSubnetLeaseException: If the store is full
def init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes d...
Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowed_epsilon: list of allowed epsilon or None to use default skip_image_ids: list of image ids to skip max_num_images: maximum number of images to read
def init_disk_cache(self): """Initialize the on-disk version of the cache.""" try: # Cleanup old disk cache files path = self.disk_cache_location os.remove(path) except Exception: pass self.disk_cache_location = os.path.join(tempfile.mkdtem...
Initialize the on-disk version of the cache.
def cmap_pal(name=None, lut=None): """ Create a continuous palette using an MPL colormap Parameters ---------- name : str Name of colormap lut : None | int This is the number of entries desired in the lookup table. Default is ``None``, leave it up Matplotlib. Return...
Create a continuous palette using an MPL colormap Parameters ---------- name : str Name of colormap lut : None | int This is the number of entries desired in the lookup table. Default is ``None``, leave it up Matplotlib. Returns ------- out : function Contin...
def annotations(obj: BioCCollection or BioCDocument or BioCPassage or BioCSentence, docid: str = None, level: int = PASSAGE) -> Generator[BioCAnnotation, None, None]: """ Get all annotations in document id. Args: obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence ...
Get all annotations in document id. Args: obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence docid: document id. If None, all documents level: one of DOCUMENT, PASSAGE, SENTENCE Yields: one annotation
def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs): """ Read a georaster from a file. :param filename: url :param band_names: list of strings, or string. if None - will try to read from image, otherwise - these will be ['0', ..]...
Read a georaster from a file. :param filename: url :param band_names: list of strings, or string. if None - will try to read from image, otherwise - these will be ['0', ..] :param lazy_load: if True - do not load anything :return: GeoRaster2
def show_repo(self, repo_names=[], envs=[], query='/repositories/'): """ `repo_names` - Name of repository(s) to show Show repositories in specified environments """ juicer.utils.Log.log_debug("Show Repo(s): %s", str(repo_names)) repo_objects = {} for env in env...
`repo_names` - Name of repository(s) to show Show repositories in specified environments
async def get_cred_def(self, cd_id: str) -> str: """ Get credential definition from ledger by its identifier. Raise AbsentCredDef for no such credential definition, logging any error condition and raising BadLedgerTxn on bad request. Raise ClosedPool if cred def not in cache and pool is...
Get credential definition from ledger by its identifier. Raise AbsentCredDef for no such credential definition, logging any error condition and raising BadLedgerTxn on bad request. Raise ClosedPool if cred def not in cache and pool is closed. Retrieve the credential definition from the agent's...
def crop(self, xa, xb, ya, yb): """ Crops the image. Two points : - We use numpy conventions xa = 200 and xb = 400 will give you a width of 200 pixels ! - We crop relative to the current array (i.e. not necessarily to the original array !) ...
Crops the image. Two points : - We use numpy conventions xa = 200 and xb = 400 will give you a width of 200 pixels ! - We crop relative to the current array (i.e. not necessarily to the original array !) This means you can crop several times in a row wit...
def create_pipeline(self): """Main wrapper for pipeline creation. 1. Runs clean_pipelines to clean up existing ones 2. determines which environments the pipeline needs 3. Renders all of the pipeline blocks as defined in configs 4. Runs post_pipeline to create pipeline """...
Main wrapper for pipeline creation. 1. Runs clean_pipelines to clean up existing ones 2. determines which environments the pipeline needs 3. Renders all of the pipeline blocks as defined in configs 4. Runs post_pipeline to create pipeline
def process_data(name=None): '''Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary ''' ct = current_process() if not hasattr(ct, '_pulsar_local'): ct._pulsar_local = {} loc = c...
Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary
def geocode(self, address=None, components=None, region=None, language=None, bounds=None, sensor=None): """Geocode given address. Geocoder can queried using address and/or components. Components when used with address will restrict your query to specific area. When used without a...
Geocode given address. Geocoder can queried using address and/or components. Components when used with address will restrict your query to specific area. When used without address they act like more precise query. For full details see `Google docs <https://developers.google.com/maps/docu...
def flexifunction_buffer_function_ack_send(self, target_system, target_component, func_index, result, force_mavlink1=False): ''' Flexifunction type and parameters for component at function index from buffer target_system : System ID (uint8_t) ...
Flexifunction type and parameters for component at function index from buffer target_system : System ID (uint8_t) target_component : Component ID (uint8_t) func_index : Function index (uint16_t) result ...
def metrics_by_name_list(names): """ Return a dictionary with {metric name: metric value} for all the metrics with the given names. """ results = {} for name in names: # no lock - a metric could have been removed in the meanwhile try: results[name] = get(name) ex...
Return a dictionary with {metric name: metric value} for all the metrics with the given names.
def _write_commits_to_release_notes(self): """ writes commits to the releasenotes file by appending to the end """ with open(self.release_file, 'a') as out: out.write("==========\n{}\n".format(self.tag)) for commit in self.commits: try: ...
writes commits to the releasenotes file by appending to the end
def _parse_price(html_chunk): """ Parse price of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str/None: Price as string with currency or None if not found. """ price = get_first_content( html_chunk.find("div", {"class...
Parse price of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str/None: Price as string with currency or None if not found.
def run_batch(args: dict) -> int: """Runs a batch operation for the given arguments""" batcher.run_project( project_directory=args.get('project_directory'), log_path=args.get('logging_path'), output_directory=args.get('output_directory'), shared_data=load_shared_data(args.get('s...
Runs a batch operation for the given arguments
def validate_request(self, path, action, body=None, query=None): """Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there m...
Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there must not be any required parameters in # the given schema ...
def bulk(self, body, doc_type=None, params=None): """ `<http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html>`_ :arg body: The operation definition and data (action-data pairs), separated by newlines :arg doc_type: Default document type for items which do...
`<http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html>`_ :arg body: The operation definition and data (action-data pairs), separated by newlines :arg doc_type: Default document type for items which don't provide one :arg interval: Collection interval (e.g., '10s...
def cancel(self, request, *args, **kwargs): # pylint: disable=unused-argument """ Cancel the task associated with the specified status record. Arguments: request (Request): A POST including a task status record ID Returns ------- Response: A JSON respon...
Cancel the task associated with the specified status record. Arguments: request (Request): A POST including a task status record ID Returns ------- Response: A JSON response indicating whether the cancellation succeeded or not
def get_software_version(self, cabinet, frame, board): """Get the software version for a given BMP. Returns ------- :py:class:`.BMPInfo` Information about the software running on a BMP. """ sver = self._send_scp(cabinet, frame, board, SCPCommands.sver) ...
Get the software version for a given BMP. Returns ------- :py:class:`.BMPInfo` Information about the software running on a BMP.
def configure_proxy(proxyname, start=True): ''' Create the salt proxy file and start the proxy process if required Parameters: proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started ...
Create the salt proxy file and start the proxy process if required Parameters: proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started default = True CLI Example: .. code-...
def change_column(self, table, column_name, field): """Change column.""" operations = [self.alter_change_column(table, column_name, field)] if not field.null: operations.extend([self.add_not_null(table, column_name)]) return operations
Change column.
def _create_input(paired, out_file, ref_file, snp_file, qsnp_file): """Create INI input for qSNP""" ini_file["[inputFiles]"]["dbSNP"] = snp_file ini_file["[inputFiles]"]["ref"] = ref_file ini_file["[inputFiles]"]["normalBam"] = paired.normal_bam ini_file["[inputFiles]"]["tumourBam"] = paired.tumor_b...
Create INI input for qSNP
def file_update_all(backend, message, dryrun): """ Update all of the changed files for this Recipe """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if re...
Update all of the changed files for this Recipe
def sweepYfiltered(self): """ Get the filtered sweepY of the current sweep. Only works if self.kernel has been generated. """ assert self.kernel is not None return swhlab.common.convolve(self.sweepY,self.kernel)
Get the filtered sweepY of the current sweep. Only works if self.kernel has been generated.
def plot_kde(self, ax=None, amax=None, amin=None, label=None, return_fig=False): """ Plot a KDE for the curve. Very nice summary of KDEs: https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ ...
Plot a KDE for the curve. Very nice summary of KDEs: https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ Args: ax (axis): Optional matplotlib (MPL) axis to plot into. Returned. amax (float): Optional max value to permit. amin (float): Optional min va...