code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def take(attributes, properties): assert is_iterable_typed(attributes, basestring) assert is_iterable_typed(properties, basestring) result = [] for e in properties: if b2.util.set.intersection(attributes, feature.attributes(get_grist(e))): result.append(e) return result
Returns a property set which include all properties in 'properties' that have any of 'attributes'.
def unzip(file_obj): files = [] zip = ZipFile(file_obj) bad_file = zip.testzip() if bad_file: raise Exception( % bad_file) infolist = zip.infolist() for zipinfo in infolist: if zipinfo.filename.startswith(): continue file_obj = SimpleUploadedFile(n...
Take a path to a zipfile and checks if it is a valid zip file and returns...
def keyPressEvent(self, event): key = event.key() if key in [Qt.Key_Up]: self._parent.previous_row() elif key in [Qt.Key_Down]: self._parent.next_row() elif key in [Qt.Key_Enter, Qt.Key_Return]: self._parent.show_editor() else...
Qt Override.
def is_email(potential_email_address): context, mail = parseaddr(potential_email_address) first_condition = len(context) == 0 and len(mail) != 0 dot_after_at = ( in potential_email_address and in potential_email_address.split()[1]) return first_condition and dot_after_at
Check if potential_email_address is a valid e-mail address. Please note that this function has no false-negatives but many false-positives. So if it returns that the input is not a valid e-mail adress, it certainly isn't. If it returns True, it might still be invalid. For example, the domain could not ...
def electron_shell_str(shell, shellidx=None): am = shell[] amchar = lut.amint_to_char(am) amchar = amchar.upper() shellidx_str = if shellidx is not None: shellidx_str = .format(shellidx) exponents = shell[] coefficients = shell[] ncol = len(coefficients) + 1 point_pl...
Return a string representing the data for an electron shell If shellidx (index of the shell) is not None, it will also be printed
def get(self, campaign_id, nick=None): request = TOPRequest() request[] = campaign_id if nick!=None: request[] = nick self.create(self.execute(request), fields=[,,,,], models={:CampaignArea}) return self.result
xxxxx.xxxxx.campaign.area.get =================================== 取得一个推广计划的投放地域设置
def slamdunkOverallRatesPlot (self): pconfig = { : , : , : False, : False, : , : , : 2, : , : False, : False, : [ "Plus Strand +", "Minus ...
Generate the overall rates plot
def _resolve_responses(self): while True: message = self.res_queue.get() if message is None: _logger.debug("_resolve_responses thread is terminated") return self.__resolve_responses(message)
_resolve_responses
def gen_select_list(sig_dic): view_jushi = dic_tmp = sig_dic[] for key in dic_tmp.keys(): tmp_str = {0}.format(sig_dic[], key, dic_tmp[key]) view_jushi += tmp_str view_jushi += return view_jushi
For generating List view HTML file for SELECT. for each item.
def create(self, create_missing=None): return HostGroup( self._server_config, id=self.create_json(create_missing)[], ).read()
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1235377 <https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_.
def _convert(self, format): if self.format == format: return self else: image = Image(self.pil_image) image._format = format return image
Return a new Image instance with the given format. Returns self if the format is already the same.
def create_refresh_token(self, access_token_value): if access_token_value not in self.access_tokens: raise InvalidAccessToken(.format(access_token_value)) if not self.refresh_token_lifetime: logger.debug(, access_token_value) return None re...
Creates an refresh token bound to the specified access token.
def get(self, nicks=[], fields=[]): request = TOPRequest() request[] = .join(nicks) if not fields: user = User() fields = user.fields request[] = .join(fields) self.create(self.execute(request)) return self.users
taobao.users.get 获取多个用户信息
def xform(self, left, right, repeating, base, sign): base_prefix = if self.CONFIG.use_prefix: if base == 8: base_prefix = elif base == 16: base_prefix = else: base_prefix = base_subscript ...
Return prefixes for tuple. :param str left: left of the radix :param str right: right of the radix :param str repeating: repeating part :param int base: the base in which value is displayed :param int sign: -1, 0, 1 as appropriate :returns: the number string :rty...
def write(self, f): if isinstance(f, str): f = io.open(f, , encoding=) if not hasattr(f, ): raise AttributeError("Wrong type of file: {0}".format(type(f))) NS_LOGGER.info(.format(f.name)) for section in self.sections.keys(): f.write(.format(...
Write namespace as INI file. :param f: File object or path to file.
def raw_reader(queue=None): if queue is None: queue = BufferQueue() ctx = _HandlerContext( position=0, limit=None, queue=queue, field_name=None, annotations=None, depth=0, whence=None ) return reader_trampoline(_container_handler(None...
Returns a raw binary reader co-routine. Args: queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a new one will be created. Yields: IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed in the middle of a value or ...
def _fetch(self, endpoint_name, **params): params[] = self.api_key resp = requests.get(self._endpoint(endpoint_name), params=params) resp.raise_for_status() data = resp.json() self._check_or_raise(data.get(, {})) return data
Wrapper for making an api request from giphy
def _set_clear_mpls_auto_bandwidth_statistics_lsp(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=clear_mpls_auto_bandwidth_statistics_lsp.clear_mpls_auto_bandwidth_statistics_lsp, is_leaf=True, yang_name="clear-mpls-auto-bandwidth-statistics-lsp", re...
Setter method for clear_mpls_auto_bandwidth_statistics_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_lsp (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_clear_mpls_auto_bandwidth_statistics_lsp is considered as a private method. ...
def libvlc_media_list_index_of_item(p_ml, p_md): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,),), None, ctypes.c_int, MediaList, Media) return f(p_ml, p_md)
Find index position of List media instance in media list. Warning: the function will return the first matched position. The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @param p_md: media instance. @return: position of media instance or -1...
def times(self, a): return Vector(self.x*a, self.y*a, self.z*a)
Multiply.
def calcWeightedAvg(data,weights): data_avg = np.mean(data,axis=1) weighted_sum = np.dot(data_avg,weights) return weighted_sum
Generates a weighted average of simulated data. The Nth row of data is averaged and then weighted by the Nth element of weights in an aggregate average. Parameters ---------- data : numpy.array An array of data with N rows of J floats weights : numpy.array A length N array of weigh...
def _make_like(self, column, format, value): c = [] if format.startswith(): c.append() c.append(value) if format.endswith(): c.append() return column.like(.join(c))
make like condition :param column: column object :param format: '%_' '_%' '%_%' :param value: column value :return: condition object
def build(self, **kw): try: self.get_executor()(self, **kw) except SCons.Errors.BuildError as e: e.node = self raise
Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread ...
def niggli_reduce(lattice, eps=1e-5): _set_no_error() niggli_lattice = np.array(np.transpose(lattice), dtype=, order=) result = spg.niggli_reduce(niggli_lattice, float(eps)) _set_error_message() if result == 0: return None else: return np.array(np.transpose(niggli_lattice)...
Run Niggli reduction Args: lattice: Lattice parameters in the form of [[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]] eps: float: Tolerance to check if difference of norms of two basis vectors is close to zero or not and if tw...
def conditional_committors(source, sink, waypoint, msm): for data in [source, sink, waypoint]: if not isinstance(data, int): raise ValueError("source, sink, and waypoint must be integers.") if (source == waypoint) or (sink == waypoint) or (sink == source): raise ValueErro...
Computes the conditional committors :math:`q^{ABC^+}` which are is the probability of starting in one state and visiting state B before A while also visiting state C at some point. Note that in the notation of Dickson et. al. this computes :math:`h_c(A,B)`, with ``sources = A``, ``sinks = B``, ``waypoi...
def btc_witness_script_deserialize(_script): script = None if isinstance(_script, str) and re.match(, _script): script = binascii.unhexlify(_script) else: script = _script[:] ptr = [0] witness_stack_len = read_var_int(ptr, script) witness_stack = [] for...
Given a hex-encoded serialized witness script, turn it into a witness stack (i.e. an array of Nones, ints, and strings)
def mouse_move(self, event): if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE): self.posX = event.xdata self.posY = event.ydata self.graphic_target(self.posX, self.posY)
The following gets back coordinates of the mouse on the canvas.
def _query_response_to_snapshot(response_pb, collection, expected_prefix): if not response_pb.HasField("document"): return None document_id = _helpers.get_doc_id(response_pb.document, expected_prefix) reference = collection.document(document_id) data = _helpers.decode_dict(response_pb.docu...
Parse a query response protobuf to a document snapshot. Args: response_pb (google.cloud.proto.firestore.v1beta1.\ firestore_pb2.RunQueryResponse): A collection (~.firestore_v1beta1.collection.CollectionReference): A reference to the collection that initiated the query. ...
def __callback (self, odom): pose = odometry2Pose3D(odom) self.lock.acquire() self.data = pose self.lock.release()
Callback function to receive and save Pose3d. @param odom: ROS Odometry received @type odom: Odometry
def set_nested(data, value, *keys): if len(keys) == 1: data[keys[0]] = value else: if keys[0] not in data: data[keys[0]] = {} set_nested(data[keys[0]], value, *keys[1:])
Assign to a nested dictionary. :param dict data: Dictionary to mutate :param value: Value to set :param list *keys: List of nested keys >>> data = {} >>> set_nested(data, 'hi', 'k0', 'k1', 'k2') >>> data {'k0': {'k1': {'k2': 'hi'}}}
def get_raw_file(): with open("{0}/dividers.txt".format( os.path.abspath( os.path.dirname(__file__) ) ), mode="r") as file_handler: lines = file_handler.readlines() lines[35] = str( random.randint(0, 999999999999) ) return lines
Get the raw divider file in a string array. :return: the array :rtype: str
def DemangleName(self, name): "Applies some simple heuristics to split names into (city, name)." return (nam, SPECIAL_CITIES.get(city, city))
Applies some simple heuristics to split names into (city, name).
def normalise_rows(matrix): lengths = np.apply_along_axis(np.linalg.norm, 1, matrix) if not (lengths > 0).all(): lengths[lengths == 0] = 1 return matrix / lengths[:, np.newaxis]
Scales all rows to length 1. Fails when row is 0-length, so it leaves these unchanged
def start(self, timeout=None, task=None, block_callbacks=False, role=None): self.close_connection() if self.is_running(): logger.error() self.set_state() return True if not block_callbacks: self.__cb_p...
Start PostgreSQL Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion or failure. :returns: True if start was initiated and postmaster ports are open, False if start failed
def clean_tenant_url(url_string): if hasattr(settings, ): if (settings.PUBLIC_SCHEMA_URLCONF and url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)): url_string = url_string[len(settings.PUBLIC_SCHEMA_URLCONF):] return url_string
Removes the TENANT_TOKEN from a particular string
def get_last_update(op): last_update = get_end_time(op) if not last_update: last_event = get_last_event(op) if last_event: last_update = last_event[] if not last_update: last_update = get_create_time(op) return last_update
Return the most recent timestamp in the operation.
def read_in_weight_table(self, in_weight_table): print("Reading the weight table...") with open_csv(in_weight_table, "r") as csvfile: reader = csv.reader(csvfile) header_row = next(reader) if len(header_row) < len(self.header_wt): ...
Read in weight table
def to_cartesian(r, theta, theta_units="radians"): assert theta_units in [, ],\ "kwarg theta_units must specified in radians or degrees" if theta_units == "degrees": theta = to_radians(theta) theta = to_proper_radians(theta) x = r * cos(theta) y = r * sin(theta) retu...
Converts polar r, theta to cartesian x, y.
def SetStorageProfiler(self, storage_profiler): self._storage_profiler = storage_profiler if self._storage_file: self._storage_file.SetStorageProfiler(storage_profiler)
Sets the storage profiler. Args: storage_profiler (StorageProfiler): storage profiler.
async def unpinChatMessage(self, chat_id): p = _strip(locals()) return await self._api_request(, _rectify(p))
See: https://core.telegram.org/bots/api#unpinchatmessage
def bookmark_rename(bookmark_id_or_name, new_bookmark_name): client = get_client() bookmark_id = resolve_id_or_name(client, bookmark_id_or_name)["id"] submit_data = {"name": new_bookmark_name} res = client.update_bookmark(bookmark_id, submit_data) formatted_print(res, simple_text="Success")
Executor for `globus bookmark rename`
def peer(opt_peer, opt_username, opt_password, scope="module"): p = BigIP(opt_peer, opt_username, opt_password) return p
peer bigip fixture
def convert_enamldef_def_to_func(token_stream): in_enamldef = False depth = 0 for tok in token_stream: if tok.type == : in_enamldef = True elif tok.type == : depth += 1 elif in_enamldef and tok.type == : depth -= 1 ...
A token stream processor which processes all enaml declarative functions to allow using `def` instead of `func`. It does this by transforming DEF tokens to NAME within enamldef blocks and then changing the token value to `func`. Notes ------ Use this at your own risk! This was a feature...
def create_versions(self, project_id, versions): for v in versions: self.create_version(project_id, v)
Accepts result of getVersions()
def get_cpu_info(self): info = snap7.snap7types.S7CpuInfo() result = self.library.Cli_GetCpuInfo(self.pointer, byref(info)) check_error(result, context="client") return info
Retrieves CPU info from client
def write_updates_to_csv(self, updates): with open(self._csv_file_name, ) as csvfile: csvwriter = self.csv_writer(csvfile) csvwriter.writerow(CSV_COLUMN_HEADERS) for update in updates: row = [ update.name, upda...
Given a list of updates, write the updates out to the provided CSV file. Args: updates (list): List of Update objects.
def adapt(self, d, x): self.x_mem[:,1:] = self.x_mem[:,:-1] self.x_mem[:,0] = x self.d_mem[1:] = self.d_mem[:-1] self.d_mem[0] = d self.y_mem = np.dot(self.x_mem.T, self.w) self.e_mem = self.d_mem - self.y_mem dw_part1 = np.dot(...
Adapt weights according one desired value and its input. **Args:** * `d` : desired value (float) * `x` : input array (1-dimensional array)
def is_python_interpreter(filename): real_filename = os.path.realpath(filename) if (not osp.isfile(real_filename) or not is_python_interpreter_valid_name(filename)): return False elif is_pythonw(filename): if os.name == : if not encoding.is_tex...
Evaluate wether a file is a python interpreter or not.
def get_states(self, dump_optimizer=False): return pickle.dumps((self.states, self.optimizer) if dump_optimizer else self.states)
Gets updater states. Parameters ---------- dump_optimizer : bool, default False Whether to also save the optimizer itself. This would also save optimizer information such as learning rate and weight decay schedules.
def mv_normal_like(x, mu, tau): R if len(np.shape(x)) > 1: return np.sum([flib.prec_mvnorm(r, mu, tau) for r in x]) else: return flib.prec_mvnorm(x, mu, tau)
R""" Multivariate normal log-likelihood .. math:: f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\} :Parameters: - `x` : (n,k) - `mu` : (k) Location parameter sequence. - `Tau` : (k,k) Positive definite precision matrix. ...
def process_buffer(self, i_block, receive_buffer): self._log.info("Worker thread processing block %i", i_block) time_overall0 = time.time() time_unpack = 0.0 time_write = 0.0 for i_heap, heap in enumerate(receive_buffer.result()): if isinstance(h...
Blocking function to process the received heaps. This is run in an executor.
def date_from_relative_week_year(base_date, time, dow, ordinal=1): relative_date = datetime(base_date.year, base_date.month, base_date.day) ord = convert_string_to_number(ordinal) if dow in year_variations: if time == or time == : return datetime(relative_date.year, 1, 1)...
Converts relative day to time Eg. this tuesday, last tuesday
def convert_dict_to_datetime(obj_map): converted_map = {} for key, value in obj_map.items(): if isinstance(value, dict) and in value.keys(): converted_map[key] = datetime.datetime(**value) elif isinstance(value, dict): converted_map[key] = convert_dict_to_datetime(v...
converts dictionary representations of datetime back to datetime obj
def get_trust_id(self): if not bool(self._my_map[]): raise errors.IllegalState() else: return Id(self._my_map[])
Gets the ``Trust`` ``Id`` for this authorization. return: (osid.id.Id) - the trust ``Id`` raise: IllegalState - ``has_trust()`` is ``false`` *compliance: mandatory -- This method must be implemented.*
def setTransducer(self, edfsignal, transducer): if (edfsignal < 0 or edfsignal > self.n_channels): raise ChannelDoesNotExist(edfsignal) self.channels[edfsignal][] = transducer self.update_header()
Sets the transducer of signal edfsignal :param edfsignal: int :param transducer: str Notes ----- This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action.
def _NormalizedVolumeIdentifiers( self, volume_system, volume_identifiers, prefix=): normalized_volume_identifiers = [] for volume_identifier in volume_identifiers: if isinstance(volume_identifier, int): volume_identifier = .format(prefix, volume_identifier) elif not volume_ident...
Normalizes volume identifiers. Args: volume_system (VolumeSystem): volume system. volume_identifiers (list[int|str]): allowed volume identifiers, formatted as an integer or string with prefix. prefix (Optional[str]): volume identifier prefix. Returns: list[str]: volume identi...
def items(self): queryset = self.get_queryset() self.cache_infos(queryset) self.set_max_entries() return queryset
Get a queryset, cache infos for standardized access to them later then compute the maximum of entries to define the priority of each items.
def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs): docx = docx_preprocess(docx, batch=batch) url_params = {"batch": batch, "api_key": api_key, "version": version} results = api_handler(docx, cloud=cloud, api="docxextraction", url_params=url_params, **kwargs) r...
Given a .docx file, returns the raw text associated with the given .docx file. The .docx file may be provided as base64 encoded data or as a filepath. Example usage: .. code-block:: python >>> from indicoio import docx_extraction >>> results = docx_extraction(docx_file) :param docx: Th...
def from_xso_item(cls, xso_item): item = cls(xso_item.jid) item.update_from_xso_item(xso_item) return item
Create a :class:`Item` with the :attr:`jid` set to the :attr:`.xso.Item.jid` obtained from `xso_item`. Then update that instance with `xso_item` using :meth:`update_from_xso_item` and return it.
def put(self, entity): if self._options.HasField("read_only"): raise RuntimeError("Transaction is read only") else: super(Transaction, self).put(entity)
Adds an entity to be committed. Ensures the transaction is not marked readonly. Please see documentation at :meth:`~google.cloud.datastore.batch.Batch.put` :type entity: :class:`~google.cloud.datastore.entity.Entity` :param entity: the entity to be saved. :raises: :cla...
def disaggregate(self, sitecol, ruptures, iml4, truncnorm, epsilons, monitor=Monitor()): acc = AccumDict(accum=[]) ctx_mon = monitor(, measuremem=False) pne_mon = monitor(, measuremem=False) clo_mon = monitor(, measuremem=False) for rupture in ruptur...
Disaggregate (separate) PoE in different contributions. :param sitecol: a SiteCollection with N sites :param ruptures: an iterator over ruptures with the same TRT :param iml4: a 4d array of IMLs of shape (N, R, M, P) :param truncnorm: an instance of scipy.stats.truncnorm :param ...
def format_time(x): if isinstance(x, (datetime64, datetime)): return format_timestamp(x) elif isinstance(x, (timedelta64, timedelta)): return format_timedelta(x) elif isinstance(x, ndarray): return list(x) if x.ndim else x[()] return x
Formats date values This function formats :class:`datetime.datetime` and :class:`datetime.timedelta` objects (and the corresponding numpy objects) using the :func:`xarray.core.formatting.format_timestamp` and the :func:`xarray.core.formatting.format_timedelta` functions. Parameters ---------- ...
def copy(self: BaseBoardT) -> BaseBoardT: board = type(self)(None) board.pawns = self.pawns board.knights = self.knights board.bishops = self.bishops board.rooks = self.rooks board.queens = self.queens board.kings = self.kings board.occupied_co[...
Creates a copy of the board.
def Convert(self, metadata, config, token=None): result = ExportedDNSClientConfiguration( metadata=metadata, dns_servers=" ".join(config.dns_server), dns_suffixes=" ".join(config.dns_suffix)) yield result
Converts DNSClientConfiguration to ExportedDNSClientConfiguration.
def get_programs(): programs = [] os.environ[] += os.pathsep + os.getcwd() for p in os.environ[].split(os.pathsep): if path.isdir(p): for f in os.listdir(p): if _is_executable(path.join(p, f)): yield f
Returns a generator that yields the available executable programs :returns: a generator that yields the programs available after a refresh_listing() :rtype: generator
def islink(path): if six.PY3 or not salt.utils.platform.is_windows(): return os.path.islink(path) if not HAS_WIN32FILE: log.error(, path) if not _is_reparse_point(path): return False reparse_data = _get_reparse_data(path) if not reparse_data: ...
Equivalent to os.path.islink()
def cp(src, dst, overwrite=False): if not isinstance(src, list): src = [src] dst = os.path.expanduser(dst) dst_folder = os.path.isdir(dst) if len(src) > 1 and not dst_folder: raise OSError("Cannot copy multiple item to same file") for item in src: source = os.path.ex...
Copy files to a new location. :param src: list (or string) of paths of files to copy :param dst: file or folder to copy item(s) to :param overwrite: IF the file already exists, should I overwrite it?
def choices(cls, blank=False): choices = sorted([(key, value) for key, value in cls.values.items()], key=lambda x: x[0]) if blank: choices.insert(0, (, Enum.Value(, None, , cls))) return choices
Choices for Enum :return: List of tuples (<value>, <human-readable value>) :rtype: list
def states(self): state_list = [] for state in States: if state.value & self._states != 0: state_list.append(state) if (self._flashing_states & States.FILTER) != 0: state_list.append(States.FILTER_LOW_SPEED) return state_list
Returns a set containing the enabled states.
def next(self): if not self.__has_more(): raise StopIteration() else: return javabridge.get_env().get_string(self.__next())
Reads the next dataset row. :return: the next row :rtype: Instance
def xirr(values, dates, guess=0): if isinstance(values, Range): values = values.values if isinstance(dates, Range): dates = dates.values if guess is not None and guess != 0: raise ValueError( % guess) else: try: return scipy.optimize.newton(lambda r: x...
Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the excel function XIRR(). Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d :param values: the payments of which at least one has to be ne...
def to_price_index(returns, start=100): return (returns.replace(to_replace=np.nan, value=0) + 1).cumprod() * start
Returns a price index given a series of returns. Args: * returns: Expects a return series * start (number): Starting level Assumes arithmetic returns. Formula is: cumprod (1+r)
def get_user_subscription_to_discussion(recID, uid): user_email = User.query.get(uid).email (emails1, emails2) = get_users_subscribed_to_discussion( recID, check_authorizations=False) if user_email in emails1: return 1 elif user_email in emails2: return 2 else: r...
Returns the type of subscription for the given user to this discussion. This does not check authorizations (for eg. if user was subscribed, but is suddenly no longer authorized). :param recID: record ID :param uid: user id :return: - 0 if user is not subscribed to discussion ...
def conv_uuid(self, column, name, **kwargs): return [f(column, name, **kwargs) for f in self.uuid_filters]
Convert UUID filter.
def _get_depencency_var_name(self, dependency): for dep_path, var_name in self.dependencies: if dep_path == dependency: return var_name
Returns the variable name assigned to the given dependency or None if the dependency has not yet been registered. Args: dependency (str): Thet dependency that needs to be imported. Returns: str or None
def get(self, index): if self and (index <= len(self) -1): return self._result_cache[index]
Get the element by index. If index is out of bounds for the internal list, None is returned. Indexes cannot be negative. :param int index: retrieve element by positive index in list :rtype: SubElement or None
def heldout_log_likelihood(self, test_mask=None): if test_mask is None: if self.mask is None: return 0 else: test_mask = ~self.mask xs = np.hstack((self.gaussian_states, self.inputs)) if self.single_emission: ...
Compute the log likelihood of the masked data given the latent discrete and continuous states.
def form(value): if isinstance(value, FLOAT + INT): if value <= 0: return str(value) elif value < .001: return % value elif value < 10 and isinstance(value, FLOAT): return % value elif value > 1000: return .format(int(round(value...
Format numbers in a nice way. >>> form(0) '0' >>> form(0.0) '0.0' >>> form(0.0001) '1.000E-04' >>> form(1003.4) '1,003' >>> form(103.4) '103' >>> form(9.3) '9.30000' >>> form(-1.2) '-1.2'
def police_priority_map_conform_map_pri1_conform(self, **kwargs): config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, "name") name_key.text = ...
Auto Generated Code
def load_preset(self): if in self.settings.preview: with open(os.path.join(os.path.dirname(__file__), )) as f: presets = yaml.load(f.read()) if self.settings.preview[] in presets: self.preset = presets[self.settings.preview[]] return...
Loads preset if it is specified in the .frigg.yml
def summary(self): TotalAvailableDownloadedInstalledCategories if self.count() == 0: return results = {: 0, : 0, : 0, : 0, : {}, : {}} for update in self.update...
Create a dictionary with a summary of the updates in the collection. Returns: dict: Summary of the contents of the collection .. code-block:: cfg Summary of Updates: {'Total': <total number of updates returned>, 'Available': <updates that are not downl...
def handle_subscribe(self, request, path): ret = [] if path: name = path[0] if name not in self.children: self.children[name] = NotifierNode( getattr(self.data, name, None), self) ret += self.children[...
Add to the list of request to notify, and notify the initial value of the data held Args: request (Subscribe): The subscribe request path (list): The relative path from ourself Returns: list: [(callback, Response)] that need to be called
def has_image(self, name: str) -> bool: path = "docker/images/{}".format(name) r = self.__api.head(path) if r.status_code == 204: return True elif r.status_code == 404: return False self.__api.handle_erroneous_response(r)
Determines whether the server has a Docker image with a given name.
def _Close(self): super(RawFile, self)._Close() for file_object in self._file_objects: file_object.close() self._file_objects = []
Closes the file-like object.
def is_valid_port(instance: int): if not isinstance(instance, (int, str)): return True return int(instance) in range(65535)
Validates data is a valid port
def substitute_environ(self): for attr_name in dir(self): if attr_name.startswith() or attr_name.upper() != attr_name: continue orig_value = getattr(self, attr_name) is_required = isinstance(orig_value, Required) orig_type = orig_value.v_...
Substitute environment variables into settings.
def toolchain_spec_prepare_loaderplugins( toolchain, spec, loaderplugin_read_key, handler_sourcepath_key, loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS): registry = spec_update_loaderplugin_registry( spec, default=toolchain.loaderplugin_registry) ...
A standard helper function for combining the filtered (e.g. using ``spec_update_sourcepath_filter_loaderplugins``) loaderplugin sourcepath mappings back into one that is usable with the standard ``toolchain_spec_compile_entries`` function. Arguments: toolchain The toolchain spec ...
def _iter_qs(self): cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.) nplanes = int(max(ceil(cumum / self.deltam), 1)) dq = cumum / nplanes for i in xrange(nplanes): yield self.qrange[0] * exp(2**(1/2.) * dq * (i + .5))
Iterate over the Q values
def get(self, singleExposure=False): self.log.info() if singleExposure: batchSize = 1 else: batchSize = int(self.settings["orbfit"]["batch size"]) exposureCount = 1 while exposureCount > 0: expsoureObjects, astorbString, ...
*get the orbfitPositions object* **Key Arguments:** - ``singleExposure`` -- only execute fot a single exposure (useful for debugging) **Return:** - None **Usage:** See class docstring
def getFixedStar(ID, jd): star = swe.sweFixedStar(ID, jd) _signInfo(star) return star
Returns a fixed star.
def _calc_lm_step(self, damped_JTJ, grad, subblock=None): delta0, res, rank, s = np.linalg.lstsq(damped_JTJ, -0.5*grad, rcond=self.min_eigval) if self._fresh_JTJ: CLOG.debug( % ( delta0.size-rank, delta0.size)) if subblock is not None: ...
Calculates a Levenberg-Marquard step w/o acceleration
def parse_relation(obj: dict) -> BioCRelation: rel = BioCRelation() rel.id = obj[] rel.infons = obj[] for node in obj[]: rel.add_node(BioCNode(node[], node[])) return rel
Deserialize a dict obj to a BioCRelation object
def cancel_bbuild(self, build_execution_configuration_id, **kwargs): kwargs[] = True if kwargs.get(): return self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs) else: (data) = self.cancel_bbuild_with_http_info(build_execution_configurati...
Cancel the build execution defined with given executionConfigurationId. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respons...
def apply(self, a, return_Ya=False): r if self.V.shape[1] == 0: Pa = numpy.zeros(a.shape) if return_Ya: return Pa, numpy.zeros((0, a.shape[1])) return Pa if return_Ya: x, Ya = self._apply(a, return_Ya=return_Ya) els...
r"""Apply the projection to an array. The computation is carried out without explicitly forming the matrix corresponding to the projection (which would be an array with ``shape==(N,N)``). See also :py:meth:`_apply`.
def mpstatus_to_json(status): msg_keys = list(status.msgs.keys()) data = for key in msg_keys[:-1]: data += mavlink_to_json(status.msgs[key]) + data += mavlink_to_json(status.msgs[msg_keys[-1]]) data += return data
Translate MPStatus in json string
def send_rsp_recv_cmd(self, target, data, timeout): return super(Device, self).send_rsp_recv_cmd(target, data, timeout)
While operating as *target* send response *data* to the remote device and return new command data if received within *timeout* seconds.
def EndEdit(self, row, col, grid, oldVal=None): self._tc.Unbind(wx.EVT_KEY_UP) self.ApplyEdit(row, col, grid) del self._col del self._row del self._grid
End editing the cell. This function must check if the current value of the editing control is valid and different from the original value (available as oldval in its string form.) If it has not changed then simply return None, otherwise return the value in its string form. *Mus...
def get_bucket_notification(self, bucket_name): is_valid_bucket_name(bucket_name) response = self._url_open( "GET", bucket_name=bucket_name, query={"notification": ""}, ) data = response.data.decode() return parse_get_bucket_notificat...
Get notifications configured for the given bucket. :param bucket_name: Bucket name.
def operation_name(operation, ns): verb = operation.value.name if ns.object_: return "{}_{}".format(verb, pluralize(ns.object_name)) else: return verb
Convert an operation, obj(s) pair into a swagger operation id. For compatability with Bravado, we want to use underscores instead of dots and verb-friendly names. Example: foo.retrieve => client.foo.retrieve() foo.search_for.bar => client.foo.search_for_bars()
def angToPix(nside, lon, lat, nest=False): theta = np.radians(90. - lat) phi = np.radians(lon) return hp.ang2pix(nside, theta, phi, nest=nest)
Input (lon, lat) in degrees instead of (theta, phi) in radians