code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def export_deleted_fields(self): result = [] if self.__modified_data__ is not None: return result for index, item in enumerate(self): try: deleted_fields = item.export_deleted_fields() result.extend(['{}.{}'.format(index, key) for key in de...
Returns a list with any deleted fields form original data. In tree models, deleted fields on children will be appended.
def download(self, uri, file_path): with open(file_path, 'wb') as file: return self._connection.download_to_stream(file, uri)
Downloads the contents of the requested URI to a stream. Args: uri: URI file_path: File path destination Returns: bool: Indicates if the file was successfully downloaded.
def terminate(pid, sig, timeout): os.kill(pid, sig) start = time.time() while True: try: _, status = os.waitpid(pid, os.WNOHANG) except OSError as exc: if exc.errno != errno.ECHILD: raise else: if status: return True...
Terminates process with PID `pid` and returns True if process finished during `timeout`. Current user must have permission to access process information.
def _find_short_paths(self, paths): path_parts_s = [path.split(os.path.sep) for path in paths] root_node = {} for parts in sorted(path_parts_s, key=len, reverse=True): node = root_node for part in parts: node = node.setdefault(part, {}) node.cl...
Find short paths of given paths. E.g. if both `/home` and `/home/aoik` exist, only keep `/home`. :param paths: Paths. :return: Set of short paths.
def _advance_window(self): x_to_remove, y_to_remove = self._x_in_window[0], self._y_in_window[0] self._window_bound_lower += 1 self._update_values_in_window() x_to_add, y_to_add = self._x_in_window[-1], self._y_in_window[-1] self._remove_observation(x_to_remove, y_to_remove) ...
Update values in current window and the current window means and variances.
def users_changed_handler(stream): while True: yield from stream.get() users = [ {'username': username, 'uuid': uuid_str} for username, uuid_str in ws_connections.values() ] packet = { 'type': 'users-changed', 'value': sorted(u...
Sends connected client list of currently active users in the chatroom
def e_164(msisdn: str) -> str: number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None) return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
Returns the msisdn in E.164 international format.
def write(self): html = self.render() if self.file_type == 'pdf': self.write_pdf(html) else: with codecs.open(self.destination_file, 'w', encoding='utf_8') as outfile: outfile.write(html)
Writes generated presentation code into the destination file.
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element): BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, data_object_element) data_object_id = data_object_...
Adds to graph the new element that represents BPMN data object. Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing ...
def from_string(string_data, file_format="xyz"): mols = pb.readstring(str(file_format), str(string_data)) return BabelMolAdaptor(mols.OBMol)
Uses OpenBabel to read a molecule from a string in all supported formats. Args: string_data: String containing molecule data. file_format: String specifying any OpenBabel supported formats. Returns: BabelMolAdaptor object
def restore_taskset(self, taskset_id): try: return self.get(taskset_id=taskset_id) except self.model.DoesNotExist: pass
Get the async result instance by taskset id.
def _run_queries(self, agent_strs, stmt_types, params, persist): self._query_over_statement_types(agent_strs, stmt_types, params) assert len(self.__done_dict) == len(stmt_types) \ or None in self.__done_dict.keys(), \ "Done dict was not initiated for all stmt_type's." if ...
Use paging to get all statements requested.
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True): global LOGGERS loggername = name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logger_config = LOGGING_CONFIG.get(name, DEFAULT_LOGGING_CONFIG) logger = _get_basic...
Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the logger :param log_to_file: Boolean, True if logger should log to a file as well. :return: Logger
def get_state_vector_sampler(n_sample): def sampling_by_measurement(circuit, meas): val = 0.0 e = expect(circuit.run(returns="statevector"), meas) bits, probs = zip(*e.items()) dists = np.random.multinomial(n_sample, probs) / n_sample return dict(zip(tuple(bits), dists)) ...
Returns a function which get the expectations by sampling the state vector
def exclude_functions(self, *funcs): for f in funcs: f.exclude = True run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats) cProfileFuncStat.run_time_s = run_time_s
Excludes the contributions from the following functions.
def doAction(self, loginMethod, actionClass): loginAccount = loginMethod.account return actionClass( self, loginMethod.localpart + u'@' + loginMethod.domain, loginAccount)
Show the form for the requested action.
def now(self): try: if self.now_id: return Chart(self.now_id) else: log.debug('attempted to get current chart, but none was found') return except AttributeError: log.debug('attempted to get current ("now") chart from a c...
fetch the chart identified by this chart's now_id attribute if the now_id is either null or not present for this chart return None returns the new chart instance on sucess
def _compute_nonlinear_magnitude_term(self, C, mag): return self._compute_linear_magnitude_term(C, mag) +\ C["b3"] * ((mag - 7.0) ** 2.)
Computes the non-linear magnitude term
async def wait(self): while True: await self.eio.wait() await self.sleep(1) if not self._reconnect_task: break await self._reconnect_task if self.eio.state != 'connected': break
Wait until the connection with the server ends. Client applications can use this function to block the main thread during the life of the connection. Note: this method is a coroutine.
def _get_spec(self) -> dict: if self.spec: return self.spec self.spec = requests.get(self.SPEC_URL.format(self.version)).json() return self.spec
Fetches the OpenAPI spec from the server. If the spec has already been fetched, the cached version is returned instead. ArgS: None Returns: OpenAPI spec data
def _get_runner(classpath, main, jvm_options, args, executor, cwd, distribution, create_synthetic_jar, synthetic_jar_dir): executor = executor or SubprocessExecutor(distribution) safe_cp = classpath if create_synthetic_jar: safe_cp = safe_classpath(classpath, synthetic_jar_dir) ...
Gets the java runner for execute_java and execute_java_async.
def datetime_parsing(text, base_date=datetime.now()): matches = [] found_array = [] for expression, function in regex: for match in expression.finditer(text): matches.append((match.group(), function(match, base_date), match.span())) for match, value, spans in matches: subn = ...
Extract datetime objects from a string of text.
def warsaw_up_to_warsaw(C, parameters=None, sectors=None): C_in = smeftutil.wcxf2arrays_symmetrized(C) p = default_parameters.copy() if parameters is not None: p.update(parameters) Uu = Ud = Ul = Ue = np.eye(3) V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"]) Uq = V ...
Translate from the 'Warsaw up' basis to the Warsaw basis. Parameters used: - `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined as the mismatch between left-handed quark mass matrix diagonalization matrices).
def GetValue(self, row, col): if len(self.dataframe): return str(self.dataframe.iloc[row, col]) return ''
Find the matching value from pandas DataFrame, return it.
def get_brokendate_fx_forward_rate(self, asset_manager_id, asset_id, price_date, value_date): self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s - Price Date: %s - Value Date: %s', asset_manager_id, asset_id, price_date, value_date) url = '%s/brokendateforward...
This method takes calculates broken date forward FX rate based on the passed in parameters
def convert_to_feature_collection(self): if self.data['type'] == 'FeatureCollection': return if not self.embed: raise ValueError( 'Data is not a FeatureCollection, but it should be to apply ' 'style or highlight. Because `embed=False` it cannot be ...
Convert data into a FeatureCollection if it is not already.
def split_array_like(df, columns=None): dtypes = df.dtypes if columns is None: columns = df.columns elif isinstance(columns, str): columns = [columns] for column in columns: expanded = np.repeat(df.values, df[column].apply(len).values, axis=0) expanded[:, df.columns.get_l...
Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. columns : ~typing.Collection[str] or str or None ...
def indexed_file(self, f): filename, handle = f if handle is None and filename is not None: handle = open(filename) if (handle is None and filename is None) or \ (filename != self._indexed_filename) or \ (handle != self._indexed_file_handle): self.index = {} if ((handle is not ...
Setter for information about the file this object indexes. :param f: a tuple of (filename, handle), either (or both) of which can be None. If the handle is None, but filename is provided, then handle is created from the filename. If both handle and filename are None, or th...
def run(self): if self.args['add']: self.action_add() elif self.args['rm']: self.action_rm() elif self.args['show']: self.action_show() elif self.args['rename']: self.action_rename() else: self.action_run_command()
Perform the specified action
def serialize(exc): return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
Serialize `self.exc` into a data dictionary representing it.
def _error_catcher(self): clean_exit = False try: try: yield except SocketTimeout: raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: if 'read operation timed out' not in str(e): ...
Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool.
def get_level_values(self, level): level = self._get_level_number(level) values = self._get_level_values(level) return values
Return vector of label values for requested level, equal to the length of the index. Parameters ---------- level : int or str ``level`` is either the integer position of the level in the MultiIndex, or the name of the level. Returns ------- ...
def subnet_delete(auth=None, **kwargs): cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.delete_subnet(**kwargs)
Delete a subnet name Name or ID of the subnet to update CLI Example: .. code-block:: bash salt '*' neutronng.subnet_delete name=subnet1 salt '*' neutronng.subnet_delete \ name=1dcac318a83b4610b7a7f7ba01465548
def write(self, path=None): if not self._path and not path: raise ConfigException('no config path given') if path: self._path = path if '~' in self._path: self._path = os.path.expanduser(self._path) f = open(self._path, 'w') f.write(json.dumps(...
Write config data to disk. If this config object already has a path, it will write to it. If it doesn't, one must be passed during this call. :param str path: path to config file
def _api_post(self, url, **kwargs): kwargs['url'] = self.url + url kwargs['auth'] = self.auth headers = deepcopy(self.headers) headers.update(kwargs.get('headers', {})) kwargs['headers'] = headers self._post(**kwargs)
A convenience wrapper for _post. Adds headers, auth and base url by default
def drawQuad(page, quad, color=None, fill=None, dashes=None, width=1, roundCap=False, morph=None, overlay=True): img = page.newShape() Q = img.drawQuad(Quad(quad)) img.finish(color=color, fill=fill, dashes=dashes, width=width, roundCap=roundCap, morph=morph) img.commit(ov...
Draw a quadrilateral.
def get_hosting_devices_for_agent(self, context, host): agent_ids = self._dmplugin.get_cfg_agents(context, active=None, filters={'host': [host]}) if agent_ids: return [self._dmplugin.get_device_info_for_agent(context, hd_db) ...
Fetches routers that a Cisco cfg agent is managing. This function is supposed to be called when the agent has started, is ready to take on assignments and before any callbacks to fetch logical resources are issued. :param context: contains user information :param host: originat...
def parallel_for(loop_function, parameters, nb_threads=100): import multiprocessing.pool from contextlib import closing with closing(multiprocessing.pool.ThreadPool(nb_threads)) as pool: return pool.map(loop_function, parameters)
Execute the loop body in parallel. .. note:: Race-Conditions Executing code in parallel can cause an error class called "race-condition". Parameters ---------- loop_function : Python function which takes a tuple as input parameters : List of tuples Each element here sho...
def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None, use_compiled_model=False, update_endpoint=False, **kwargs): self._ensure_latest_training_job() endpoint_name = endpoint_name or self.latest_training_job.name self.deploy_instance_typ...
Deploy the trained model to an Amazon SageMaker endpoint and return a ``sagemaker.RealTimePredictor`` object. More information: http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html Args: initial_instance_count (int): Minimum number of EC2 instances to deploy to...
def list_of_objects_from_api(url): response = requests.get(url) content = json.loads(response.content) count = content["meta"]["total_count"] if count <= 20: return content["items"] else: items = [] + content["items"] num_requests = int(math.ceil(count // 20)) for i i...
API only serves 20 pages by default This fetches info on all of items and return them as a list Assumption: limit of API is not less than 20
def _set_nil(self, element, value_parser): if self.value: element.text = value_parser(self.value) else: element.attrib['nil'] = 'true' return element
Method to set an attribute of the element. If the value of the field is None then set the nil='true' attribute in the element :param element: the element which needs to be modified :type element: xml.etree.ElementTree.Element :param value_parser: the lambda function which changes will b...
def get_dataset(self, name, multi_instance=0): return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0]
get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaul...
def load_to_array(self, keys): data = np.empty((len(self.data[keys[0]]), len(keys))) for i in range(0, len(self.data[keys[0]])): for j, key in enumerate(keys): data[i, j] = self.data[key][i] return data
This loads the data contained in the catalogue into a numpy array. The method works only for float data :param keys: A list of keys to be uploaded into the array :type list:
def get_codon(seq, codon_no, start_offset): seq = seq.replace("-","") codon_start_pos = int(codon_no - 1)*3 - start_offset codon = seq[codon_start_pos:codon_start_pos + 3] return codon
This function takes a sequece and a codon number and returns the codon found in the sequence at that position
def _to_dsn(hosts): p = urlparse(hosts) try: user_and_pw, netloc = p.netloc.split('@', maxsplit=1) except ValueError: netloc = p.netloc user_and_pw = 'crate' try: host, port = netloc.split(':', maxsplit=1) except ValueError: host = netloc port = 5432 ...
Convert a host URI into a dsn for aiopg. >>> _to_dsn('aiopg://myhostname:4242/mydb') 'postgres://crate@myhostname:4242/mydb' >>> _to_dsn('aiopg://myhostname:4242') 'postgres://crate@myhostname:4242/doc' >>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require') 'postgres://hoschi:pw...
def load_pyobj(name, pyobj): 'Return Sheet object of appropriate type for given sources in `args`.' if isinstance(pyobj, list) or isinstance(pyobj, tuple): if getattr(pyobj, '_fields', None): return SheetNamedTuple(name, pyobj) else: return SheetList(name, pyobj) elif...
Return Sheet object of appropriate type for given sources in `args`.
def check_column(state, name, missing_msg=None, expand_msg=None): if missing_msg is None: missing_msg = "We expected to find a column named `{{name}}` in the result of your query, but couldn't." if expand_msg is None: expand_msg = "Have another look at your query result. " msg_kwargs = {"nam...
Zoom in on a particular column in the query result, by name. After zooming in on a column, which is represented as a single-column query result, you can use ``has_equal_value()`` to verify whether the column in the solution query result matches the column in student query result. Args: name: n...
def style(self): LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) hazard_class = hazard_class_field['key'] for layer ...
Function to apply some styles to the layers.
def _repr_mimebundle_(self, *args, **kwargs): chart = self.to_chart() dct = chart.to_dict() return alt.renderers.get()(dct)
Return a MIME bundle for display in Jupyter frontends.
def connect_database(url): db = _connect_database(url) db.copy = lambda: _connect_database(url) return db
create database object by url mysql: mysql+type://user:passwd@host:port/database sqlite: # relative path sqlite+type:///path/to/database.db # absolute path sqlite+type:////path/to/database.db # memory database sqlite+type:// mongodb: mongodb+t...
def cli(env, identifier): mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') if not (env.skip_confirmations or formatting.no_going_back(subnet_id)): raise exceptions.CLIAbort('Aborted') m...
Cancel a subnet.
def calculate_localised_cost(self, d1, d2, neighbours, motions): my_nbrs_with_motion = [n for n in neighbours[d1] if n in motions] my_motion = (d1.center[0] - d2.center[0], d1.center[1] - d2.center[1]) if my_nbrs_with_motion == []: distance = euclidean_dist(d1.center, d2.center) / se...
Calculates assignment cost between two cells taking into account the movement of cells neighbours. :param CellFeatures d1: detection in first frame :param CellFeatures d2: detection in second frame
def visit_delete(self, node): return "del %s" % ", ".join(child.accept(self) for child in node.targets)
return an astroid.Delete node as string
def remove_image(self, image_id, force=False, noprune=False): logger.info("removing image '%s' from filesystem", image_id) logger.debug("image_id = '%s'", image_id) if isinstance(image_id, ImageName): image_id = image_id.to_str() self.d.remove_image(image_id, force=force, nop...
remove provided image from filesystem :param image_id: str or ImageName :param noprune: bool, keep untagged parents? :param force: bool, force remove -- just trash it no matter what :return: None
def _gmtime(timestamp): try: return time.gmtime(timestamp) except OSError: dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp) dst = int(_isdst(dt)) return time.struct_time(dt.timetuple()[:8] + tuple([dst]))
Custom gmtime because yada yada.
def _generate_union_properties(self, fields): for field in fields: if not is_void_type(field.data_type): doc = self.process_doc( field.doc, self._docf) if field.doc else undocumented warning_str = ( ' @note Ensure the `is{}` met...
Emits union instance properties from the given fields.
def _read_audio_data(self, file_path): try: self.log(u"Reading audio data...") audio_file = AudioFile( file_path=file_path, file_format=self.OUTPUT_AUDIO_FORMAT, rconf=self.rconf, logger=self.logger ) ...
Read audio data from file. :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
def get_instance_attribute(self, instance_id, attribute): params = {'InstanceId' : instance_id} if attribute: params['Attribute'] = attribute return self.get_object('DescribeInstanceAttribute', params, InstanceAttribute, verb='POST')
Gets an attribute from an instance. :type instance_id: string :param instance_id: The Amazon id of the instance :type attribute: string :param attribute: The attribute you need information about Valid choices are: * instanceType|kern...
def get_context_data(self, **kwargs): context = super(CrossTypeAnimalList, self).get_context_data(**kwargs) context['list_type'] = self.kwargs['breeding_type'] return context
This add in the context of list_type and returns this as whatever the crosstype was.
def close_monomers(self, group, cutoff=4.0): nearby_residues = [] for self_atom in self.atoms.values(): nearby_atoms = group.is_within(cutoff, self_atom) for res_atom in nearby_atoms: if res_atom.parent not in nearby_residues: nearby_residues.a...
Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Distance cut off. Returns ------- ne...
def ppca(Y, Q, iterations=100): from numpy.ma import dot as madot N, D = Y.shape W = np.random.randn(D, Q) * 1e-3 Y = np.ma.masked_invalid(Y, copy=0) mu = Y.mean(0) Ycentered = Y - mu try: for _ in range(iterations): exp_x = np.asarray_chkfinite(np.linalg.solve(W.T.dot(W)...
EM implementation for probabilistic pca. :param array-like Y: Observed Data :param int Q: Dimensionality for reduced array :param int iterations: number of iterations for EM
def prepare_axes(axes, title, size, cmap=None): if axes is None: return None axes.set_xlim([0, size[1]]) axes.set_ylim([size[0], 0]) axes.set_aspect('equal') axes.axis('off') if isinstance(cmap, str): title = '{} (cmap: {})'.format(title, cmap) axes.set_title(title) axes_...
Prepares an axes object for clean plotting. Removes x and y axes labels and ticks, sets the aspect ratio to be equal, uses the size to determine the drawing area and fills the image with random colors as visual feedback. Creates an AxesImage to be shown inside the axes object and sets the needed p...
def servers(self): url = "%s/servers" % self.root return Servers(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
gets the federated or registered servers for Portal
def pelix_bundles(self): framework = self.__context.get_framework() return { bundle.get_bundle_id(): { "name": bundle.get_symbolic_name(), "version": bundle.get_version(), "state": bundle.get_state(), "location": bundle.get_loca...
List of installed bundles
def _correct_qualimap_genome_results(samples): for s in samples: if verify_file(s.qualimap_genome_results_fpath): correction_is_needed = False with open(s.qualimap_genome_results_fpath, 'r') as f: content = f.readlines() metrics_started = False ...
fixing java.lang.Double.parseDouble error on entries like "6,082.49"
def pair_looper(iterator): left = START for item in iterator: if left is not START: yield (left, item) left = item
Loop through iterator yielding items in adjacent pairs
def top(self): for child in self.children(skip_not_present=False): if not isinstance(child, AddrmapNode): continue return child raise RuntimeError
Returns the top-level addrmap node
def get_batched(portal_type=None, uid=None, endpoint=None, **kw): results = get_search_results(portal_type=portal_type, uid=uid, **kw) size = req.get_batch_size() start = req.get_batch_start() complete = req.get_complete(default=_marker) if complete is _marker: complete = uid and True or Fal...
Get batched results
def _load_scratch_orgs(self): current_orgs = self.list_orgs() if not self.project_config.orgs__scratch: return for config_name in self.project_config.orgs__scratch.keys(): if config_name in current_orgs: continue self.create_scratch_org(config_...
Creates all scratch org configs for the project in the keychain if a keychain org doesn't already exist
def lastId(self) -> BaseReference: if self.childIds is not None: if len(self.childIds) > 0: return self.childIds[-1] return None else: raise NotImplementedError
Last child's id of current TextualNode
def _create_dict_with_nested_keys_and_val(cls, keys, value): if len(keys) > 1: new_keys = keys[:-1] new_val = {keys[-1]: value} return cls._create_dict_with_nested_keys_and_val(new_keys, new_val) elif len(keys) == 1: return {keys[0]: value} else: raise ValueError('Keys must con...
Recursively constructs a nested dictionary with the keys pointing to the value. For example: Given the list of keys ['a', 'b', 'c', 'd'] and a primitive value 'hello world', the method will produce the nested dictionary {'a': {'b': {'c': {'d': 'hello world'}}}}. The number of keys in the list defin...
def convolve_stack(data, kernel, rot_kernel=False, method='scipy'): r if rot_kernel: kernel = rotate_stack(kernel) return np.array([convolve(data_i, kernel_i, method=method) for data_i, kernel_i in zip(data, kernel)])
r"""Convolve stack of data with stack of kernels This method convolves the input data with a given kernel using FFT and is the default convolution used for all routines Parameters ---------- data : np.ndarray Input data array, normally a 2D image kernel : np.ndarray Input kerne...
def do(self): 'Do or redo the action' self._runner = self._generator(*self.args, **self.kwargs) rets = next(self._runner) if isinstance(rets, tuple): self._text = rets[0] return rets[1:] elif rets is None: self._text = '' r...
Do or redo the action
def hessian(self, theta_x, theta_y, kwargs_lens, k=None, diff=0.00000001): alpha_ra, alpha_dec = self.alpha(theta_x, theta_y, kwargs_lens) alpha_ra_dx, alpha_dec_dx = self.alpha(theta_x + diff, theta_y, kwargs_lens) alpha_ra_dy, alpha_dec_dy = self.alpha(theta_x, theta_y + diff, kwargs_lens) ...
computes the hessian components f_xx, f_yy, f_xy from f_x and f_y with numerical differentiation :param theta_x: x-position (preferentially arcsec) :type theta_x: numpy array :param theta_y: y-position (preferentially arcsec) :type theta_y: numpy array :param kwargs_lens: list o...
def retweet(self, id): try: self._client.retweet(id=id) return True except TweepError as e: if e.api_code == TWITTER_PAGE_DOES_NOT_EXISTS_ERROR: return False raise
Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise
def update_lbaas_healthmonitor(self, lbaas_healthmonitor, body=None): return self.put(self.lbaas_healthmonitor_path % (lbaas_healthmonitor), body=body)
Updates a lbaas_healthmonitor.
def reverse_segment(path, n1, n2): q = path.copy() if n2 > n1: q[n1:(n2+1)] = path[n1:(n2+1)][::-1] return q else: seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1] brk = len(q) - n1 q[n1:] = seg[:brk] q[:(n2+1)] = seg[brk:] return q
Reverse the nodes between n1 and n2.
def update_multi_precision(self, index, weight, grad, state): if self.multi_precision and weight.dtype == numpy.float16: weight_master_copy = state[0] original_state = state[1] grad32 = grad.astype(numpy.float32) self.update(index, weight_master_copy, grad32, orig...
Updates the given parameter using the corresponding gradient and state. Mixed precision version. Parameters ---------- index : int The unique index of the parameter into the individual learning rates and weight decays. Learning rates and weight decay ...
def import_object(name: str) -> Any: if name.count(".") == 0: return __import__(name) parts = name.split(".") obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]]) try: return getattr(obj, parts[-1]) except AttributeError: raise ImportError("No module named %s" % parts...
Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.ut...
def _get_button_label(self): dlg = wx.TextEntryDialog(self, _('Button label:')) if dlg.ShowModal() == wx.ID_OK: label = dlg.GetValue() else: label = "" dlg.Destroy() return label
Gets Button label from user and returns string
def _get_method_kwargs(self): method_kwargs = { 'user': self.user, 'content_type': self.ctype, 'object_id': self.content_object.pk, } return method_kwargs
Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object.
def get_project_export(self, project_id): try: result = self._request('/getprojectexport/', {'projectid': project_id}) return TildaProject(**result) except NetworkError: return []
Get project info for export
def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate): cc = CapturingClient(Queue(), re.compile(tasks_regex), tasks_negate, re.compile(workers_regex), workers_negate) self.observers.append(cc) yield cc.queue...
Connects a client to the streaming capture, filtering the events that are sent to it. Args: tasks_regex (str): a pattern to filter tasks to capture. ex.: '^dispatch|^email' to filter names starting with that or 'dispatch.*123456' to filter that exact na...
def _encode_query(query): if query == '': return query query_args = [] for query_kv in query.split('&'): k, v = query_kv.split('=') query_args.append(k + "=" + quote(v.encode('utf-8'))) return '&'.join(query_args)
Quote all values of a query string.
def get_object_handle(self, obj): if obj not in self._object_handles: self._object_handles[obj] = self._get_object_handle(obj=obj) return self._object_handles[obj]
Gets the vrep object handle.
def install(self, host): print("Installing..") if self._state["installed"]: return if self.is_headless(): log.info("Headless host") return print("aboutToQuit..") self.app.aboutToQuit.connect(self._on_application_quit) if host == "Maya":...
Setup common to all Qt-based hosts
def get_by_symbol(self, symbol: str) -> Commodity: assert isinstance(symbol, str) query = ( self.currencies_query .filter(Commodity.mnemonic == symbol) ) return query.one()
Loads currency by symbol
def poll(self, timeout=None): p = select.poll() p.register(self._fd, select.POLLIN | select.POLLPRI) events = p.poll(int(timeout * 1000)) if len(events) > 0: return True return False
Poll for data available for reading from the serial port. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Default is a blocking poll. Args: timeout (int, float, None): timeout duration in seconds. ...
def tokenize(code): tok_regex = '|'.join('(?P<{}>{})'.format(*pair) for pair in _tokens) tok_regex = re.compile(tok_regex, re.IGNORECASE|re.M) line_num = 1 line_start = 0 for mo in re.finditer(tok_regex, code): kind = mo.lastgroup value = mo.group(kind) if kind == 'NEWLINE': ...
Tokenize the string `code`
def lock_area(self, code, index): logger.debug("locking area code %s index %s" % (code, index)) return self.library.Srv_LockArea(self.pointer, code, index)
Locks a shared memory area.
def install_reqs(venv, repo_dest): with dir_path(repo_dest): args = ['-r', 'requirements/compiled.txt'] if not verbose: args.insert(0, '-q') subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'install'] + args)
Installs all compiled requirements that can't be shipped in vendor.
def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs): from .bases import ContainerProperty from .dataspec import DataSpec name = self.name if name in new_class_attrs: raise RuntimeError("Two property generators both ...
``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of...
def error_router(self, original_handler, e): if self._has_fr_route(): try: return self.handle_error(e) except Exception: pass return original_handler(e)
This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful endpoint, our handler will be dispatched. If it happened in an unrelated view, the app's original error handler will be dispatched. In the event that the error occurred i...
def crl_distribution_points(self): if self._crl_distribution_points is None: self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value) return self._crl_distribution_points
Returns complete CRL URLs - does not include delta CRLs :return: A list of zero or more DistributionPoint objects
def _init_params_default(self): Yimp = self.Y.copy() Inan = sp.isnan(Yimp) Yimp[Inan] = Yimp[~Inan].mean() if self.P==1: C = sp.array([[Yimp.var()]]) else: C = sp.cov(Yimp.T) C /= float(self.n_randEffs) for ti in range(self.n_randEffs): sel...
Internal method for default parameter initialization
def delete_refund(self, refund_id): request = self._delete('transactions/refunds/' + str(refund_id)) return self.responder(request)
Deletes an existing refund transaction.
def check_initializers(initializers, keys): if initializers is None: return {} _assert_is_dictlike(initializers, valid_keys=keys) keys = set(keys) if not set(initializers) <= keys: extra_keys = set(initializers) - keys raise KeyError( "Invalid initializer keys {}, initializers can only " ...
Checks the given initializers. This checks that `initializers` is a dictionary that only contains keys in `keys`, and furthermore the entries in `initializers` are functions or further dictionaries (the latter used, for example, in passing initializers to modules inside modules) that must satisfy the same cons...
def visit_compare(self, node, parent): newnode = nodes.Compare(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.left, newnode), [ (self._cmp_op_classes[op.__class__], self.visit(expr, newnode)) for (op, expr) in zip(node.ops,...
visit a Compare node by returning a fresh instance of it
def add_line(self, line): if not self.is_valid_line(line): logger.warn( "Invalid line for %s section: '%s'", self.section_name, line ) return self.lines.append(line)
Adds a given line string to the list of lines, validating the line first.
def _most_common(iterable): data = Counter(iterable) return max(data, key=data.__getitem__)
Returns the most common element in `iterable`.