code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def activate_network_interface(iface): iface = iface.encode() SIOCGIFFLAGS = 0x8913 SIOCSIFFLAGS = 0x8914 IFF_UP = 0x1 STRUCT_IFREQ_LAYOUT_IFADDR_SAFAMILY = b"16sH14s" STRUCT_IFREQ_LAYOUT_IFFLAGS = b"16sH14s" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP) try:...
Bring up the given network interface. @raise OSError: if interface does not exist or permissions are missing
def fit_transform(self, X, **kwargs): tasklogger.log_start('PHATE') self.fit(X) embedding = self.transform(**kwargs) tasklogger.log_complete('PHATE') return embedding
Computes the diffusion operator and the position of the cells in the embedding space Parameters ---------- X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, ...
def str_extract(arr, pat, flags=0, expand=True): r if not isinstance(expand, bool): raise ValueError("expand must be True or False") if expand: return _str_extract_frame(arr._orig, pat, flags=flags) else: result, name = _str_extract_noexpand(arr._parent, pat, flags=flags) ...
r""" Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression `pat`. Parameters ---------- pat : str Regular expression pattern with capturing groups. flags : int, default 0...
def start(self): while not self.is_start(self.current_tag): self.next() self.new_entry()
Find the first data entry and prepare to parse.
def check_status(self, delay=0): if not self.item_id: while not self._request_status(): yield self.status, self.completion_percentage if self.item_id is None: sleep(delay) else: yield self.status, self.completion_percentage
Checks the api endpoint in a loop :param delay: number of seconds to wait between api calls. Note Connection 'requests_delay' also apply. :return: tuple of status and percentage complete :rtype: tuple(str, float)
def level(self): m = re.match( self.compliance_prefix + r'(\d)' + self.compliance_suffix + r'$', self.compliance) if (m): return int(m.group(1)) raise IIIFInfoError( "Bad compliance profile URI, failed to extract...
Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError
def bitwise_dot_product(bs0: str, bs1: str) -> str: if len(bs0) != len(bs1): raise ValueError("Bit strings are not of equal length") return str(sum([int(bs0[i]) * int(bs1[i]) for i in range(len(bs0))]) % 2)
A helper to calculate the bitwise dot-product between two string representing bit-vectors :param bs0: String of 0's and 1's representing a number in binary representations :param bs1: String of 0's and 1's representing a number in binary representations :return: 0 or 1 as a string corresponding to the dot-...
def data_file(file_fmt, info=None, **kwargs): if isinstance(info, dict): kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest() kwargs.update(info) return utils.fstr(fmt=file_fmt, **kwargs)
Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments for f-strings Returns: str: data file name
def row_is_filtered(self, row_subs, filters): for filtername in filters: filtervalue = filters[filtername] if filtername in row_subs: row_subs_value = row_subs[filtername] if str(row_subs_value) != str(filtervalue): return True ...
returns True if row should NOT be included according to filters
def repeat(self, count): x = HSeq() for i in range(count): x = x.concatenate(self) return x
repeat sequence given number of times to produce a new sequence
def getfirstline(file, default): with open(file, 'rb') as fh: content = fh.readlines() if len(content) == 1: return content[0].decode('utf-8').strip('\n') return default
Returns the first line of a file.
def _handle_archive(archive, command, verbosity=0, interactive=True, program=None, format=None, compression=None): if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) if command not in ('list', 'test'): raise util...
Test and list archives.
def finish_assessment(self, assessment_taken_id): assessment_taken = self._get_assessment_taken(assessment_taken_id) assessment_taken_map = assessment_taken._my_map if assessment_taken.has_started() and not assessment_taken.has_ended(): assessment_taken_map['completionTime'] = DateTi...
Indicates the entire assessment is complete. arg: assessment_taken_id (osid.id.Id): ``Id`` of the ``AssessmentTaken`` raise: IllegalState - ``has_begun()`` is ``false or is_over()`` is ``true`` raise: NotFound - ``assessment_taken_id`` is not found r...
def connected_edges(G, nodes): nodes_in_G = collections.deque() for node in nodes: if not G.has_node(node): continue nodes_in_G.extend(nx.node_connected_component(G, node)) edges = G.subgraph(nodes_in_G).edges() return edges
Given graph G and list of nodes, return the list of edges that are connected to nodes
def add_event( request, template='swingtime/add_event.html', event_form_class=forms.EventForm, recurrence_form_class=forms.MultipleOccurrenceForm ): dtstart = None if request.method == 'POST': event_form = event_form_class(request.POST) recurrence_form = recurrence_form_class(req...
Add a new ``Event`` instance and 1 or more associated ``Occurrence``s. Context parameters: ``dtstart`` a datetime.datetime object representing the GET request value if present, otherwise None ``event_form`` a form object for updating the event ``recurrence_form`` a fo...
def rollback_app(self, app_id, version, force=False): params = {'force': force} data = json.dumps({'version': version}) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) return response.json()
Roll an app back to a previous version. :param str app_id: application ID :param str version: application version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict
def delete_unused(self, keyword_ids=None): if keyword_ids is None: keywords = self.all() else: keywords = self.filter(id__in=keyword_ids) keywords.filter(assignments__isnull=True).delete()
Removes all instances that are not assigned to any object. Limits processing to ``keyword_ids`` if given.
def _flush(self): self.classes_names = None self.__cache_methods = None self.__cached_methods_idx = None self.__cache_fields = None self.__cache_all_methods = None self.__cache_all_fields = None
Flush all caches Might be used after classes, methods or fields are added.
def add(a, b): if a is None: if b is None: return None else: return b elif b is None: return a return a + b
Add two values, ignoring None
def get_instance(self, payload): return TranscriptionInstance( self._version, payload, account_sid=self._solution['account_sid'], recording_sid=self._solution['recording_sid'], )
Build an instance of TranscriptionInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
def _retrieve(self, *criterion): try: return self._query(*criterion).one() except NoResultFound as error: raise ModelNotFoundError( "{} not found".format( self.model_class.__name__, ), error, )
Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted.
def callable_name(callable_obj): try: if (isinstance(callable_obj, type) and issubclass(callable_obj, param.ParameterizedFunction)): return callable_obj.__name__ elif (isinstance(callable_obj, param.Parameterized) and 'operation' in callable_obj.params()): ...
Attempt to return a meaningful name identifying a callable or generator
def truncate_table(self, tablename): self.get(tablename).remove() self.db.commit()
SQLite3 doesn't support direct truncate, so we just use delete here
def _ref_bib(key, ref): s = '' s += '@{}{{{},\n'.format(ref['type'], key) entry_lines = [] for k, v in ref.items(): if k == 'type': continue if k == 'authors': entry_lines.append(' author = {{{}}}'.format(' and '.join(v))) elif k == 'editors': ...
Convert a single reference to bibtex format
def attach(self): s = self._sensor self.update(s, s.read()) self._sensor.attach(self)
Attach strategy to its sensor and send initial update.
def add_injectable( name, value, autocall=True, cache=False, cache_scope=_CS_FOREVER, memoize=False): if isinstance(value, Callable): if autocall: value = _InjectableFuncWrapper( name, value, cache=cache, cache_scope=cache_scope) value.clear_cached() ...
Add a value that will be injected into other functions. Parameters ---------- name : str value If a callable and `autocall` is True then the function's argument names and keyword argument values will be matched to registered variables when the function needs to be evalua...
def logs(ctx, services, num, follow): logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] services_path = os.path.join(home, SERVICES) tail_threads = [] for service in services: ...
Show logs of daemonized service.
def delete(self, key): "Delete a `key` from the keystore." if key in self.data: self.delete_from_index(key) del self.data[key]
Delete a `key` from the keystore.
def data(self) -> Sequence[Tuple[int, float]]: return [(num, prob) for num, prob in zip(self._num_cfds_seq, self._gnd_state_probs)]
Returns a sequence of tuple pairs with the first item being a number of Cliffords and the second item being the corresponding average ground state probability.
def add_chain(self, group_name, component_map): self.assert_writeable() for component, path in component_map.items(): if not path.startswith('Analyses/'): path = 'Analyses/{}'.format(path) component_map[component] = path self.add_analysis_attributes(group_...
Adds the component chain to ``group_name`` in the fast5. These are added as attributes to the group. :param group_name: The group name you wish to add chaining data to, e.g. ``Test_000`` :param component_map: The set of components and corresponding group names or group p...
def pickle_to_param(obj, name): return from_pyvalue(u"pickle:%s" % name, unicode(pickle.dumps(obj)))
Return the top-level element of a document sub-tree containing the pickled serialization of a Python object.
def from_scf_input(cls, workdir, scf_input, manager=None, allocate=True): flow = cls(workdir, manager=manager) flow.register_scf_task(scf_input) scf_task = flow[0][0] nl_work = DteWork.from_scf_task(scf_task) flow.register_work(nl_work) if allocate: flow.allocate() ...
Create a `NonlinearFlow` for second order susceptibility calculations from an `AbinitInput` defining a ground-state run. Args: workdir: Working directory of the flow. scf_input: :class:`AbinitInput` object with the parameters for the GS-SCF run. manager: :class:`Task...
def is_np_compat(): curr = ctypes.c_bool() check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr))) return curr.value
Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A bool value indicating whether the NumPy compatibility is currently on.
def parse(self, input_text, syncmap): self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError)
Parse the given ``input_text`` and append the extracted fragments to ``syncmap``. :param input_text: the input text as a Unicode string (read from file) :type input_text: string :param syncmap: the syncmap to append to :type syncmap: :class:`~aeneas.syncmap.SyncMap`
def _get_memory_contents(self): if self._memory_contents is not None: return self._memory_contents schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg) self._memory_contents = self._graph.compute_memory_contents_under_schedule( schedule) return self._memory_contents
Runs the scheduler to determine memory contents at every point in time. Returns: a list of frozenset of strings, where the ith entry describes the tensors in memory when executing operation i (where schedule[i] is an index into GetAllOperationNames()).
def rivermap_update(self, river, water_flow, rivermap, precipitations): isSeed = True px, py = (0, 0) for x, y in river: if isSeed: rivermap[y, x] = water_flow[y, x] isSeed = False else: rivermap[y, x] = precipitations[y, x]...
Update the rivermap with the rainfall that is to become the waterflow
def load_config(self): config = Config() self.config_obj = config.load('awsshellrc') self.config_section = self.config_obj['aws-shell'] self.model_completer.match_fuzzy = self.config_section.as_bool( 'match_fuzzy') self.enable_vi_bindings = self.config_section.as_bool...
Load the config from the config file or template.
def remove_ipv4addr(self, ipv4addr): for addr in self.ipv4addrs: if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or (isinstance(addr, HostIPv4) and addr.ipv4addr == ipv4addr)): self.ipv4addrs.remove(addr) break
Remove an IPv4 address from the host. :param str ipv4addr: The IP address to remove
def get_bitcoind_client(): bitcoind_opts = get_bitcoin_opts() bitcoind_host = bitcoind_opts['bitcoind_server'] bitcoind_port = bitcoind_opts['bitcoind_port'] bitcoind_user = bitcoind_opts['bitcoind_user'] bitcoind_passwd = bitcoind_opts['bitcoind_passwd'] return create_bitcoind_service_proxy(bit...
Connect to the bitcoind node
def datetime(self): if 'dt_scale' not in self._cache.keys(): self._cache['dt_scale'] = self._datetime - timedelta(seconds=self._offset) return self._cache['dt_scale']
Conversion of the Date object into a ``datetime.datetime`` The resulting object is a timezone-naive instance with the same scale as the originating Date object.
def com_daltonmaag_check_required_fields(ufo_font): recommended_fields = [] for field in [ "unitsPerEm", "ascender", "descender", "xHeight", "capHeight", "familyName" ]: if ufo_font.info.__dict__.get("_" + field) is None: recommended_fields.append(field) if recommended_fields: yield FA...
Check that required fields are present in the UFO fontinfo. ufo2ft requires these info fields to compile a font binary: unitsPerEm, ascender, descender, xHeight, capHeight and familyName.
def remove_polygons(self, test): empty = [] for element in self.elements: if isinstance(element, PolygonSet): ii = 0 while ii < len(element.polygons): if test(element.polygons[ii], element.layers[ii], element.dat...
Remove polygons from this cell. The function or callable ``test`` is called for each polygon in the cell. If its return value evaluates to ``True``, the corresponding polygon is removed from the cell. Parameters ---------- test : callable Test function to q...
def as_list_data(self): element = ElementTree.Element(self.list_type) id_ = ElementTree.SubElement(element, "id") id_.text = self.id name = ElementTree.SubElement(element, "name") name.text = self.name return element
Return an Element to be used in a list. Most lists want an element with tag of list_type, and subelements of id and name. Returns: Element: list representation of object.
def pull_cfg_from_parameters_out_file( parameters_out_file, namelist_to_read="nml_allcfgs" ): parameters_out = read_cfg_file(parameters_out_file) return pull_cfg_from_parameters_out( parameters_out, namelist_to_read=namelist_to_read )
Pull out a single config set from a MAGICC ``PARAMETERS.OUT`` file. This function reads in the ``PARAMETERS.OUT`` file and returns a single file with the config that needs to be passed to MAGICC in order to do the same run as is represented by the values in ``PARAMETERS.OUT``. Parameters ---------...
def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict: params_dict = self.as_dict(quiet=True) if not preference_orders: preference_orders = [] preference_orders.append(["dataset_reader", "iterator", "model", "tra...
Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial preference orders. ["A", "B", "C"] means "A" > "B" > "C". For multiple preference_orders fir...
def unserialize(cls, string): id_s, created_s = string.split('_') return cls(int(id_s, 16), datetime.utcfromtimestamp(int(created_s, 16)))
Unserializes from a string. :param string: A string created by :meth:`serialize`.
def _read_sequences(self, graph): for e in self._get_elements(graph, SBOL.Sequence): identity = e[0] c = self._get_rdf_identified(graph, identity) c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements) c['encoding'] = self._get_triplet_value(graph...
Read graph and add sequences to document
def catch_exceptions(orig_func): @functools.wraps(orig_func) def catch_exceptions_wrapper(self, *args, **kwargs): try: return orig_func(self, *args, **kwargs) except arvados.errors.ApiError as e: logging.exception("Failure") return {"msg": e._get_reason(), "st...
Catch uncaught exceptions and turn them into http errors
def infer_declared(ms, namespace=None): conditions = [] for m in ms: for cav in m.caveats: if cav.location is None or cav.location == '': conditions.append(cav.caveat_id_bytes.decode('utf-8')) return infer_declared_from_conditions(conditions, namespace)
Retrieves any declared information from the given macaroons and returns it as a key-value map. Information is declared with a first party caveat as created by declared_caveat. If there are two caveats that declare the same key with different values, the information is omitted from the map. When the...
def to_datetime(value): if value is None: return None if isinstance(value, six.integer_types): return parser.parse(value) return parser.isoparse(value)
Converts a string to a datetime.
def send_message(self, msg): if self.socket is not None: msg.version = self.PROTOCOL_VERSION serialized = msg.SerializeToString() data = struct.pack(">I", len(serialized)) + serialized try: self.socket.send(data) except Exception as e: ...
Internal method used to send messages through Clementine remote network protocol.
def reftrack_version_data(rt, role): tfi = rt.get_taskfileinfo() if not tfi: return return filesysitemdata.taskfileinfo_version_data(tfi, role)
Return the data for the version that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the version :rtype: depending on...
def get_results(self, job_id): url = self._url('%s/results' % job_id) return self.client.get(url)
Get results of a job Args: job_id (str): The ID of the job. See: https://auth0.com/docs/api/management/v2#!/Jobs/get_results
def s3path(self, rel_path): import urlparse path = self.path(rel_path, public_url=True) parts = list(urlparse.urlparse(path)) parts[0] = 's3' parts[1] = self.bucket_name return urlparse.urlunparse(parts)
Return the path as an S3 schema
def postActivate_(self): self.tmpfile = os.path.join(constant.tmpdir,"valkka-"+str(os.getpid())) self.analyzer = ExternalDetector( executable = self.executable, image_dimensions = self.image_dimensions, tmpfile = self.tmpfile )
Create temporary file for image dumps and the analyzer itself
def group_id(self, resource_id): if self._name != 'group': self._request_uri = '{}/{}'.format(self._api_uri, resource_id)
Update the request URI to include the Group ID for specific group retrieval. Args: resource_id (string): The group id.
def _setID(self, id): if type(id) in (types.ListType, types.TupleType): try: for key in self._sqlPrimary: value = id[0] self.__dict__[key] = value id = id[1:] except IndexError: raise 'Not enough ...
Set the ID, ie. the values for primary keys. id can be either a list, following the _sqlPrimary, or some other type, that will be set as the singleton ID (requires 1-length sqlPrimary).
def non_interactions(graph, t=None): nodes = set(graph) while nodes: u = nodes.pop() for v in nodes - set(graph[u]): yield (u, v)
Returns the non-existent edges in the graph at time t. Parameters ---------- graph : NetworkX graph. Graph to find non-existent edges. t : snapshot id (default=None) If None the non-existent edges are identified on the flattened graph. Returns ...
def group_list(**kwargs): ctx = Context(**kwargs) ctx.execute_action('group:list', **{ 'storage': ctx.repo.create_secure_service('storage'), })
Show available routing groups.
def get_hostinfo(self,callb=None): response = self.req_with_resp(GetInfo, StateInfo,callb=callb ) return None
Convenience method to request the device info from the device This will request the information from the device and request that callb be executed when a response is received. The is no default callback :param callb: Callable to be used when the response is received. If not set, ...
def user_add_link(self): if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = ...
Create link by user.
def generate_command(self): example = [] example.append(f"{sys.argv[0]}") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] == list: value = " ".join(self.spec[key].get('example', '')) elif self.spec[key]['type'] == dict: ...
Generate a sample command
def vfolders(access_key): fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Last Used', 'last_used'), ('Max Files', 'max_files'), ('Max Size', 'max_size'), ] if access_key is None: q = 'query { vfolders { $fields } }' else: q = 'query($a...
List and manage virtual folders.
def send(self, message): try: self.ws.send(json.dumps(message)) except websocket._exceptions.WebSocketConnectionClosedException: raise SelenolWebSocketClosedException()
Send a the defined message to the backend. :param message: Message to be send, usually a Python dictionary.
def load_private_key(self, priv_key): with open(priv_key) as fd: self._private_key = paramiko.RSAKey.from_private_key(fd)
Register the SSH private key.
def _fragment_one_level(self, mol_graphs): unique_fragments_on_this_level = [] for mol_graph in mol_graphs: for edge in mol_graph.graph.edges: bond = [(edge[0],edge[1])] try: fragments = mol_graph.split_molecule_subgraphs(bond, allow_revers...
Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs, then loop through each graph's edges and attempt to remove that edge in order to obtain two disconnected subgraphs, aka two new fragments. If successful, check to see if the new fragments are alrea...
def _make_transitions(self) -> List[Transition]: module_name = settings.TRANSITIONS_MODULE module_ = importlib.import_module(module_name) return module_.transitions
Load the transitions file.
def last(self): start = max(self.number - 1, 0) * self.size return Batch(start, self.size, self.total_size)
Returns the last batch for the batched sequence. :rtype: :class:`Batch` instance.
def worldview(self) -> str: views = self._data['worldview'] return self.random.choice(views)
Get a random worldview. :return: Worldview. :Example: Pantheism.
def get_obs_function(self): obs_function = [] for variable in self.network.findall('ObsFunction'): for var in variable.findall('CondProb'): cond_prob = defaultdict(list) cond_prob['Var'] = var.find('Var').text cond_prob['Parent'] = var.find('Pa...
Returns the observation function as nested dict in the case of table- type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_obs_function() [{'Var': 'obs_sensor', ...
def _get_template_dirs(): return filter(lambda x: os.path.exists(x), [ os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'), os.path.join('/', 'usr', 'share', 'py2pack', 'templates'), os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), ])
existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins!
def in_unit_of(self, unit, as_quantity=False): new_unit = u.Unit(unit) new_quantity = self.as_quantity.to(new_unit) if as_quantity: return new_quantity else: return new_quantity.value
Return the current value transformed to the new units :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like "1 / (erg cm**2 s)" :param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point num...
def pdf_row_limiter(rows, limits=None, **kwargs): limits = limits or [None, None] upper_limit = limits[0] if limits else None lower_limit = limits[1] if len(limits) > 1 else None return rows[upper_limit: lower_limit]
Limit row passing a value. In this case we dont implementate a best effort algorithm because the posibilities are infite with a data text structure from a pdf.
def login(self, username, password): d = self.send_command('login', keys={'client_login_name': username, 'client_login_password': password}) if d == 0: self._log.info('Login Successful') return True return False
Login to the TS3 Server @param username: Username @type username: str @param password: Password @type password: str
def start(self): self.stop() self._task = asyncio.ensure_future(self._pinger(), loop=self._loop)
Start the pinging coroutine using the client and event loop which was passed to the constructor. :meth:`start` always behaves as if :meth:`stop` was called right before it.
def callback(self, cats): enable = bool(cats) if not enable: self.search.visible = False enable_widget(self.search_widget, enable) enable_widget(self.remove_widget, enable) if self.done_callback: self.done_callback(cats)
When a catalog is selected, enable widgets that depend on that condition and do done_callback
def secgroup_create(self, name, description): nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret
Create a security group
def add_section(self, section_name): if section_name == "DEFAULT": raise Exception("'DEFAULT' is reserved section name.") if section_name in self._sections: raise Exception( "Error! %s is already one of the sections" % section_name) else: self....
Add an empty section.
def _filter_response(self, response_dict): filtered_dict = {} for key, value in response_dict.items(): if key == "_jsns": continue if key == "xmlns": continue if type(value) == list and len(value) == 1: filtered_dict[key...
Add additional filters to the response dictionary Currently the response dictionary is filtered like this: * If a list only has one item, the list is replaced by that item * Namespace-Keys (_jsns and xmlns) are removed :param response_dict: the pregenerated, but unfiltered respons...
def _call_config(self, method, *args, **kwargs): return getattr(self._config, method)(self._section_name, *args, **kwargs)
Call the configuration at the given method which must take a section name as first argument
def _select_options(pat): if pat in _registered_options: return [pat] keys = sorted(_registered_options.keys()) if pat == 'all': return keys return [k for k in keys if re.search(pat, k, re.I)]
returns a list of keys matching `pat` if pat=="all", returns all registered options
def findCampaignsByName(target): try: from astropy.coordinates import SkyCoord from astropy.coordinates.name_resolve import NameResolveError from astropy.utils.data import conf conf.remote_timeout = 90 except ImportError: print('Error: AstroPy needs to be installed for th...
Returns a list of the campaigns that cover a given target. Parameters ---------- target : str Name of the celestial object. Returns ------- campaigns : list of int A list of the campaigns that cover the given target name. ra, dec : float, float Resolved coordinates...
def delete(self, file_path, branch, commit_message, **kwargs): path = '%s/%s' % (self.path, file_path.replace('/', '%2F')) data = {'branch': branch, 'commit_message': commit_message} self.gitlab.http_delete(path, query_data=data, **kwargs)
Delete a file on the server. Args: file_path (str): Path of the file to remove branch (str): Branch from which the file will be removed commit_message (str): Commit message for the deletion **kwargs: Extra options to send to the server (e.g. sudo) Raises...
def getDataPath(_system=thisSystem, _FilePath=FilePath): if _system == "Windows": pathName = "~/Crypto101/" else: pathName = "~/.crypto101/" path = _FilePath(expanduser(pathName)) if not path.exists(): path.makedirs() return path
Gets an appropriate path for storing some local data, such as TLS credentials. If the path doesn't exist, it is created.
def p_startswith(self, st, ignorecase=False): "Return True if the input starts with `st` at current position" length = len(st) matcher = result = self.input[self.pos:self.pos + length] if ignorecase: matcher = result.lower() st = st.lower() if matcher == s...
Return True if the input starts with `st` at current position
def add_text(self, end, next=None): if self.str_begin != end: self.fmt.append_text(self.format[self.str_begin:end]) if next is not None: self.str_begin = next
Adds the text from string beginning to the specified ending index to the format. :param end: The ending index of the string. :param next: The next string begin index. If None, the string index will not be updated.
def hash(*cols): sc = SparkContext._active_spark_context jc = sc._jvm.functions.hash(_to_seq(sc, cols, _to_java_column)) return Column(jc)
Calculates the hash code of given columns, and returns the result as an int column. >>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect() [Row(hash=-757602832)]
def delete(self): if self.parent is None: raise RuntimeError( "Current statement has no parent, so it cannot " + "be deleted form a procmailrc structure" ) elif self.id is None: raise RuntimeError("id not set but have a parent, this sho...
Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id
def on_exception(func): class OnExceptionDecorator(LambdaDecorator): def on_exception(self, exception): return func(exception) return OnExceptionDecorator
Run a function when a handler thows an exception. It's return value is returned to AWS. Usage:: >>> # to create a reusable decorator >>> @on_exception ... def handle_errors(exception): ... print(exception) ... return {'statusCode': 500, 'body': 'uh oh'} ...
def reflected_light_intensity(self): self._ensure_mode(self.MODE_REFLECT) return self.value(0) * self._scale('REFLECT')
A measurement of the reflected light intensity, as a percentage.
def call_requests( requests: Union[Request, Iterable[Request]], methods: Methods, debug: bool ) -> Response: if isinstance(requests, collections.Iterable): return BatchResponse(safe_call(r, methods, debug=debug) for r in requests) return safe_call(requests, methods, debug=debug)
Takes a request or list of Requests and calls them. Args: requests: Request object, or a collection of them. methods: The list of methods that can be called. debug: Include more information in error responses.
def update_terms_translations(self, project_id, file_path=None, language_code=None, overwrite=False, sync_terms=False, tags=None, fuzzy_trigger=None): return self._upload( project_id=project_id, updating=self.UPDATING_TERM...
Updates terms translations overwrite: set it to True if you want to overwrite translations sync_terms: set it to True if you want to sync your terms (terms that are not found in the uploaded file will be deleted from project and the new ones added). Ignored if updating = transla...
def init_controller(url): global _VERA_CONTROLLER created = False if _VERA_CONTROLLER is None: _VERA_CONTROLLER = VeraController(url) created = True _VERA_CONTROLLER.start() return [_VERA_CONTROLLER, created]
Initialize a controller. Provides a single global controller for applications that can't do this themselves
def as_scipy_functional(func, return_gradient=False): def func_call(arr): return func(np.asarray(arr).reshape(func.domain.shape)) if return_gradient: def func_gradient_call(arr): return np.asarray( func.gradient(np.asarray(arr).reshape(func.domain.shape))) ret...
Wrap ``op`` as a function operating on linear arrays. This is intended to be used with the `scipy solvers <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_. Parameters ---------- func : `Functional`. A functional that should be wrapped return_gradient : bool, optional ...
def webhook_handler(request): body = request.stream.read().decode('utf8') print('webhook handler saw:', body) api.notify_webhook_received(payload=body) print('key store contains:', api._db.keys())
Receives the webhook from mbed cloud services Passes the raw http body directly to mbed sdk, to notify that a webhook was received
def is_superset(reference_set ): def is_superset_of(x): missing = reference_set - x if len(missing) == 0: return True else: raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing) is_superset_of.__name__ = 'is_superset_of_{}'...
'Is superset' validation_function generator. Returns a validation_function to check that x is a superset of reference_set :param reference_set: the reference set :return:
def select_subscription(subs_code, subscriptions): if subs_code and subscriptions: for subs in subscriptions: if (subs.subscription_code == subs_code): return subs return None
Return the uwnetid.subscription object with the subs_code.
def pickle_dict(items): ret = {} pickled_keys = [] for key, val in items.items(): if isinstance(val, basestring): ret[key] = val else: pickled_keys.append(key) ret[key] = pickle.dumps(val) if pickled_keys: ret['_pickled'] = ','.join(pickled_key...
Returns a new dictionary where values which aren't instances of basestring are pickled. Also, a new key '_pickled' contains a comma separated list of keys corresponding to the pickled values.
def GET(self, url): r = requests.get(url) if self.verbose: sys.stdout.write("%s %s\n" % (r.status_code, r.encoding)) sys.stdout.write(str(r.headers) + "\n") self.encoding = r.encoding return r.text
returns text content of HTTP GET response.
def _case_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: self._handle_child(CaseNode(), stmt, sctx)
Handle case statement.