Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
14,800
def get_corpus_path(name: str) -> [str, None]: db = TinyDB(corpus_db_path()) temp = Query() if len(db.search(temp.name == name)) > 0: path = get_full_data_path(db.search(temp.name == name)[0]["file"]) db.close() if not os.path.exists(path): download(name) ...
Get corpus path :param string name: corpus name
14,801
def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3): from .algorithms import reconstruct_acd Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps) return get_edm(Xhat)
Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: opt...
14,802
def post(self, url, headers=None, params=None, **kwargs): if len(kwargs) > 1: raise InvalidArgumentsError("Too many extra args ({} > 1)".format( len(kwargs))) if kwargs: kwarg = next(iter(kwargs)) if kwarg not in ("json", "data"): ...
Send a JSON POST request with the given request headers, additional URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. The 'json' and 'data' parameters may not both be given. Args: ur...
14,803
def is_dtype(cls, dtype): dtype = getattr(dtype, , dtype) if isinstance(dtype, (ABCSeries, ABCIndexClass, ABCDataFrame, np.dtype)): return False elif dtype is None: return False ...
Check if we match 'dtype'. Parameters ---------- dtype : object The object to check. Returns ------- is_dtype : bool Notes ----- The default implementation is True if 1. ``cls.construct_from_string(dtype)`` is an instance ...
14,804
def start(self): self.manager = multiprocessing.Manager() self.policies = self.manager.dict() policies = copy.deepcopy(operation_policy.policies) for policy_name, policy_set in six.iteritems(policies): self.policies[policy_name] = policy_set self.policy_moni...
Prepare the server to start serving connections. Configure the server socket handler and establish a TLS wrapping socket from which all client connections descend. Bind this TLS socket to the specified network address for the server. Raises: NetworkingError: Raised if the T...
14,805
def combining_search(self): start = ( self.get_pair(), ( self.cube["L"], self.cube["U"], self.cube["F"], self.cube["D"], self.cube["R"], self.cube["B"], ), ...
Searching the path for combining the pair.
14,806
def run_procedure(self, process_number, std_vs_mfg, params=): seqnum = random.randint(2, 254) self.logger.info( + str(process_number) + + hex(process_number) + + str(seqnum) + + hex(seqnum) + ) procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build() ...
Initiate a C1219 procedure, the request is written to table 7 and the response is read from table 8. :param int process_number: The numeric procedure identifier (0 <= process_number <= 2047). :param bool std_vs_mfg: Whether the procedure is manufacturer specified or not. True is manufacturer specified. :pa...
14,807
def _nonzero(self): nonzeros = np.nonzero(self.data) return tuple(Variable((dim), nz) for nz, dim in zip(nonzeros, self.dims))
Equivalent numpy's nonzero but returns a tuple of Varibles.
14,808
def println(msg): sys.stdout.write(msg) sys.stdout.flush() sys.stdout.write( * len(msg)) sys.stdout.flush()
Convenience function to print messages on a single line in the terminal
14,809
def get_views_traffic(self, per=github.GithubObject.NotSet): assert per is github.GithubObject.NotSet or (isinstance(per, (str, unicode)) and (per == "day" or per == "week")), "per must be day or week, day by default" url_parameters = dict() if per is not github.GithubObject.NotSet: ...
:calls: `GET /repos/:owner/:repo/traffic/views <https://developer.github.com/v3/repos/traffic/>`_ :param per: string, must be one of day or week, day by default :rtype: None or list of :class:`github.View.View`
14,810
async def delete(self, turn_context: TurnContext) -> None: if turn_context == None: raise TypeError() turn_context.turn_state.pop(self._context_service_key) storage_key = self.get_storage_key(turn_context) await self._storage.delete({ storage_ke...
Delete any state currently stored in this state scope. :param turn_context: The context object for this turn. :return: None
14,811
def dry_run_from_args(args: argparse.Namespace): parameter_path = args.param_path serialization_dir = args.serialization_dir overrides = args.overrides params = Params.from_file(parameter_path, overrides) dry_run_from_params(params, serialization_dir)
Just converts from an ``argparse.Namespace`` object to params.
14,812
def _compute_ll(self): self.fracs = [] self.logP = [] self.ll = [] for i in range(self.width): Dll = {: 0, : 0, : 0, : 0} Df = {: 0, : 0, : 0, : 0} DlogP= {: 0, : 0, : 0, : 0} for key in self.counts[i].keys(): ...
m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix
14,813
def set_options(self, **kw): r for k, v in kw.iteritems(): if k in self.__options: self.__options[k] = v
r"""Set Parser options. .. seealso:: ``kw`` argument have the same meaning as in :func:`lazyxml.loads`
14,814
def create_job_flow(self, job_flow_overrides): if not self.emr_conn_id: raise AirflowException() emr_conn = self.get_connection(self.emr_conn_id) config = emr_conn.extra_dejson.copy() config.update(job_flow_overrides) response = self.get_conn().run_job_fl...
Creates a job flow using the config from the EMR connection. Keys of the json extra hash may have the arguments of the boto3 run_job_flow method. Overrides for this config may be passed as the job_flow_overrides.
14,815
def check_py(self, version, name, original, loc, tokens): internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens) if self.target_info < get_target_info(version): raise self.make_err(CoconutTargetError, "found Python " + ".".join(version) + " " + name, original, loc,...
Check for Python-version-specific syntax.
14,816
def default_sort_key(item, order=None): from sympy.core import S, Basic from sympy.core.sympify import sympify, SympifyError from sympy.core.compatibility import iterable if isinstance(item, Basic): return item.sort_key(order=order) if iterable(item, exclude=string_types): if...
Return a key that can be used for sorting. The key has the structure: (class_key, (len(args), args), exponent.sort_key(), coefficient) This key is supplied by the sort_key routine of Basic objects when ``item`` is a Basic object or an object (other than a string) that sympifies to a Basic object....
14,817
def show_condition_operators(self, condition): permitted_operators = self.savedsearch.conditions_operators.get(condition) permitted_operators_list = set( [self.savedsearch.operators.get(op) for op in permitted_operators] ) return permitted_operators...
Show available operators for a given saved search condition
14,818
def _create_at(self, timestamp=None, id=None, forced_identity=None, **kwargs): id = Versionable.uuid(id) if forced_identity: ident = Versionable.uuid(forced_identity) else: ident = id if timestamp is None: timestamp = get_u...
WARNING: Only for internal use and testing. Create a Versionable having a version_start_date and version_birth_date set to some pre-defined timestamp :param timestamp: point in time at which the instance has to be created :param id: version 4 UUID unicode object. Usually this is not ...
14,819
def logout(self): if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False
Logout of a vSphere server.
14,820
def extract(group_id, access_token, fields=None): fields = fields or [, , , , ] assert set(fields).issubset(VALID_FIELDS) get_args = {: .join(fields), : access_token} get_args_str = .join( [.format(x, y) for x, y in get_args.items()]) base_url = .format( g...
FIXME: DOCS... Links: * https://developers.facebook.com/tools/explorer/
14,821
def remove_child_family(self, family_id, child_id): if self._catalog_session is not None: return self._catalog_session.remove_child_catalog(catalog_id=family_id, child_id=child_id) return self._hierarchy_session.remove_child(id_=family_id, child_id=child_id)
Removes a child from a family. arg: family_id (osid.id.Id): the ``Id`` of a family arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``family_id`` not a parent of ``child_id`` raise: NullArgument - ``family_id`` or ``child_id`` is ``null`` raise: ...
14,822
def apply_templates(toks, templates): for template in templates: name = .join([ % (f, o) for f, o in template]) for t in range(len(toks)): values_list = [] for field, offset in template: p = t + offset if p < 0 or p >= len(toks): ...
Generate features for an item sequence by applying feature templates. A feature template consists of a tuple of (name, offset) pairs, where name and offset specify a field name and offset from which the template extracts a feature value. Generated features are stored in the 'F' field of each item in the...
14,823
def commit_branches(sha1): cmd = .format(sha1) return shell.run( cmd, capture=True, never_pretend=True ).stdout.strip().split()
Get the name of the branches that this commit belongs to.
14,824
def qhalfx(self): if self.__qhalfx is None: self.log("qhalfx") self.__qhalfx = self.qhalf * self.jco self.log("qhalfx") return self.__qhalfx
get the half normal matrix attribute. Create the attribute if it has not yet been created Returns ------- qhalfx : pyemu.Matrix
14,825
def get_end(pos, alt, category, snvend=None, svend=None, svlen=None): end = pos if category in (, , ): end = snvend elif category == : end = svend if svend == pos: if svlen: end = pos + svlen ...
Return the end coordinate for a variant Args: pos(int) alt(str) category(str) snvend(str) svend(int) svlen(int) Returns: end(int)
14,826
def create_or_update_record(data, pid_type, id_key, minter): resolver = Resolver( pid_type=pid_type, object_type=, getter=Record.get_record) try: pid, record = resolver.resolve(data[id_key]) data_c = deepcopy(data) del data_c[] record_c = deepcopy(record) de...
Register a funder or grant.
14,827
def get_versioned_delete_collector_class(): key = try: cls = _cache[key] except KeyError: collector_class_string = getattr(settings, key) cls = import_from_string(collector_class_string, key) _cache[key] = cls return cls
Gets the class to use for deletion collection. :return: class
14,828
def check_marker_kwargs(self, kwargs): text = kwargs.get("text", "") if not isinstance(text, str) and text is not None: raise TypeError("text argument is not of str type") for color in (item for item in (prefix + color for prefix in ["active_", "hover_", ""] ...
Check the types of the keyword arguments for marker creation :param kwargs: dictionary of options for marker creation :type kwargs: dict :raises: TypeError, ValueError
14,829
def validate_extra_link(self, extra_link): if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link: raise Exception("Invalid extra.links format. " + "Extra link must include a and field") self.validated_formatter(extra_link[EXTRA_LINK_FORMATTER_...
validate extra link
14,830
def blogroll(request, btype): response, site, cachekey = initview(request) if response: return response[0] template = loader.get_template(.format(btype)) ctx = dict() fjlib.get_extra_context(site, ctx) ctx = Context(ctx) response = HttpResponse( template.render(ctx), content_type= ) patch_vary_headers(res...
View that handles the generation of blogrolls.
14,831
def visualize_detection(self, img, dets, classes=[], thresh=0.6): import matplotlib.pyplot as plt import random plt.imshow(img) height = img.shape[0] width = img.shape[1] colors = dict() for det in dets: (klass, score, x0, y0, x1, y1) = det ...
visualize detections in one image Parameters: ---------- img : numpy.array image, in bgr format dets : numpy.array ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...]) each row is one object classes : tuple or list of str ...
14,832
def bgc(mag_file, dir_path=".", input_dir_path="", meas_file=, spec_file=, samp_file=, site_file=, loc_file=, append=False, location="unknown", site="", samp_con=, specnum=0, meth_code="LP-NO", volume=12, user="", timezone=, noave=False): version_num = pmag.get_version() i...
Convert BGC format file to MagIC file(s) Parameters ---------- mag_file : str input file name dir_path : str working directory, default "." input_dir_path : str input file directory IF different from dir_path, default "" meas_file : str output measurement file na...
14,833
def get_calc_id(db, datadir, job_id=None): calcs = datastore.get_calc_ids(datadir) calc_id = 0 if not calcs else calcs[-1] if job_id is None: try: job_id = db(, scalar=True) except NotFound: job_id = 0 return max(calc_id, job_id)
Return the latest calc_id by looking both at the datastore and the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param datadir: the directory containing the datastores :param job_id: a job ID; if None, returns the latest job ID
14,834
def part(z, s): r if sage_included: if s == 1: return np.real(z) elif s == -1: return np.imag(z) elif s == 0: return z else: if s == 1: return z.real elif s == -1: return z.imag elif s == 0: return z
r"""Get the real or imaginary part of a complex number.
14,835
def convert_basis(basis_dict, fmt, header=None): fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError(.format(fmt)) converter = _converter_map[fmt] if converter[] is not None: ftypes = set(basis_dict[]) if ftypes > converter[]: raise Ru...
Returns the basis set data as a string representing the data in the specified output format
14,836
def get_performance_signatures(self, project, **params): results = self._get_json(self.PERFORMANCE_SIGNATURES_ENDPOINT, project, **params) return PerformanceSignatureCollection(results)
Gets a set of performance signatures associated with a project and time range
14,837
def args_to_inject(self, function, bindings, owner_key): dependencies = {} key = (owner_key, function, tuple(sorted(bindings.items()))) def repr_key(k): owner_key, function, bindings = k return % (tuple(map(_describe, k[:2])) + (dict(k[2]),)) log.debu...
Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a method this will be the owning class. :returns: Dictionary of res...
14,838
def get_newsentry_meta_description(newsentry): if newsentry.meta_description: return newsentry.meta_description text = newsentry.get_description() if len(text) > 160: return u.format(text[:160]) return text
Returns the meta description for the given entry.
14,839
def main(search, query): url = search.search(query) print(url) search.open_page(url)
main function that does the search
14,840
def get_um(method_name, response=False): key = (method_name, response) if key not in method_lookup: match = re.findall(r, method_name, re.I) if not match: return None interface, method, version = match[0] if interface not in service_lookup: return ...
Get protobuf for given method name :param method_name: full method name (e.g. ``Player.GetGameBadgeLevels#1``) :type method_name: :class:`str` :param response: whether to return proto for response or request :type response: :class:`bool` :return: protobuf message
14,841
def thumbnail(self): if not isfile(self.thumb_path): self.logger.debug(, self) path = (self.dst_path if os.path.exists(self.dst_path) else self.src_path) try: s = self.settings if self.type == : ...
Path to the thumbnail image (relative to the album directory).
14,842
def Parse(conditions): kind = rdf_file_finder.FileFinderCondition.Type classes = { kind.MODIFICATION_TIME: ModificationTimeCondition, kind.ACCESS_TIME: AccessTimeCondition, kind.INODE_CHANGE_TIME: InodeChangeTimeCondition, kind.SIZE: SizeCondition, kind.EXT_FLAGS: Ex...
Parses the file finder condition types into the condition objects. Args: conditions: An iterator over `FileFinderCondition` objects. Yields: `MetadataCondition` objects that correspond to the file-finder conditions.
14,843
def parse(self, data, extent): if self._initialized: raise pycdlibexception.PyCdlibInternalError() (self.tag_ident, self.desc_version, tag_checksum, reserved, self.tag_serial_number, desc_crc, self.desc_crc_length, self.tag_location) = struct.unpack_from(...
Parse the passed in data into a UDF Descriptor tag. Parameters: data - The data to parse. extent - The extent to compare against for the tag location. Returns: Nothing.
14,844
def GetPatternIdTripDict(self): d = {} for t in self._trips: d.setdefault(t.pattern_id, []).append(t) return d
Return a dictionary that maps pattern_id to a list of Trip objects.
14,845
def batch_get_documents( self, database, documents, mask=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
Gets multiple documents. Documents returned by this method are not guaranteed to be returned in the same order that they were requested. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() ...
14,846
def is_micropython_usb_device(port): if type(port).__name__ == : if ( not in port or port[] != or not in port or port[] != ): return False usb_id = .format(port[], port[]) else: usb_id = port[2].lower() return True return ...
Checks a USB device to see if it looks like a MicroPython device.
14,847
def print_validation_errors(result): click.echo(red()) click.echo(red( * 40)) messages = result.get_messages() for property in messages.keys(): click.echo(yellow(property + )) for error in messages[property]: click.echo(red( + error)) click.echo()
Accepts validation result object and prints report (in red)
14,848
def remove_widget(self, widget): button = self._buttons.pop(widget) self.layout().removeWidget(button) button.deleteLater()
Remove the given widget from the tooltip :param widget: the widget to remove :type widget: QtGui.QWidget :returns: None :rtype: None :raises: KeyError
14,849
def _traverse_repos(self, callback, repo_name=None): repo_files = [] if os.path.exists(self.opts[]): repo_files.append(self.opts[]) for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(.format(self.opts[])): for repo_file in filenames: i...
Traverse through all repo files and apply the functionality provided in the callback to them
14,850
def login_failures(user): cmd = .format(user) cmd += " | grep -E " out = __salt__[](cmd, output_loglevel=, python_shell=True) ret = [] lines = out[].splitlines() for line in lines: ret.append(line.split()[0]) return ret
Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL
14,851
def lookup(self, mbid, include=()): if include: for included in include: if included not in self.available_includes: raise ValueError( "{0!r} is not an includable entity for {1}".format( included, self....
Lookup an entity directly from a specified :term:`MBID`\ .
14,852
def listDataTypes(self, datatype="", dataset=""): try: return self.dbsDataType.listDataType(dataType=datatype, dataset=dataset) except dbsException as de: dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.serverError) except Exception as ex: ...
API to list data types known to dbs (when no parameter supplied). :param dataset: Returns data type (of primary dataset) of the dataset (Optional) :type dataset: str :param datatype: List specific data type :type datatype: str :returns: List of dictionaries containing the follow...
14,853
def _freeze_relations(self, relations): if relations: sel = relations[0] sel.relations.extend(relations[1:]) return ct.SelectorList([sel.freeze()]) else: return ct.SelectorList()
Freeze relation.
14,854
def addports(self): timer = metrics.Timer() timer.start() for port in self.service.ports: p = self.findport(port) for op in port.binding.operations.values(): m = p[0].method(op.name) binding = m.binding.input method...
Look through the list of service ports and construct a list of tuples where each tuple is used to describe a port and it's list of methods as: (port, [method]). Each method is tuple: (name, [pdef,..] where each pdef is a tuple: (param-name, type).
14,855
def discover(self, metafile): for report in self.reports: if report.remote_location == : if naarad.utils.is_valid_file(os.path.join(os.path.join(report.location, self.resource_path), metafile)): with open(os.path.join(os.path.join(report.location, self.resource_path), metafile), ) as me...
Determine what summary stats, time series, and CDF csv exist for the reports that need to be diffed. :return: boolean: return whether the summary stats / time series / CDF csv summary was successfully located
14,856
def uimports(code): for uimport in UIMPORTLIST: uimport = bytes(uimport, ) code = code.replace(uimport, b + uimport) return code
converts CPython module names into MicroPython equivalents
14,857
def bios_image(self, bios_image): self._bios_image = self.manager.get_abs_image_path(bios_image) log.info(.format(name=self._name, id=self._id, ...
Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path
14,858
def names(self): if getattr(self, , None) is None: result = [] else: result = [self.key] if hasattr(self, ): result.extend(self.aliases) return result
Names, by which the instance can be retrieved.
14,859
def url(self): if self.parent is None: pieces = [self.client.base_url, , , ] else: pieces = [self.parent.url] pieces.append(self.model_class.path) return .join(pieces)
The url for this collection.
14,860
def translate_latex2unicode(text, kb_file=None): if kb_file is None: kb_file = get_kb_filename() try: text = decode_to_unicode(text) except UnicodeDecodeError: text = unicode(wash_for_utf8(text)) if CFG_LATEX_UNICODE_TRANSLATION_CONST == {}: _load_latex2uni...
Translate latex text to unicode. This function will take given text, presumably containing LaTeX symbols, and attempts to translate it to Unicode using the given or default KB translation table located under CFG_ETCDIR/bibconvert/KB/latex-to-unicode.kb. The translated Unicode string will then be re...
14,861
def extendedEuclid(a, b): if a == 0: return b, 0, 1 else: g, y, x = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b
14,862
def soma_points(self): db = self.data_block return db[db[:, COLS.TYPE] == POINT_TYPE.SOMA]
Get the soma points
14,863
def decrypt(self, ciphertext): cipherbytes = ciphertext.encode() try: combined = base64.b64decode(cipherbytes) except (base64.binascii.Error, TypeError) as e: raise DataIntegrityError("Cipher text is damaged: {}".form...
Return plaintext for given ciphertext.
14,864
def fetch_access_token_by_client_credentials(self): s Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from KKBOX such as public albums, playlists and so on. ...
There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from KKBOX such as public albums, playlists and so on. Howeve...
14,865
def pseudosection(self, column=, filename=None, log10=False, **kwargs): fig, ax, cb = PS.plot_pseudosection_type2( self.data, column=column, log10=log10, **kwargs ) if filename is not None: fig.savefig(filename, dpi=300) return fig, ax, cb
Plot a pseudosection of the given column. Note that this function only works with dipole-dipole data at the moment. Parameters ---------- column : string, optional Column to plot into the pseudosection, default: r filename : string, optional if not None, ...
14,866
def content_children(self): text_types = {CT_RegularTextRun, CT_TextLineBreak, CT_TextField} return tuple(elm for elm in self if type(elm) in text_types)
A sequence containing the text-container child elements of this ``<a:p>`` element, i.e. (a:r|a:br|a:fld).
14,867
def get_pool_details(self, pool_id): uri = % pool_id return super(ApiPool, self).get(uri)
Method to return object pool by id Param pool_id: pool id Returns object pool
14,868
def MatrixTriangularSolve(a, rhs, lower, adj): trans = 0 if not adj else 2 r = np.empty(rhs.shape).astype(a.dtype) for coord in np.ndindex(a.shape[:-2]): pos = coord + (Ellipsis,) r[pos] = sp.linalg.solve_triangular(a[pos] if not adj else np.conj(a[pos]), rhs[pos], ...
Matrix triangular solve op.
14,869
def print_file(self, f=sys.stdout, file_format="mwtab"): if file_format == "mwtab": for key in self: if key == "SUBJECT_SAMPLE_FACTORS": print(" elif key == "METABOLOMICS WORKBENCH": print(self.header, file=f) ...
Print :class:`~mwtab.mwtab.MWTabFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `mwtab` or `json`. :param f: Print to file or stdout. :param int tw: Tab width. :return: None :rtype: :py:obj:`None`
14,870
def unindex_template(self, tpl): name = getattr(tpl, , ) try: del self.name_to_template[name] except KeyError: pass
Unindex a template from the `templates` container. :param tpl: The template to un-index :type tpl: alignak.objects.item.Item :return: None
14,871
def avl_release_parent(node): parent = node.parent if parent is not None: if parent.right is node: parent.right = None elif parent.left is node: parent.left = None else: raise AssertionError() node.parent = None parent.balance = ma...
removes the parent of a child
14,872
def get_K(rho, z, alpha=1.0, zint=100.0, n2n1=0.95, get_hdet=False, K=1, Kprefactor=None, return_Kprefactor=False, npts=20, **kwargs): if type(rho) != np.ndarray or type(z) != np.ndarray or (rho.shape != z.shape): raise ValueError() pts, wts = np.polynomial.legendre....
Calculates one of three electric field integrals. Internal function for calculating point spread functions. Returns one of three electric field integrals that describe the electric field near the focus of a lens; these integrals appear in Hell's psf calculation. Parameters ---------- r...
14,873
def _process_state_embryo(self, job_record): uow, is_duplicate = self.insert_and_publish_uow(job_record, 0, 0) self.update_job(job_record, uow, job.STATE_IN_PROGRESS)
method that takes care of processing job records in STATE_EMBRYO state
14,874
def add(self, field, op=None, val=None): if field.has_subfield(): self._fields[field.full_name] = 1 else: self._fields[field.name] = 1 if op and op.is_size() and not op.is_variable(): self._slices[field.name] = val + 1 ...
Update report fields to include new one, if it doesn't already. :param field: The field to include :type field: Field :param op: Operation :type op: ConstraintOperator :return: None
14,875
def month_days(year, month): if month > 13: raise ValueError("Incorrect month index") if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR): return 29 if month == HESHVAN and (year_days(year) % 10) != 5: return 29 if month == KISLEV and (year_days(year) % 10) =...
How many days are in a given month of a given year
14,876
def transforms(self) -> Mapping[Type, Iterable[Type]]: try: return getattr(self.__class__, "transform")._transforms except AttributeError: return {}
The available data transformers.
14,877
def get_template_names(self): if self.request.is_ajax(): template = self.ajax_template_name else: template = self.template_name return template
Returns the template name to use for this request.
14,878
def _slice_area_from_bbox(self, src_area, dst_area, ll_bbox=None, xy_bbox=None): if ll_bbox is not None: dst_area = AreaDefinition( , , , {: }, 100, 100, ll_bbox) elif xy_bbox is not None: dst_area = AreaDefin...
Slice the provided area using the bounds provided.
14,879
def configure(args, parser): if not args.force and on_travis(): parser.error(red("doctr appears to be running on Travis. Use " "doctr configure --force to run anyway.")) if not args.authenticate: args.upload_key = False if args.travis_tld: if args.travis_tld in [, ...
Color guide - red: Error and warning messages - green: Welcome messages (use sparingly) - blue: Default values - bold_magenta: Action items - bold_black: Parts of code to be run or copied that should be modified
14,880
def create_resource_quota(self, name, quota_json): url = self._build_k8s_url("resourcequotas/") response = self._post(url, data=json.dumps(quota_json), headers={"Content-Type": "application/json"}) if response.status_code == http_client.CONFLICT: ...
Prevent builds being scheduled and wait for running builds to finish. :return:
14,881
def __roll(self, unrolled): rolled = [] index = 0 for count in range(len(self.__sizes) - 1): in_size = self.__sizes[count] out_size = self.__sizes[count+1] theta_unrolled = np.matrix(unrolled[index:index+(in_size+1)*out_size]) theta_rolled...
Converts parameter array back into matrices.
14,882
def attribute(name, value, getter=None, setter=None, deleter=None, label=None, desc=None, meta=None): _annotate("attribute", name, value, getter=getter, setter=setter, deleter=deleter, label=label, desc=desc, meta=meta)
Annotates a model attribute. @param name: attribute name, unique for a model. @type name: str or unicode @param value: attribute type information. @type value: implementer of L{src.feat.models.interface.IValueInfo} @param getter: an effect or None if the attribute is write-only; t...
14,883
def getMonitor(self): from .RegionMatching import Screen scr = self.getScreen() return scr if scr is not None else Screen(0)
Returns an instance of the ``Screen`` object this Location is inside. Returns the primary screen if the Location isn't positioned in any screen.
14,884
def remove_isolated_nodes(graph): nodes = list(nx.isolates(graph)) graph.remove_nodes_from(nodes)
Remove isolated nodes from the network, in place. :param pybel.BELGraph graph: A BEL graph
14,885
def hasLogger(self, logger): if isinstance(logger, logging.Logger): logger = logging.name return logger in self._loggers
Returns whether or not the inputed logger is tracked by this widget. :param logger | <str> || <logging.Logger>
14,886
def get_exception(self): self.lock.acquire() try: e = self.saved_exception self.saved_exception = None return e finally: self.lock.release()
Return any exception that happened during the last server request. This can be used to fetch more specific error information after using calls like `start_client`. The exception (if any) is cleared after this call. :return: an exception, or ``None`` if there is no stored ex...
14,887
def light_3d(self, r, kwargs_list, k=None): r = np.array(r, dtype=float) flux = np.zeros_like(r) for i, func in enumerate(self.func_list): if k is None or k == i: kwargs = {k: v for k, v in kwargs_list[i].items() if not k in [, ]} if self.prof...
computes 3d density at radius r :param x: coordinate in units of arcsec relative to the center of the image :type x: set or single 1d numpy array
14,888
def _delete(self, identifier=None): assert identifier is not None, writer = self.index.writer() writer.delete_by_term(, identifier) writer.commit()
Deletes given identifier from index. Args: identifier (str): identifier of the document to delete.
14,889
def cosine(brands, exemplars, weighted_avg=False, sqrt=False): scores = {} for brand, followers in brands: if weighted_avg: scores[brand] = np.average([_cosine(followers, others) for others in exemplars.values()], weights=[1. / len(others) for othe...
Return the cosine similarity betwee a brand's followers and the exemplars.
14,890
def process_tokens(self, tokens): control_pragmas = {"disable", "enable"} for (tok_type, content, start, _, _) in tokens: if tok_type != tokenize.COMMENT: continue match = OPTION_RGX.search(content) if match is None: continue ...
process tokens from the current module to search for module/block level options
14,891
def get_group_target(self): return Surface._from_pointer( cairo.cairo_get_group_target(self._pointer), incref=True)
Returns the current destination surface for the context. This is either the original target surface as passed to :class:`Context` or the target surface for the current group as started by the most recent call to :meth:`push_group` or :meth:`push_group_with_content`.
14,892
def wsp(word): violations = 0 unstressed = [] for w in extract_words(word): unstressed += w.split()[1::2] if w.count() % 2 == 0: unstressed += [w.rsplit(, 1)[-1], ] for syll in unstressed: if re.search(r, syll, flags=FLAGS): violati...
Return the number of unstressed superheavy syllables.
14,893
def db_downgrade(version): v1 = get_db_version() migrate_api.downgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print else: print % (v1, v2)
Downgrade the database
14,894
def _fixpath(self, p): return os.path.abspath(os.path.expanduser(p))
Apply tilde expansion and absolutization to a path.
14,895
def __select_builder(lxml_builder, libxml2_builder, cmdline_builder): if prefer_xsltproc: return cmdline_builder if not has_libxml2: if has_lxml: return lxml_builder else: return cmdline_builder return libxml2_builder
Selects a builder, based on which Python modules are present.
14,896
def hardmask(self): p = re.compile("a|c|g|t|n") for seq_id in self.fasta_dict.keys(): self.fasta_dict[seq_id] = p.sub("N", self.fasta_dict[seq_id]) return self
Mask all lowercase nucleotides with N's
14,897
def log_request_data_send(self, target_system, target_component, id, ofs, count, force_mavlink1=False): return self.send(self.log_request_data_encode(target_system, target_component, id, ofs, count), force_mavlink1=force_mavlink1)
Request a chunk of a log target_system : System ID (uint8_t) target_component : Component ID (uint8_t) id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) ...
14,898
def jsonRender(self, def_buf): try: ret_dict = SerialBlock() ret_dict[Field.Meter_Address] = self.getMeterAddress() for fld in def_buf: compare_fld = fld.upper() if not "RESERVED" in compare_fld and not "CRC" in compare_fld: ...
Translate the passed serial block into string only JSON. Args: def_buf (SerialBlock): Any :class:`~ekmmeters.SerialBlock` object. Returns: str: JSON rendering of meter record.
14,899
def cleanup(self): keys = self.client.smembers(self.keys_container) for key in keys: entry = self.client.get(key) if entry: entry = pickle.loads(entry) if self._is_expired(entry, self.timeout): self.delete_entry(key)
Cleanup all the expired keys