code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def request_uri(self): uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
Absolute path including the query string.
def update_time_range(form_data): if 'since' in form_data or 'until' in form_data: form_data['time_range'] = '{} : {}'.format( form_data.pop('since', '') or '', form_data.pop('until', '') or '', )
Move since and until to time_range.
def get_base_branch(cherry_pick_branch): prefix, sha, base_branch = cherry_pick_branch.split("-", 2) if prefix != "backport": raise ValueError( 'branch name is not prefixed with "backport-". Is this a cherry_picker branch?' ) if not re.match("[0-9a-f]{7,40}", sha): raise...
return '2.7' from 'backport-sha-2.7' raises ValueError if the specified branch name is not of a form that cherry_picker would have created
def table_columns(self): with self.conn.cursor() as cur: cur.execute(self.TABLE_COLUMNS_QUERY % self.database) for row in cur: yield row
Yields column names.
def conn_aws(cred, crid): driver = get_driver(Provider.EC2) try: aws_obj = driver(cred['aws_access_key_id'], cred['aws_secret_access_key'], region=cred['aws_default_region']) except SSLError as e: abort_err("\r SSL Error with AWS: {}".format(...
Establish connection to AWS service.
def _create_skt(self): log.debug('Creating the auth socket') if ':' in self.auth_address: self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.bind((self...
Create the authentication socket.
def binary_float_to_decimal_float(number: Union[float, str]) -> float: if isinstance(number, str): if number[0] == '-': n_sign = -1 else: n_sign = 1 elif isinstance(number, float): n_sign = np.sign(number) number = str(number) deci = 0 for ndx, val...
Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point.
def coerce(self, value, resource): return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}
Get a dict with attributes from ``value``. Arguments --------- value : ? The value to get some resources from. resource : dataql.resources.Object The ``Object`` object used to obtain this value from the original one. Returns ------- dict ...
def get_details(self, ids): if isinstance(ids, list): if len(ids) > 5: ids = ids[:5] id_param = ';'.join(ids) + '/' else: ids = str(ids) id_param = ids + '/' header, content = self._http_request(id_param) resp = json.loads(c...
Locu Venue Details API Call Wrapper Args: list of ids : ids of a particular venues to get insights about. Can process up to 5 ids
def emotes(self, emotes): if emotes is None: self._emotes = [] return es = [] for estr in emotes.split('/'): es.append(Emote.from_str(estr)) self._emotes = es
Set the emotes :param emotes: the key of the emotes tag :type emotes: :class:`str` :returns: None :rtype: None :raises: None
def find_default_container(builder, default_container=None, use_biocontainers=None, ): if not default_container and use_biocontainers: default_container = get_container_from_software_requirements( use_biocontainers, ...
Default finder for default containers.
def add_data_from_jsonp(self, data_src, data_name = 'json_data', series_type="map", name=None, **kwargs): self.jsonp_data_flag = True self.jsonp_data_url = json.dumps(data_src) if data_name == 'data': data_name = 'json_'+ data_name self.jsonp_data = data_name self.add...
add data directly from a https source the data_src is the https link for data using jsonp
def remove(self, observableElement): if observableElement in self._observables: self._observables.remove(observableElement)
remove an obsrvable element :param str observableElement: the name of the observable element
def create_job(self, job_template_uri): endpoint = self._build_url('jobs') data = self._query_api('POST', endpoint, None, {'Content-Type': 'application/json'}, json.dumps({'jobTemp...
Creates a job
def append(self, node): if node.parent == self.key and not self.elapsed_time: self.children.append(node) else: for child in self.children: if not child.elapsed_time: child.append(node)
To append a new child.
def _should_trigger_abbreviation(self, buffer): return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations)
Checks whether, based on the settings for the abbreviation and the given input, the abbreviation should trigger. @param buffer Input buffer to be checked (as string)
def is_option(value, *options): if not isinstance(value, string_types): raise VdtTypeError(value) if not value in options: raise VdtValueError(value) return value
This check matches the value to any of a set of options. >>> vtor = Validator() >>> vtor.check('option("yoda", "jedi")', 'yoda') 'yoda' >>> vtor.check('option("yoda", "jedi")', 'jed') # doctest: +SKIP Traceback (most recent call last): VdtValueError: the value "jed" is unacceptable. >>> vt...
def _logging_callback(level, domain, message, data): domain = ffi.string(domain).decode() message = ffi.string(message).decode() logger = LOGGER.getChild(domain) if level not in LOG_LEVELS: return logger.log(LOG_LEVELS[level], message)
Callback that outputs libgphoto2's logging message via Python's standard logging facilities. :param level: libgphoto2 logging level :param domain: component the message originates from :param message: logging message :param data: Other data in the logging record (unused)
def zoomset_cb(self, setting, value, channel): if not self.gui_up: return info = channel.extdata._info_info if info is None: return scale_x, scale_y = value if scale_x == scale_y: text = self.fv.scale2text(scale_x) else: tex...
This callback is called when the main window is zoomed.
def redirect_ext(to, params_=None, anchor_=None, permanent_=False, args=None, kwargs=None): if permanent_: redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect return redirect_class(resolve_url_ext(to, params_, anchor_, args, kwargs))
Advanced redirect which can includes GET-parameters and anchor.
def _find_fld_pkt_val(self, pkt, val): fld = self._iterate_fields_cond(pkt, val, True) dflts_pkt = pkt.default_fields if val == dflts_pkt[self.name] and self.name not in pkt.fields: dflts_pkt[self.name] = fld.default val = fld.default return fld, val
Given a Packet instance `pkt` and the value `val` to be set, returns the Field subclass to be used, and the updated `val` if necessary.
def unregister_child(self, child): self._children.remove(child) child.on_closed.disconnect(self.unregister_child)
Unregister an existing child that is no longer to be owned by the current instance. :param child: The child instance.
def balance(self): while self.recNum > self.shpNum: self.null() while self.recNum < self.shpNum: self.record()
Adds corresponding empty attributes or null geometry records depending on which type of record was created to make sure all three files are in synch.
def _reset(self, **kwargs): super(Tag, self)._reset(**kwargs) self._api_name = self.name if 'server' in self.servers: self.servers = kwargs['servers']['server'] if self.servers and isinstance(self.servers[0], six.string_types): self.servers = [Server(uuid=server, ...
Reset the objects attributes. Accepts servers as either unflattened or flattened UUID strings or Server objects.
def cleanup(context): for name in 'work_dir', 'artifact_dir', 'task_log_dir': path = context.config[name] if os.path.exists(path): log.debug("rm({})".format(path)) rm(path) makedirs(path)
Clean up the work_dir and artifact_dir between task runs, then recreate. Args: context (scriptworker.context.Context): the scriptworker context.
def InstallTemplatePackage(): virtualenv_bin = os.path.dirname(sys.executable) extension = os.path.splitext(sys.executable)[1] pip = "%s/pip%s" % (virtualenv_bin, extension) major_minor_version = ".".join( pkg_resources.get_distribution("grr-response-core").version.split(".") [0:2]) subprocess.che...
Call pip to install the templates.
def spec(self): from ambry_sources.sources import SourceSpec d = self.dict d['url'] = self.url return SourceSpec(**d)
Return a SourceSpec to describe this source
def figure(size=(8,8), *args, **kwargs): return plt.figure(figsize=size, *args, **kwargs)
Creates a figure. Parameters ---------- size : 2-tuple size of the view window in inches args : list args of mayavi figure kwargs : list keyword args of mayavi figure Returns ------- pyplot figure the current ...
def report_stderr(host, stderr): lines = stderr.readlines() if lines: print("STDERR from {host}:".format(host=host)) for line in lines: print(line.rstrip(), file=sys.stderr)
Take a stderr and print it's lines to output if lines are present. :param host: the host where the process is running :type host: str :param stderr: the std error of that process :type stderr: paramiko.channel.Channel
def lazy_result(f): @wraps(f) def decorated(ctx, param, value): return LocalProxy(lambda: f(ctx, param, value)) return decorated
Decorate function to return LazyProxy.
def get_network(self, org, segid): network_info = { 'organizationName': org, 'partitionName': self._part_name, 'segmentId': segid, } res = self._get_network(network_info) if res and res.status_code in self._resp_ok: return res.json()
Return given network from DCNM. :param org: name of organization. :param segid: segmentation id of the network.
def getFixedStarList(IDs, date): starList = [getFixedStar(ID, date) for ID in IDs] return FixedStarList(starList)
Returns a list of fixed stars.
def current_state(self): field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(field_name, getattr(self, field_name)) for field_name in field_names])
Returns a ``field -> value`` dict of the current state of the instance.
def get_random_name(): char_seq = [] name_source = random.randint(1, 2**8-1) current_value = name_source while current_value > 0: char_offset = current_value % 26 current_value = current_value - random.randint(1, 26) char_seq.append(chr(char_offset + ord('a'))) name = ''.join...
Return random lowercase name
def getAllKws(self): kws_ele = [] kws_bl = [] for ele in self.all_elements: if ele == '_prefixstr' or ele == '_epics': continue elif self.getElementType(ele).lower() == u'beamline': kws_bl.append(ele) else: kws_e...
extract all keywords into two categories kws_ele: magnetic elements kws_bl: beamline elements return (kws_ele, kws_bl)
def is_delimiter(line): return bool(line) and line[0] in punctuation and line[0]*len(line) == line
True if a line consists only of a single punctuation character.
def get_cluster_interfaces(cluster, extra_cond=lambda nic: True): nics = get_nics(cluster) nics = [(nic['device'], nic['name']) for nic in nics if nic['mountable'] and nic['interface'] == 'Ethernet' and not nic['management'] and extra_cond(nic)] nics = sorted(...
Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In addition to ``extra_cond``, only the mountable and Ehernet interfaces are re...
def lp10(self, subset_k, subset_p, weights={}): if self._z is None: self._add_minimization_vars() positive = set(subset_k) - self._flipped negative = set(subset_k) & self._flipped v = self._v.set(positive) cs = self._prob.add_linear_constraints(v >= self._epsilon) ...
Force reactions in K above epsilon while minimizing support of P. This program forces reactions in subset K to attain flux > epsilon while minimizing the sum of absolute flux values for reactions in subset P (L1-regularization).
def run(self, resources): if not resources['connection']._port.startswith('jlink'): raise ArgumentError("FlashBoardStep is currently only possible through jlink", invalid_port=args['port']) hwman = resources['connection'] debug = hwman.hwman.debug(self._debug_string) debug.fl...
Runs the flash step Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step.
def new_as_dict(self, raw=True, vars=None): result = {} for section in self.sections(): if section not in result: result[section] = {} for option in self.options(section): value = self.get(section, option, raw=raw, vars=vars) try: value = cherr...
Convert an INI file to a dictionary
def run_crbox(self,spstring,form,output="",wavecat="INDEF", lowave=0,hiwave=30000): range=hiwave-lowave midwave=range/2.0 iraf.countrate(spectrum=spstring, magnitude="", instrument="box(%f,%f)"%(midwave,range), form=form, ...
Calcspec has a bug. We will use countrate instead, and force it to use a box function of uniform transmission as the obsmode.
def name_for_scalar_relationship(base, local_cls, referred_cls, constraint): name = referred_cls.__name__.lower() + "_ref" return name
Overriding naming schemes.
def _init_alphabet_from_tokens(self, tokens): self._alphabet = {c for token in tokens for c in token} self._alphabet |= _ESCAPE_CHARS
Initialize alphabet from an iterable of token or subtoken strings.
def set_item(self, key, value): keys = list(self.keys()) if key in keys: self.set_value(1,keys.index(key),str(value)) else: self.set_value(0,len(self), str(key)) self.set_value(1,len(self)-1, str(value))
Sets the item by key, and refills the table sorted.
def list_attr(self, recursive=False): if recursive: raise DeprecationWarning("Symbol.list_attr with recursive=True has been deprecated. " "Please use attr_dict instead.") size = mx_uint() pairs = ctypes.POINTER(ctypes.c_char_p)() f_handle ...
Gets all attributes from the symbol. Example ------- >>> data = mx.sym.Variable('data', attr={'mood': 'angry'}) >>> data.list_attr() {'mood': 'angry'} Returns ------- ret : Dict of str to str A dictionary mapping attribute keys to values.
def clear( self ): self.blockSignals(True) self.setUpdatesEnabled(False) for child in self.findChildren(XRolloutItem): child.setParent(None) child.deleteLater() self.setUpdatesEnabled(True) self.blockSignals(False)
Clears out all of the rollout items from the widget.
def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None): callback = (lambda con, sender, object, iface, signal, params: signal_fired(sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None return Subscription(self.con...
Subscribes to matching signals. Subscribes to signals on connection and invokes signal_fired callback whenever the signal is received. To receive signal_fired callback, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- se...
def validateAllServers(self): url = self._url + "/servers/validate" params = {"f" : "json"} return self._get(url=url, param_dict=params, proxy_port=self._proxy_port, proxy_url=self._proxy_ur)
This operation provides status information about a specific ArcGIS Server federated with Portal for ArcGIS. Parameters: serverId - unique id of the server
def create_xref(self): log.debug("Creating Crossreferences (XREF)") tic = time.time() for c in self._get_all_classes(): self._create_xref(c) log.info("End of creating cross references (XREF)") log.info("run time: {:0d}min {:02d}s".format(*divmod(int(time.time() - tic)...
Create Class, Method, String and Field crossreferences for all classes in the Analysis. If you are using multiple DEX files, this function must be called when all DEX files are added. If you call the function after every DEX file, the crossreferences might be wrong!
def _get_binned_arrays(self, wavelengths, flux_unit, area=None, vegaspec=None): x = self._validate_binned_wavelengths(wavelengths) y = self.sample_binned(wavelengths=x, flux_unit=flux_unit, area=area, vegaspec=vegaspec) if isinstance(wave...
Get binned observation in user units.
def rollback(self): self._tx_active = False return self._channel.rpc_request(specification.Tx.Rollback())
Abandon the current transaction. Rollback all messages published during the current transaction session to the remote server. Note that all messages published during this transaction session will be lost, and will have to be published again. A new transacti...
def has_in_url_path(url, subs): scheme, netloc, path, query, fragment = urlparse.urlsplit(url) return any([sub in path for sub in subs])
Test if any of `subs` strings is present in the `url` path.
async def finish_pairing(self, pin): self.srp.step1(pin) pub_key, proof = self.srp.step2(self._atv_pub_key, self._atv_salt) msg = messages.crypto_pairing({ tlv8.TLV_SEQ_NO: b'\x03', tlv8.TLV_PUBLIC_KEY: pub_key, tlv8.TLV_PROOF: proof}) resp = await sel...
Finish pairing process.
def extract_changesets(objects): def add_changeset_info(collation, axis, item): if axis not in collation: collation[axis] = {} first = collation[axis] first["id"] = axis first["username"] = item["username"] first["uid"] = item["uid"] first["timestamp"] = i...
Provides information about each changeset present in an OpenStreetMap diff file. Parameters ---------- objects : osc_decoder class A class containing OpenStreetMap object dictionaries. Returns ------- changeset_collation : dict A dictionary of dictionaries with each changes...
def _verify_password(self, raw_password, hashed_password): PraetorianError.require_condition( self.pwd_ctx is not None, "Praetorian must be initialized before this method is available", ) return self.pwd_ctx.verify(raw_password, hashed_password)
Verifies that a plaintext password matches the hashed version of that password using the stored passlib password context
def _format_snapshots(snapshots: List[icontract._Snapshot], prefix: Optional[str] = None) -> List[str]: if not snapshots: return [] result = [] if prefix is not None: result.append(":{} OLD:".format(prefix)) else: result.append(":OLD:") for snapshot in snapshots: text...
Format snapshots as reST. :param snapshots: snapshots defined to capture the argument values of a function before the invocation :param prefix: prefix to be prepended to ``:OLD:`` directive :return: list of lines describing the snapshots
def serialize(self, data): return json.dumps(self._serialize_datetime(data), ensure_ascii=False)
Return the data as serialized string. :param dict data: The data to serialize :rtype: str
def Font(name=None, source="sys", italic=False, bold=False, size=20): assert source in ["sys", "file"] if not name: return pygame.font.SysFont(pygame.font.get_default_font(), size, bold=bold, italic=italic) if source == "sys": return pygame.font.SysFont(name, size, bold=bol...
Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str
def load_model( self, the_metamodel, filename, is_main_model, encoding='utf-8', add_to_local_models=True): if not self.local_models.has_model(filename): if self.all_models.has_model(filename): new_model = self.all_models.filename_to_model[filename] ...
load a single model Args: the_metamodel: the metamodel used to load the model filename: the model to be loaded (if not cached) Returns: the loaded/cached model
def _non_reducing_slice(slice_): kinds = (ABCSeries, np.ndarray, Index, list, str) if isinstance(slice_, kinds): slice_ = IndexSlice[:, slice_] def pred(part): return ((isinstance(part, slice) or is_list_like(part)) and not isinstance(part, tuple)) if not is_list_like(sli...
Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make sure we're always working with DataFrames.
def add_type(cls, typ): if not isinstance(typ, basestring): raise TypeError("The type should be a string. But is %s" % type(typ)) cls.types.append(typ)
Register a type for jb_reftrack nodes. A type specifies how the reference should be handled. For example the type shader will connect shaders with the parent when it the shaders are loaded. Default types are :data:`JB_ReftrackNode.types`. .. Note:: You have to add types before you init...
async def connect(self): if self.connected or self.is_connecting: return self._is_connecting = True try: logger.info("Connecting to RabbitMQ...") self._transport, self._protocol = await aioamqp.connect(**self._connection_parameters) logger.info("Ge...
Create new asynchronous connection to the RabbitMQ instance. This will connect, declare exchange and bind itself to the configured queue. After that, client is ready to publish or consume messages. :return: Does not return anything.
def unsnip(tag=None,start=-1): import IPython i = IPython.get_ipython() if tag in _tagged_inputs.keys(): if len(_tagged_inputs[tag]) > 0: i.set_next_input(_tagged_inputs[tag][start]) else: if len(_last_inputs) > 0: i.set_next_input(_last_inputs[start])
This function retrieves a tagged or untagged snippet.
def is_reassignment_pending(self): in_progress_plan = self.zk.get_pending_plan() if in_progress_plan: in_progress_partitions = in_progress_plan['partitions'] self.log.info( 'Previous re-assignment in progress for {count} partitions.' ' Current part...
Return True if there are reassignment tasks pending.
def _enum_from_direction(direction): if isinstance(direction, int): return direction if direction == Query.ASCENDING: return enums.StructuredQuery.Direction.ASCENDING elif direction == Query.DESCENDING: return enums.StructuredQuery.Direction.DESCENDING else: msg = _BAD_DI...
Convert a string representation of a direction to an enum. Args: direction (str): A direction to order by. Must be one of :attr:`~.firestore.Query.ASCENDING` or :attr:`~.firestore.Query.DESCENDING`. Returns: int: The enum corresponding to ``direction``. Raises: ...
def _draw_outer_connector(context, width, height): c = context arrow_height = height / 2.5 gap = height / 6. connector_height = (height - gap) / 2. c.rel_move_to(-width / 2., -gap / 2.) c.rel_line_to(width, 0) c.rel_line_to(0, -(connector_height - arrow_height)) ...
Draw the outer connector for container states Connector for container states can be connected from the inside and the outside. Thus the connector is split in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow. :param context: Cairo context ...
def _to_link_header(self, link): try: bucket, key, tag = link except ValueError: raise RiakError("Invalid link tuple %s" % link) tag = tag if tag is not None else bucket url = self.object_path(bucket, key) header = '<%s>; riaktag="%s"' % (url, tag) ...
Convert the link tuple to a link header string. Used internally.
def active_brokers(self): return { broker for broker in six.itervalues(self.brokers) if not broker.inactive and not broker.decommissioned }
Set of brokers that are not inactive or decommissioned.
def remove_message(self, message): if message in self.__messages: self.__messages.remove(message)
Remove a message from the batch
def build(self): if self._category_text_iter is None: raise CategoryTextIterNotSetError() nlp = self.get_nlp() category_document_iter = ( (category, self._clean_function(raw_text)) for category, raw_text in self._category_text_iter ) ...
Generate a TermDocMatrix from data in parameters. Returns ---------- term_doc_matrix : TermDocMatrix The object that this factory class builds.
def info(vm, info_type='all', key='uuid'): ret = {} if info_type not in ['all', 'block', 'blockstats', 'chardev', 'cpus', 'kvm', 'pci', 'spice', 'version', 'vnc']: ret['Error'] = 'Requested info_type is not available' return ret if key not in ['uuid', 'alias', 'hostname']: ret['Error...
Lookup info on running kvm vm : string vm to be targeted info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc] info type to return key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*'...
def require(*requirements, **kwargs): none_on_failure = kwargs.get('none_on_failure', False) def inner(f): @functools.wraps(f) def wrapper(*args, **kwargs): for req in requirements: if none_on_failure: if not getattr(req, 'is_available'): ...
Decorator that can be used to require requirements. :param requirements: List of requirements that should be verified :param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None
def get_config(self, view = None): path = self._path() + '/config' resp = self._get_resource_root().get(path, params = view and dict(view=view) or None) return self._parse_svc_config(resp, view)
Retrieve the service's configuration. Retrieves both the service configuration and role type configuration for each of the service's supported role types. The role type configurations are returned as a dictionary, whose keys are the role type name, and values are the respective configuration dictionari...
def calibration_template(self): temp = {} temp['tone_doc'] = self.tone_calibrator.stimulus.templateDoc() comp_doc = [] for calstim in self.bs_calibrator.get_stims(): comp_doc.append(calstim.stateDict()) temp['noise_doc'] = comp_doc return temp
Gets the template documentation for the both the tone curve calibration and noise calibration :returns: dict -- all information necessary to recreate calibration objects
def startLoading(self): if super(XBatchItem, self).startLoading(): tree = self.treeWidget() if not isinstance(tree, XOrbTreeWidget): self.takeFromTree() return next_batch = self.batch() tree._loadBatch(self, next_batch)
Starts loading this item for the batch.
def add_grammar(self, customization_id, grammar_name, grammar_file, content_type, allow_overwrite=None, **kwargs): if customization_id is None: raise ValueError('customization_id m...
Add a grammar. Adds a single grammar file to a custom language model. Submit a plain text file in UTF-8 format that defines the grammar. Use multiple requests to submit multiple grammar files. You must use credentials for the instance of the service that owns a model to add a grammar to...
def get_object_detail(self, request, obj): if self.display_detail_fields: display_fields = self.display_detail_fields else: display_fields = self.display_fields data = self.serialize(obj, ['id'] + list(display_fields)) return HttpResponse(self.json_dumps(data), co...
Handles get requests for the details of the given object.
def addSourceLocation(self, sourceLocationUri, weight): assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer" self.topicPage["sourceLocations"].append({"uri": sourceLocationUri, "wgt": weight})
add a list of relevant sources by identifying them by their geographic location @param sourceLocationUri: uri of the location where the sources should be geographically located @param weight: importance of the provided list of sources (typically in range 1 - 50)
def systemInformationType13(): a = L2PseudoLength(l2pLength=0x00) b = TpPd(pd=0x6) c = MessageType(mesType=0x0) d = Si13RestOctets() packet = a / b / c / d return packet
SYSTEM INFORMATION TYPE 13 Section 9.1.43a
def save_params(step_num, model, trainer, ckpt_dir): param_path = os.path.join(ckpt_dir, '%07d.params'%step_num) trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num) logging.info('[step %d] Saving checkpoints to %s, %s.', step_num, param_path, trainer_path) model.save_parameter...
Save the model parameter, marked by step_num.
def getXML(self): s = '' for element in self._svgElements: s += element.getXML() return s
Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation.
def eccentricity(self, directed=None, weighted=None): sp = self.shortest_path(directed=directed, weighted=weighted) return sp.max(axis=0)
Maximum distance from each vertex to any other vertex.
def _MultiStream(cls, fds): missing_chunks_by_fd = {} for chunk_fd_pairs in collection.Batch( cls._GenerateChunkPaths(fds), cls.MULTI_STREAM_CHUNKS_READ_AHEAD): chunks_map = dict(chunk_fd_pairs) contents_map = {} for chunk_fd in FACTORY.MultiOpen( chunks_map, mode="r", token=...
Effectively streams data from multiple opened AFF4ImageBase objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd is an object from the fds argument. If one or more chunks ...
def get_batch_header_values(self): lines = self.getOriginalFile().data.splitlines() reader = csv.reader(lines) batch_headers = batch_data = [] for row in reader: if not any(row): continue if row[0].strip().lower() == 'batch header': ...
Scrape the "Batch Header" values from the original input file
def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None, notfound_ok=None, head_only=False): raise NotImplementedError
Fetches an object.
def load(path: str) -> "Store": if _gpg.is_encrypted(path): src_bytes = _gpg.decrypt(path) else: src_bytes = open(path, "rb").read() src = src_bytes.decode("utf-8") ext = _gpg.unencrypted_ext(path) assert ext not in [ ".yml", ".yaml...
Load password store from file.
def parse_spec(self): recruiters = [] spec = get_config().get("recruiters") for match in self.SPEC_RE.finditer(spec): name = match.group(1) count = int(match.group(2)) recruiters.append((name, count)) return recruiters
Parse the specification of how to recruit participants. Example: recruiters = bots: 5, mturk: 1
async def read_line(stream: asyncio.StreamReader) -> bytes: line = await stream.readline() if len(line) > MAX_LINE: raise ValueError("Line too long") if not line.endswith(b"\r\n"): raise ValueError("Line without CRLF") return line[:-2]
Read a single line from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return :class:`bytes` without CRLF.
def mousePressEvent(self, event): self.parent.raise_() self.raise_() if event.button() == Qt.RightButton: pass
override Qt method
def gunzip(gzip_file, file_gunzip=None): if file_gunzip is None: file_gunzip = os.path.splitext(gzip_file)[0] gzip_open_to(gzip_file, file_gunzip) return file_gunzip
Unzip .gz file. Return filename of unzipped file.
def getKendallTauScore(myResponse, otherResponse): kt = 0 list1 = myResponse.values() list2 = otherResponse.values() if len(list1) <= 1: return kt for itr1 in range(0, len(list1) - 1): for itr2 in range(itr1 + 1, len(list2)): if ((list1[itr1] > list1[itr2] ...
Returns the Kendall Tau Score
def return_standard_conf(): result = resource_string(__name__, 'daemon/dagobahd.yml') result = result % {'app_secret': os.urandom(24).encode('hex')} return result
Return the sample config file.
def get_response_example(self, resp_spec): if 'schema' in resp_spec.keys(): if '$ref' in resp_spec['schema']: definition_name = self.get_definition_name_from_ref(resp_spec['schema']['$ref']) return self.definitions_example[definition_name] elif 'items' in ...
Get a response example from a response spec.
async def monitor_mode(self, poll_devices=False, device=None, workdir=None): print("Running monitor mode") await self.connect(poll_devices, device, workdir) self.plm.monitor_mode()
Place the IM in monitoring mode.
def getSignalParameters(fitParams, n_std=3): signal = getSignalPeak(fitParams) mx = signal[1] + n_std * signal[2] mn = signal[1] - n_std * signal[2] if mn < fitParams[0][1]: mn = fitParams[0][1] return mn, signal[1], mx
return minimum, average, maximum of the signal peak
def set_series_resistance(self, channel, value, resistor_index=None): if resistor_index is None: resistor_index = self.series_resistor_index(channel) try: if channel == 0: self.calibration.R_hv[resistor_index] = value else: self.calibra...
Set the current series resistance value for the specified channel. Parameters ---------- channel : int Analog channel index. value : float Series resistance value. resistor_index : int, optional Series resistor channel index. If :...
def join(self,timeout=None): if timeout is None: for thread in self.__threads: thread.join() else: deadline = _time() + timeout for thread in self.__threads: delay = deadline - _time() if delay <= 0: ...
Join all threads in this group. If the optional "timeout" argument is given, give up after that many seconds. This method returns True is the threads were successfully joined, False if a timeout occurred.
def get_subreddit_image(self, subreddit, id): url = self._base_url + "/3/gallery/r/{0}/{1}".format(subreddit, id) resp = self._send_request(url) return Gallery_image(resp, self)
Return the Gallery_image with the id submitted to subreddit gallery :param subreddit: The subreddit the image has been submitted to. :param id: The id of the image we want.
def public(self): req = self.request(self.mist_client.uri+'/keys/'+self.id+"/public") public = req.get().json() return public
Return the public ssh-key :returns: The public ssh-key as string
def main(): r = Random(42) startSerializationTime = time.time() for i in xrange(_SERIALIZATION_LOOPS): builderProto = RandomProto.new_message() r.write(builderProto) elapsedSerializationTime = time.time() - startSerializationTime builderBytes = builderProto.to_bytes() startDeserializationTime = time...
Measure capnp serialization performance of Random