code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def getmap(self, path, query=None): """ Performs a GET request where the response content type is required to be "application/json" and the content is a JSON-encoded data structure. The decoded structure is returned. """ code, data, ctype = self.get(path, query) if ct...
Performs a GET request where the response content type is required to be "application/json" and the content is a JSON-encoded data structure. The decoded structure is returned.
def iterfiles(self): """Yield all WinFile object. """ try: for path in self.order: yield self.files[path] except: for winfile in self.files.values(): yield winfile
Yield all WinFile object.
def fov_for_height_and_distance(height, distance): """Calculate the FOV needed to get a given frustum height at a given distance. """ vfov_deg = np.degrees(2.0 * np.arctan(height * 0.5 / distance)) return vfov_deg
Calculate the FOV needed to get a given frustum height at a given distance.
def data(self, **query): """Query for Data object annotation.""" data = self.gencloud.project_data(self.id) query['case_ids__contains'] = self.id ids = set(d['id'] for d in self.gencloud.api.dataid.get(**query)['objects']) return [d for d in data if d.id in ids]
Query for Data object annotation.
def __create_channel_run(self, channel, username, token): """Sends a post request to create the channel run.""" data = { 'channel_id': channel.get_node_id().hex, 'chef_name': self.__get_chef_name(), 'ricecooker_version': __version__, 'started_by_user': use...
Sends a post request to create the channel run.
def download_extract(url): """download and extract file.""" logger.info("Downloading %s", url) request = urllib2.Request(url) request.add_header('User-Agent', 'caelum/0.1 +https://github.com/nrcharles/caelum') opener = urllib2.build_opener() with tempfile.TemporaryFile(suf...
download and extract file.
def save(self): """Save data.""" with open(self.filename, 'wb') as file: self.prune() self.data['version'] = self.version json.dump(self.data, file, sort_keys=True, indent=2)
Save data.
def _get_range(book, range_, sheet): """Return a range as nested dict of openpyxl cells.""" filename = None if isinstance(book, str): filename = book book = opxl.load_workbook(book, data_only=True) elif isinstance(book, opxl.Workbook): pass else: raise TypeError ...
Return a range as nested dict of openpyxl cells.
def forwards(apps, schema_editor): """ Having added the new 'exhibition' Work type, we're going to assume that every Event of type 'museum' should actually have one Exhibition attached. So, we'll add one, with the same title as the Event. And we'll move all Creators from the Event to the Exhibition...
Having added the new 'exhibition' Work type, we're going to assume that every Event of type 'museum' should actually have one Exhibition attached. So, we'll add one, with the same title as the Event. And we'll move all Creators from the Event to the Exhibition.
def extract_transformers_from_source(source): '''Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed. ''' ...
Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed.
def save_related(self, request, form, formsets, change): """ Rebuilds the tree after saving items related to parent. """ super(MenuItemAdmin, self).save_related(request, form, formsets, change) self.model.objects.rebuild()
Rebuilds the tree after saving items related to parent.
def _remove_redundancy_routers(self, context, router_ids, ports, delete_ha_groups=False): """Deletes all interfaces of the specified redundancy routers and then the redundancy routers themselves. """ subnets_info = [{'subnet_id': port['fixed_ips'][0]['s...
Deletes all interfaces of the specified redundancy routers and then the redundancy routers themselves.
def do_rename(argdict): '''Rename a page.''' site = make_site_obj(argdict) slug = argdict['slug'] newtitle = argdict['newtitle'] try: site.rename_page(slug, newtitle) print "Renamed page." except ValueError: # pragma: no cover print "Cannot rename. A page with the given s...
Rename a page.
def define(self, value, lineno, namespace=None): """ Defines label value. It can be anything. Even an AST """ if self.defined: error(lineno, "label '%s' already defined at line %i" % (self.name, self.lineno)) self.value = value self.lineno = lineno self.names...
Defines label value. It can be anything. Even an AST
def _genA(self): """ Generate the matrix A in the Bartlett decomposition A is a lower triangular matrix, with A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j ~ Normal() when i > j """ p, df = self._p, self.df A = np...
Generate the matrix A in the Bartlett decomposition A is a lower triangular matrix, with A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j ~ Normal() when i > j
def load_data(path, fmt=None, bg_data=None, bg_fmt=None, meta_data={}, holo_kw={}, as_type="float32"): """Load experimental data Parameters ---------- path: str Path to experimental data file or folder fmt: str The file format to use (see `file_formats.formats`). ...
Load experimental data Parameters ---------- path: str Path to experimental data file or folder fmt: str The file format to use (see `file_formats.formats`). If set to `None`, the file format is guessed. bg_data: str Path to background data file or `qpimage.QPImage` ...
def format(self, record): """Overridden method that applies SGR codes to log messages.""" # XXX: idea, colorize message arguments s = super(ANSIFormatter, self).format(record) if hasattr(self.context, 'ansi'): s = self.context.ansi(s, **self.get_sgr(record)) return s
Overridden method that applies SGR codes to log messages.
def _register_view(self, app, resource, *urls, **kwargs): """Bind resources to the app. :param app: an actual :class:`flask.Flask` app :param resource: :param urls: :param endpoint: endpoint name (defaults to :meth:`Resource.__name__.lower` Can be used to reference ...
Bind resources to the app. :param app: an actual :class:`flask.Flask` app :param resource: :param urls: :param endpoint: endpoint name (defaults to :meth:`Resource.__name__.lower` Can be used to reference this route in :meth:`flask.url_for` :type endpoint: str ...
def rm(self, container_alias): ''' a method to remove an active container :param container_alias: string with name or id of container :return: string with container id ''' title = '%s.rm' % self.__class__.__name__ # validate inputs ...
a method to remove an active container :param container_alias: string with name or id of container :return: string with container id
def _decode_embedded_list(src): ''' Convert enbedded bytes to strings if possible. List helper. ''' output = [] for elem in src: if isinstance(elem, dict): elem = _decode_embedded_dict(elem) elif isinstance(elem, list): elem = _decode_embedded_list(elem) ...
Convert enbedded bytes to strings if possible. List helper.
def update_item(self, payload, last_modified=None): """ Update an existing item Accepts one argument, a dict containing Item data """ to_send = self.check_items([payload])[0] if last_modified is None: modified = payload["version"] else: mod...
Update an existing item Accepts one argument, a dict containing Item data
def from_local_name(acs, attr, name_format): """ :param acs: List of AttributeConverter instances :param attr: attribute name as string :param name_format: Which name-format it should be translated to :return: An Attribute instance """ for aconv in acs: #print(ac.format, name_format)...
:param acs: List of AttributeConverter instances :param attr: attribute name as string :param name_format: Which name-format it should be translated to :return: An Attribute instance
def getFilename(name): """Get a filename from given name without dangerous or incompatible characters.""" # first replace all illegal chars name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name) # then remove double dots and underscores while ".." in name: name = name.replace('..', '.') while "_...
Get a filename from given name without dangerous or incompatible characters.
def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return confi...
Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values.
def _get_record_attrs(out_keys): """Check for records, a single key plus output attributes. """ if len(out_keys) == 1: attr = list(out_keys.keys())[0] if out_keys[attr]: return attr, out_keys[attr] return None, None
Check for records, a single key plus output attributes.
def AddClient(self, client): """Adds a client to the index. Args: client: A VFSGRRClient record to add or update. """ client_id, keywords = self.AnalyzeClient(client) self.AddKeywordsForName(client_id, keywords)
Adds a client to the index. Args: client: A VFSGRRClient record to add or update.
def pin(package, version, checks, marker, resolving, lazy, quiet): """Pin a dependency for all checks that require it. This can also resolve transient dependencies. Setting the version to `none` will remove the package. You can specify an unlimited number of additional checks to apply the pin for v...
Pin a dependency for all checks that require it. This can also resolve transient dependencies. Setting the version to `none` will remove the package. You can specify an unlimited number of additional checks to apply the pin for via arguments.
def response_hook(self, r, **kwargs): """The actual hook handler.""" if r.status_code == 401: # Handle server auth. www_authenticate = r.headers.get('www-authenticate', '').lower() auth_type = _auth_type_from_header(www_authenticate) if auth_type is not N...
The actual hook handler.
def disable_multicolor(self): """ swap from the multicolor image to the single color image """ # disable the multicolor image for color in ['red', 'green', 'blue']: self.multicolorscales[color].config(state=tk.DISABLED, bg='grey') self.multicolorframes[color].config(bg='g...
swap from the multicolor image to the single color image
def AssignTasksToClient(self, client_id): """Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks. """ rules = self.Get(self.Schema.RULES) if not rules: return 0 i...
Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks.
def update_hacluster_dns_ha(service, relation_data, crm_ocf='ocf:maas:dns'): """ Configure DNS-HA resources based on provided configuration @param service: Name of the service being configured @param relation_data: Pointer to dictionary of relation data. @param crm_ocf: Coro...
Configure DNS-HA resources based on provided configuration @param service: Name of the service being configured @param relation_data: Pointer to dictionary of relation data. @param crm_ocf: Corosync Open Cluster Framework resource agent to use for DNS HA
def binned_bitsets_from_list( list=[] ): """Read a list into a dictionary of bitsets""" last_chrom = None last_bitset = None bitsets = dict() for l in list: chrom = l[0] if chrom != last_chrom: if chrom not in bitsets: bitsets[chrom] = BinnedBitSet(MAX) ...
Read a list into a dictionary of bitsets
def RemoveDevice(self, object_path): '''Remove (forget) a device ''' adapter = mockobject.objects[self.path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceRemoved', 'o', [object_path])
Remove (forget) a device
def is_contextfree(self): """Returns True iff the grammar is context-free.""" for lhs, rhs in self.rules: if len(lhs) != 1: return False if lhs[0] not in self.nonterminals: return False return True
Returns True iff the grammar is context-free.
def unregister(self, name): """Unregister function by name. """ try: name = name.name except AttributeError: pass return self.pop(name,None)
Unregister function by name.
def check_load(grid, mode): """ Checks for over-loading of branches and transformers for MV or LV grid. Parameters ---------- grid : GridDing0 Grid identifier. mode : str Kind of grid ('MV' or 'LV'). Returns ------- :obj:`dict` Dict of critical branches with max...
Checks for over-loading of branches and transformers for MV or LV grid. Parameters ---------- grid : GridDing0 Grid identifier. mode : str Kind of grid ('MV' or 'LV'). Returns ------- :obj:`dict` Dict of critical branches with max. relative overloading, and the ...
def compile_relative_distances(self, sympy_accesses=None): """ Return load and store distances between accesses. :param sympy_accesses: optionally restrict accesses, default from compile_sympy_accesses() e.g. if accesses are to [+N, +1, -1, -N], relative distances are [N-1, 2, N-1] ...
Return load and store distances between accesses. :param sympy_accesses: optionally restrict accesses, default from compile_sympy_accesses() e.g. if accesses are to [+N, +1, -1, -N], relative distances are [N-1, 2, N-1] returned is a dict of list of sympy expressions, for each variable
def get_pending_withdrawals(self, currency=None): """ Used to view your pending withdrawals Endpoint: 1.1 NO EQUIVALENT 2.0 /key/balance/getpendingwithdrawals :param currency: String literal for the currency (ie. BTC) :type currency: str :return: pending...
Used to view your pending withdrawals Endpoint: 1.1 NO EQUIVALENT 2.0 /key/balance/getpendingwithdrawals :param currency: String literal for the currency (ie. BTC) :type currency: str :return: pending withdrawals in JSON :rtype : list
def new(cls, settings, *args, **kwargs): """ Create a new Cloud instance based on the Settings """ logger.debug('Initializing new "%s" Instance object' % settings['CLOUD']) cloud = settings['CLOUD'] if cloud == 'bare': self = BareInstance(settings=settings, *a...
Create a new Cloud instance based on the Settings
def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. ...
Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the tem...
def decorator_handle(tokens): """Process decorators.""" defs = [] decorates = [] for i, tok in enumerate(tokens): if "simple" in tok and len(tok) == 1: decorates.append("@" + tok[0]) elif "test" in tok and len(tok) == 1: varname = decorator_var + "_" + str(i) ...
Process decorators.
def _extract_coeffs(self, imt): """ Extract dictionaries of coefficients specific to required intensity measure type. """ C_HR = self.COEFFS_HARD_ROCK[imt] C_BC = self.COEFFS_BC[imt] C_SR = self.COEFFS_SOIL_RESPONSE[imt] SC = self.COEFFS_STRESS[imt] ...
Extract dictionaries of coefficients specific to required intensity measure type.
def jtype(c): """ Return the a string with the data type of a value, for JSON data """ ct = c['type'] return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang'))
Return the a string with the data type of a value, for JSON data
def _bool_segments(array, start=0, delta=1, minlen=1): """Yield segments of consecutive `True` values in a boolean array Parameters ---------- array : `iterable` An iterable of boolean-castable values. start : `float` The value of the first sample on the indexed axis (e.g.t...
Yield segments of consecutive `True` values in a boolean array Parameters ---------- array : `iterable` An iterable of boolean-castable values. start : `float` The value of the first sample on the indexed axis (e.g.the GPS start time of the array). delta : `float` ...
def sticker_templates(): """ It returns the registered stickers in the system. :return: a DisplayList object """ voc = DisplayList() stickers = getStickerTemplates() for sticker in stickers: voc.add(sticker.get('id'), sticker.get('title')) if voc.index == 0: logger.warnin...
It returns the registered stickers in the system. :return: a DisplayList object
def exclude(source, keys, *, transform=None): """Returns a dictionary excluding keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values """ check = keys if callable(keys) else lambda key: key i...
Returns a dictionary excluding keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values
def coerce(self, values): """Convert an iterable of literals to an iterable of options. Args: values (iterable or string): An iterable of raw values to convert into options. If the value is a string is is assumed to be a comma separated list and will be split b...
Convert an iterable of literals to an iterable of options. Args: values (iterable or string): An iterable of raw values to convert into options. If the value is a string is is assumed to be a comma separated list and will be split before processing. Returns: ...
def params_of_mean(value=array([-.005, 1.]), tau=.1, rate=4.): """ Intercept and slope of rate stochastic of poisson distribution Rate stochastic must be positive for t in [0,T] p(intercept, slope|tau,rate) = N(slope|0,tau) Exp(intercept|rate) 1(intercept>0) 1(intercept + slope * T>0) """ ...
Intercept and slope of rate stochastic of poisson distribution Rate stochastic must be positive for t in [0,T] p(intercept, slope|tau,rate) = N(slope|0,tau) Exp(intercept|rate) 1(intercept>0) 1(intercept + slope * T>0)
def _get_color(self, r, g, b): """Convert red, green and blue values specified in floats with range 0-1 to whatever the native widget color object is. """ clr = (r, g, b) return clr
Convert red, green and blue values specified in floats with range 0-1 to whatever the native widget color object is.
def wrap(msg, indent, indent_first=True): """ Helper function that wraps msg to 120-chars page width. All lines (except maybe 1st) will be prefixed with string {indent}. First line is prefixed only if {indent_first} is True. :param msg: string to indent :param indent: string that will be used fo...
Helper function that wraps msg to 120-chars page width. All lines (except maybe 1st) will be prefixed with string {indent}. First line is prefixed only if {indent_first} is True. :param msg: string to indent :param indent: string that will be used for indentation :param indent_first: if True then ...
def toposort(data): """ Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items. Output is a list of sets in topological order. The first set consists of items with no dependences, each subsequent set consists of items that depend upon items ...
Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items. Output is a list of sets in topological order. The first set consists of items with no dependences, each subsequent set consists of items that depend upon items in the preceeding sets. :par...
def int_list_packer(term, values): """ return singletons, ranges and exclusions """ DENSITY = 10 # a range can have holes, this is inverse of the hole density MIN_RANGE = 20 # min members before a range is allowed to be used singletons = set() ranges = [] exclude = set() sorted =...
return singletons, ranges and exclusions
def delete(self): """Delete the instance.""" if lib.EnvDeleteInstance(self._env, self._ist) != 1: raise CLIPSError(self._env)
Delete the instance.
def wrap_many(self, *args, strict=False): """Wraps different copies of this element inside all empty tags listed in params or param's (non-empty) iterators. Returns list of copies of this element wrapped inside args or None if not succeeded, in the same order and same structure, ...
Wraps different copies of this element inside all empty tags listed in params or param's (non-empty) iterators. Returns list of copies of this element wrapped inside args or None if not succeeded, in the same order and same structure, i.e. args = (Div(), (Div())) -> value = (A(...), (A(...
def update(did): """Update DDO of an existing asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@contex...
Update DDO of an existing asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@context" - created...
def check_in(self, url: str, new_status: Status, increment_try_count: bool=True, url_result: Optional[URLResult]=None): '''Update record for processed URL. Args: url: The URL. new_status: Update the item status to `new_status`. incre...
Update record for processed URL. Args: url: The URL. new_status: Update the item status to `new_status`. increment_try_count: Whether to increment the try counter for the URL. url_result: Additional values.
def cut_from_block(html_message): """Cuts div tag which wraps block starting with "From:".""" # handle the case when From: block is enclosed in some tag block = html_message.xpath( ("//*[starts-with(mg:text_content(), 'From:')]|" "//*[starts-with(mg:text_content(), 'Date:')]")) if bloc...
Cuts div tag which wraps block starting with "From:".
def get_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. """ doc = txt.dedent(obj.__doc__ or "") env = env.copy() ...
Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any.
def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""): """ List all build configuration sets """ data = list_build_configuration_sets_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
List all build configuration sets
def tf_idf(text): """ Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) where :math:`tf(w, d)` is the number of times word :math:`w` appeared in document :math:`...
Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) where :math:`tf(w, d)` is the number of times word :math:`w` appeared in document :math:`d`, :math:`f(w)` is the number...
def main(): """Main entry point""" # Quit when interrupted import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Arguments: # --separator STRING/REGEX - how to split a row into cells (only relevant for CSV parser) # --flatten - flatten item hashes. {'a':{'b':'c'}} --> {'a_b':'c'} ...
Main entry point
def get_all_publications(return_namedtuples=True): """ Get list publications from all available source. Args: return_namedtuples (bool, default True): Convert :class:`.Publication` structures to namedtuples (used in AMQP communication). Ret...
Get list publications from all available source. Args: return_namedtuples (bool, default True): Convert :class:`.Publication` structures to namedtuples (used in AMQP communication). Returns: list: List of :class:`.Publication` structures co...
def download_ts(self, path, chunk, process_last_line=True): """ This will look for a download ts link. It will then download that file and replace the link with the local file. :param process_last_line: :param path: str of the path to put the file :param chunk: s...
This will look for a download ts link. It will then download that file and replace the link with the local file. :param process_last_line: :param path: str of the path to put the file :param chunk: str of the chunk file, note this could have partial lines :return: s...
def c(*args, **kwargs): ''' kind of like od -c on the command line, basically it dumps each character and info about that char since -- 2013-5-9 *args -- tuple -- one or more strings to dump ''' with Reflect.context(**kwargs) as r: kwargs["args"] = args instance = C_CLASS(r...
kind of like od -c on the command line, basically it dumps each character and info about that char since -- 2013-5-9 *args -- tuple -- one or more strings to dump
def differences_between(self, current_files, parent_files, changes, prefixes): """ yield (thing, changes, is_path) If is_path is true, changes is None and thing is the path as a tuple. If is_path is false, thing is the current_files and parent_files for that changed treeentry a...
yield (thing, changes, is_path) If is_path is true, changes is None and thing is the path as a tuple. If is_path is false, thing is the current_files and parent_files for that changed treeentry and changes is the difference between current_files and parent_files. The code here...
def _rest_post(self, suburi, request_headers, request_body): """REST POST operation. The response body after the operation could be the new resource, or ExtendedError, or it could be empty. """ return self._rest_op('POST', suburi, request_headers, request_body)
REST POST operation. The response body after the operation could be the new resource, or ExtendedError, or it could be empty.
def on_for_seconds(self, left_speed, right_speed, seconds, brake=True, block=True): """ Rotate the motors at 'left_speed & right_speed' for 'seconds'. Speeds can be percentages or any SpeedValue implementation. """ if seconds < 0: raise ValueError("seconds is negativ...
Rotate the motors at 'left_speed & right_speed' for 'seconds'. Speeds can be percentages or any SpeedValue implementation.
def install_remote(self): """Download, extract and install NApp.""" package, pkg_folder = None, None try: package = self._download() pkg_folder = self._extract(package) napp_folder = self._get_local_folder(pkg_folder) dst = self._installed / self.u...
Download, extract and install NApp.
def getRelativePath(basepath, path): """Get a path that is relative to the given base path.""" basepath = splitpath(os.path.abspath(basepath)) path = splitpath(os.path.abspath(path)) afterCommon = False for c in basepath: if afterCommon or path[0] != c: path.insert(0, os.path.par...
Get a path that is relative to the given base path.
def _from_dict(cls, _dict): """Initialize a LanguageModels object from a json dictionary.""" args = {} if 'customizations' in _dict: args['customizations'] = [ LanguageModel._from_dict(x) for x in (_dict.get('customizations')) ] els...
Initialize a LanguageModels object from a json dictionary.
def make_encoder(self,formula_dict,inter_list,param_dict): """ make the encoder function """ X_dict = {} Xcol_dict = {} encoder_dict = {} # first, replace param_dict[key] = values, with param_dict[key] = dmatrix for key in formula_dict: encodin...
make the encoder function
def associate_route_table(self, route_table_id, subnet_id): """ Associates a route table with a specific subnet. :type route_table_id: str :param route_table_id: The ID of the route table to associate. :type subnet_id: str :param subnet_id: The ID of the subnet to assoc...
Associates a route table with a specific subnet. :type route_table_id: str :param route_table_id: The ID of the route table to associate. :type subnet_id: str :param subnet_id: The ID of the subnet to associate with. :rtype: str :return: The ID of the association creat...
def export_throw_event_info(node_params, output_element): """ Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThr...
Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThrowEvent' element.
def _rapRperiAxiEq(R,E,L,pot): """The vr=0 equation that needs to be solved to find apo- and pericenter""" return E-potentialAxi(R,pot)-L**2./2./R**2.
The vr=0 equation that needs to be solved to find apo- and pericenter
def get_measurement_id_options(self): """ Returns list of measurement choices.""" # get the URL for the main check in page document = self._get_document_for_url( self._get_url_for_measurements() ) # gather the IDs for all measurement types measurement_ids = s...
Returns list of measurement choices.
def create_small_thumbnail(self, token, item_id): """ Create a 100x100 small thumbnail for the given item. It is used for preview purpose and displayed in the 'preview' and 'thumbnails' sidebar sections. :param token: A valid token for the user in question. :type token: ...
Create a 100x100 small thumbnail for the given item. It is used for preview purpose and displayed in the 'preview' and 'thumbnails' sidebar sections. :param token: A valid token for the user in question. :type token: string :param item_id: The item on which to set the thumbnail....
def on(self, event, listener, *user_args): """Register a ``listener`` to be called on ``event``. The listener will be called with any extra arguments passed to :meth:`emit` first, and then the extra arguments passed to :meth:`on` last. If the listener function returns :class:`F...
Register a ``listener`` to be called on ``event``. The listener will be called with any extra arguments passed to :meth:`emit` first, and then the extra arguments passed to :meth:`on` last. If the listener function returns :class:`False`, it is removed and will not be called th...
def get_image_grad(net, image, class_id=None): """Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provi...
Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used.
def determine_if_whitespace(self): """ Set is_space if current token is whitespace Is space if value is: * Newline * Empty String * Something that matches regexes['whitespace'] """ value = self.current.value if value == '\n'...
Set is_space if current token is whitespace Is space if value is: * Newline * Empty String * Something that matches regexes['whitespace']
def authorized_default_handler(resp, remote, *args, **kwargs): """Store access token in session. Default authorized handler. :param remote: The remote application. :param resp: The response. :returns: Redirect response. """ response_token_setter(remote, resp) db.session.commit() re...
Store access token in session. Default authorized handler. :param remote: The remote application. :param resp: The response. :returns: Redirect response.
def init_registry_from_json(mongo, filename, clear_collection=False): """Initialize a model registry with a list of model definitions that are stored in a given file in Json format. Parameters ---------- mongo : scodata.MongoDBFactory Connector for MongoDB filename : string Path...
Initialize a model registry with a list of model definitions that are stored in a given file in Json format. Parameters ---------- mongo : scodata.MongoDBFactory Connector for MongoDB filename : string Path to file containing model definitions clear_collection : boolean ...
def write(self): """Write object state to Zookeeper. This will write the current state of the object to Zookeeper, taking the final merged state as the new one, and resetting any write buffers. """ self._check() cache = self._cache pristine_cache = self._...
Write object state to Zookeeper. This will write the current state of the object to Zookeeper, taking the final merged state as the new one, and resetting any write buffers.
def wait_for_crm_operation(operation): """Poll for cloud resource manager operation until finished.""" logger.info("wait_for_crm_operation: " "Waiting for operation {} to finish...".format(operation)) for _ in range(MAX_POLLS): result = crm.operations().get(name=operation["name"]).e...
Poll for cloud resource manager operation until finished.
def attention_mask_same_segment( query_segment, memory_segment=None, dtype=tf.float32): """Bias for attention where attention between segments is disallowed. Args: query_segment: a mtf.Tensor with shape [..., length_dim] memory_segment: a mtf.Tensor with shape [..., memory_length_dim] dtype: a tf.d...
Bias for attention where attention between segments is disallowed. Args: query_segment: a mtf.Tensor with shape [..., length_dim] memory_segment: a mtf.Tensor with shape [..., memory_length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim]
def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(self, attribute, pickle_data)
Load data from a pickle file.
def get_nsing(self,epsilon=1.0e-4): """ get the number of solution space dimensions given a ratio between the largest and smallest singular values Parameters ---------- epsilon: float singular value ratio Returns ------- nsing : float ...
get the number of solution space dimensions given a ratio between the largest and smallest singular values Parameters ---------- epsilon: float singular value ratio Returns ------- nsing : float number of singular components above the eps...
def defaults(self): """ Reset the chart options and style to defaults """ self.chart_style = {} self.chart_opts = {} self.style("color", "#30A2DA") self.width(900) self.height(250)
Reset the chart options and style to defaults
def load_glove_df(filepath, **kwargs): """ Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 ...
Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 Name: the, dtype: float64
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None, ...
Strided 2-D convolution with explicit padding. The padding is consistent and is based only on `kernel_size`, not on the dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). Args: inputs: `Tensor` of size `[batch, channels, height_in, width_in]`. filters: `int` number of filters in the ...
def init_prior(self, R): """initialize prior for the subject Returns ------- TFA Returns the instance itself. """ centers, widths = self.init_centers_widths(R) # update prior prior = np.zeros(self.K * (self.n_dim + 1)) self.set_center...
initialize prior for the subject Returns ------- TFA Returns the instance itself.
def printSequences(x, formatString="%d"): """ Print a bunch of sequences stored in a 2D numpy array. """ [seqLen, numElements] = x.shape for i in range(seqLen): s = "" for j in range(numElements): s += formatString % x[i][j] print s
Print a bunch of sequences stored in a 2D numpy array.
async def execute_all_with_names(self, subprocesses, container = None, retnames = ('',), forceclose = True): ''' DEPRECATED Execute all subprocesses and get the return values. :param subprocesses: sequence of subroutines (coroutines) :param container: if specified, run ...
DEPRECATED Execute all subprocesses and get the return values. :param subprocesses: sequence of subroutines (coroutines) :param container: if specified, run subprocesses in another container. :param retnames: DEPRECATED get return value from container.(name) for each n...
def _get_notifications_status(self, notifications): """ Get the notifications status """ if notifications: size = len(notifications["activeNotifications"]) else: size = 0 status = self.status_notif if size > 0 else self.status_no_notif ret...
Get the notifications status
def get_cached_moderated_reddits(self): """Return a cached dictionary of the user's moderated reddits. This list is used internally. Consider using the `get_my_moderation` function instead. """ if self._mod_subs is None: self._mod_subs = {'mod': self.reddit_session....
Return a cached dictionary of the user's moderated reddits. This list is used internally. Consider using the `get_my_moderation` function instead.
def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME): """ Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the TMOC instance. Parameters ---------- times : `astropy.time.Time` astropy times to check whe...
Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the TMOC instance. Parameters ---------- times : `astropy.time.Time` astropy times to check whether they are contained in the TMOC or not. keep_inside : bool, optional True b...
def lookup(self, pathogenName, sampleName): """ Look up a pathogen name, sample name combination and get its FASTA/FASTQ file name and unique read count. This method should be used instead of C{add} in situations where you want an exception to be raised if a pathogen/sample comb...
Look up a pathogen name, sample name combination and get its FASTA/FASTQ file name and unique read count. This method should be used instead of C{add} in situations where you want an exception to be raised if a pathogen/sample combination has not already been passed to C{add}. ...
def highlight_occurences(editor): """ Highlights given editor current line. :param editor: Document editor. :type editor: QWidget :return: Method success. :rtype: bool """ format = editor.language.theme.get("accelerator.occurence") if not format: return False extra_sel...
Highlights given editor current line. :param editor: Document editor. :type editor: QWidget :return: Method success. :rtype: bool
def list(self, full_properties=False, filter_args=None): """ List the Virtual Functions of this Partition. Authorization requirements: * Object-access permission to this Partition. Parameters: full_properties (bool): Controls whether the full set of reso...
List the Virtual Functions of this Partition. Authorization requirements: * Object-access permission to this Partition. Parameters: full_properties (bool): Controls whether the full set of resource properties should be retrieved, vs. only the short set as re...
def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked. """ print("Loading obs ", self.run_date, self.model_name, self.forecast_variable) ...
Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked.
def _normalise_weights(logZ, weights, ntrim=None): """ Correctly normalise the weights for trimming This takes a list of log-evidences, and re-normalises the weights so that the largest weight across all samples is 1, and the total weight in each set of samples is proportional to the evidence. Par...
Correctly normalise the weights for trimming This takes a list of log-evidences, and re-normalises the weights so that the largest weight across all samples is 1, and the total weight in each set of samples is proportional to the evidence. Parameters ---------- logZ: array-like log-evi...