Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,000
def add_sim_options(p): p.add_option("--distance", default=500, type="int", help="Outer distance between the two ends [default: %default]") p.add_option("--readlen", default=150, type="int", help="Length of the read") p.set_depth(depth=10) p.set_outfile(outfile=Non...
Add options shared by eagle or wgsim.
343,001
def remove_all_for(self, key): if not isinstance(key, _string_type): raise TypeError("Key need to be a string.") for idx in _range(self.__kcount[key]): super(VDFDict, self).__delitem__((idx, key)) self.__omap = list(filter(lambda x: x[1] != key, self.__omap)) ...
Removes all items with the given key
343,002
def find_arg_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> BreakingAndDangerousChanges: old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes: List[BreakingChange] = [] dangerous_changes: List[DangerousChange] = [] for type_name, old_t...
Find argument changes. Given two schemas, returns a list containing descriptions of any breaking or dangerous changes in the new_schema related to arguments (such as removal or change of type of an argument, or a change in an argument's default value).
343,003
def resolve_or_missing(self, key): if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found.
343,004
def find_cell_content(self, lines): cell_end_marker, next_cell_start, self.explicit_eoc = self.find_cell_end(lines) if self.metadata is None: cell_start = 0 self.metadata = {} else: cell_start = 1 source = lines[cell_start:...
Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start
343,005
def similarity_cost(inputs_encoded, targets_encoded): x, y = common_layers.pad_to_same_length(inputs_encoded, targets_encoded) depth = tf.shape(inputs_encoded)[3] x, y = tf.reshape(x, [-1, depth]), tf.reshape(y, [-1, depth]) return rank_loss(x, y)
Loss telling to be more similar to your own targets than to others.
343,006
def enable_notebook(): try: from IPython.core.getipython import get_ipython except ImportError: raise ImportError() ip = get_ipython() f = ip.display_formatter.formatters[] f.for_type(np.ndarray, _array_to_html)
Enable automatic visualization of NumPy arrays in the IPython Notebook.
343,007
def add_packet(self, packet): if not self.meta[]: self.meta[] = flow_tuple(packet) self.meta[] = self.meta[][0] self.meta[] = self.meta[][1] self.meta[] = packet[][] self.meta[] = packet[][] self.meta[] = self.meta[][2] ...
Add a packet to this flow
343,008
def get_clean_conf_dir(): if sys.platform.startswith("win"): current_user = else: current_user = + str(getpass.getuser()) conf_dir = osp.join(str(tempfile.gettempdir()), .format(current_user), SUBFOLDER) return conf_dir
Return the path to a temp clean configuration dir, for tests and safe mode.
343,009
def get_extent(self, filename, locations): f = self.get_file(filename) if len(locations) < 2: raise Exception() start_location, end_location = locations if hasattr(start_location, ): start_location = SourceLocation.from_position(self, f, ...
Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. ...
343,010
def WriteSerializableArray(self, array): if array is None: self.WriteByte(0) else: self.WriteVarInt(len(array)) for item in array: item.Serialize(self)
Write an array of serializable objects to the stream. Args: array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin
343,011
def makeSearchJobParamsDict(cls, options, forRunning=False): if options["searchMethod"] == "v2": hsVersion = "v2" else: raise Exception("Unsupported search method: %r" % options["searchMethod"]) maxModels = options["maxPermutations"] if options["action"] == "dryRun" and maxModels is No...
Constructs a dictionary of HyperSearch parameters suitable for converting to json and passing as the params argument to ClientJobsDAO.jobInsert() Parameters: ---------------------------------------------------------------------- options: NupicRunPermutations options dict forRunning: True ...
343,012
def load_plugins(group=): for ep in pkg_resources.iter_entry_points(group, name=None): plugin = ep.load() if check_hook_mechanism_is_intact(plugin): if check_register_present(plugin): plugin.register() else: log.warning(, plugi...
Load and register installed gcdt plugins.
343,013
def getTempFile(suffix="", rootDir=None): if rootDir is None: handle, tmpFile = tempfile.mkstemp(suffix) os.close(handle) return tmpFile else: tmpFile = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString() + suffix) open(tmpFile, ).close() os.chmod(tm...
Returns a string representing a temporary file, that must be manually deleted
343,014
def create(self, *args, **kwargs): data = self.get_data(, type=POST, params={: self.droplet_id}) if data: self.ip = data[][] self.region = data[][] return self
Creates a FloatingIP and assigns it to a Droplet. Note: Every argument and parameter given to this method will be assigned to the object. Args: droplet_id: int - droplet id
343,015
def arrays(self): return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]
Returns symbol instances corresponding to arrays of the current scope.
343,016
def _setter(self): def set_attr_value(obj, value): if value is None or value == self._default: if self._clark_name in obj.attrib: del obj.attrib[self._clark_name] return str_value = self._simple_type.to_xml(value) o...
Return a function object suitable for the "set" side of the attribute property descriptor.
343,017
def parse_const_argument(lexer: Lexer) -> ArgumentNode: start = lexer.token return ArgumentNode( name=parse_name(lexer), value=expect_token(lexer, TokenKind.COLON) and parse_const_value(lexer), loc=loc(lexer, start), )
Argument[Const]: Name : Value[?Const]
343,018
def allow_any(self, ctx, ops): authed, used = self._allow_any(ctx, ops) return self._new_auth_info(used), authed
like allow except that it will authorize as many of the operations as possible without requiring any to be authorized. If all the operations succeeded, the array will be nil. If any the operations failed, the returned error will be the same that allow would return and each element in th...
343,019
def evaluate(model_path: str, stream_name: str, config_path: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None: config = None try: model_dir = path.dirname(model_path) if not path.isdir(model_path) else model_path config_path = find_config(model_dir if conf...
Evaluate the given model on the specified data stream. Configuration is updated by the respective predict.stream_name section, in particular: - hooks section is entirely replaced - model and dataset sections are updated :param model_path: path to the model to be evaluated :param stream_nam...
343,020
def set_trace(*args, **kwargs): kwargs[] = out debugger = pdb.Pdb(*args, **kwargs) debugger.use_rawinput = True debugger.set_trace(sys._getframe().f_back)
Call pdb.set_trace, making sure it receives the unwrapped stdout. This is so we don't keep drawing progress bars over debugger output.
343,021
def readLocationElement(self, locationElement): loc = Location() for dimensionElement in locationElement.findall(".dimension"): dimName = dimensionElement.attrib.get("name") xValue = yValue = None try: xValue = dimensionElement.attrib.get() ...
Format 0 location reader
343,022
def build_howto(request=None): how_tos = {} for app in settings.INSTALLED_APPS: mod = import_module(app) app_dir = os.path.dirname(mod.__file__) how_to_file = os.path.join(app_dir, ) if os.path.exists(how_to_file): contents = open(how_to_file).read() ...
Searches for "how_to.md" files in app directories. Creates user-friendly admin how-to section from apps that have them.
343,023
def update(self, other): if not isinstance(other, AttrTree): raise Exception() fixed_status = (self.fixed, other.fixed) (self.fixed, other.fixed) = (False, False) for identifier, element in other.items(): if identifier not in self.data: se...
Updated the contents of the current AttrTree with the contents of a second AttrTree.
343,024
def weld_str_slice(array, start=None, stop=None, step=None): obj_id, weld_obj = create_weld_object(array) start = _prepare_slice(start, ) stop = _prepare_slice(stop, ) step = _prepare_slice(step, ) weld_template = weld_obj.weld_code = weld_template.format(array=obj_id, ...
Slice each element. Parameters ---------- array : numpy.ndarray or WeldObject Input data. start : int, optional stop : int, optional step : int, optional Returns ------- WeldObject Representation of this computation.
343,025
def _unpack_content(raw_data, content_type=None): from .pipeline.universal import RawDeserializer context = getattr(raw_data, "context", {}) if context: if RawDeserializer.CONTEXT_NAME in context: return context[RawDeserializer.CON...
Extract the correct structure for deserialization. If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. if we can't, raise. Your Pipeline should have a RawDeserializer. If not a pipeline response and raw_data is bytes or string, use content-type to decode it...
343,026
def configure(level=logging.INFO, logfile=None): for handler in Log.handlers: if isinstance(handler, logging.StreamHandler): Log.handlers.remove(handler) Log.setLevel(level) if logfile is not None: log_format = "[%(asctime)s] [%(levelname)s]: %(message)s" formatter = logging.Formatte...
Configure logger which dumps log on terminal :param level: logging level: info, warning, verbose... :type level: logging level :param logfile: log file name, default to None :type logfile: string :return: None :rtype: None
343,027
def batch_snapshot(self, read_timestamp=None, exact_staleness=None): return BatchSnapshot( self, read_timestamp=read_timestamp, exact_staleness=exact_staleness )
Return an object which wraps a batch read / query. :type read_timestamp: :class:`datetime.datetime` :param read_timestamp: Execute all reads at the given timestamp. :type exact_staleness: :class:`datetime.timedelta` :param exact_staleness: Execute all reads at a timestamp that is ...
343,028
def _build_paths(): paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["include"], "purelib": paths["purelib"], "platlib": paths["platlib"], }
Prepare paths for distlib.wheel.Wheel to install into.
343,029
def constructConditionalPDF( gb, rs: np.ndarray, e: Tuple[str, str, Dict] ) -> gaussian_kde: adjective_response_dict = {} all_θs = [] σ_X = σ_Y = 0.1 for stmt in e[2]["InfluenceStatements"]: for ev in stmt.evidence: if ev.annotations.get(...
Construct a conditional probability density function for a particular AnalysisGraph edge.
343,030
def data_validation(self, in_nc): data_nc = Dataset(in_nc) dims = list(data_nc.dimensions) if dims not in self.dims_oi: data_nc.close() raise Exception("{0} {1}".format(self.error_messages[1], dims)) nc_vars = list(data_nc.variables) ...
Check the necessary dimensions and variables in the input netcdf data
343,031
def get_activity_kudos(self, activity_id, limit=None): result_fetcher = functools.partial(self.protocol.get, , id=activity_id) return BatchedResultsIterator(entity=model.ActivityKudos, ...
Gets the kudos for an activity. http://strava.github.io/api/v3/kudos/#list :param activity_id: The activity for which to fetch kudos. :type activity_id: int :param limit: Max rows to return (default unlimited). :type limit: int :return: An iterator of :class:`stravali...
343,032
def _retrieve_station_history(self, station_ID, limit, interval): params = {: station_ID, : interval, : self._language} if limit is not None: params[] = limit uri = http_client.HttpClient.to_url(STATION_WEATHER_HISTORY_URL, self._A...
Helper method for station_X_history functions.
343,033
def cross_variance(self, x, z, sigmas_f, sigmas_h): Pxz = zeros((sigmas_f.shape[1], sigmas_h.shape[1])) N = sigmas_f.shape[0] for i in range(N): dx = self.residual_x(sigmas_f[i], x) dz = self.residual_z(sigmas_h[i], z) Pxz += self.Wc[i] * outer(dx, d...
Compute cross variance of the state `x` and measurement `z`.
343,034
def _read_mode_pocsp(self, size, kind): temp = self._read_binary(size) data = dict( kind=kind, length=size, start=True if int(temp[0]) else False, end=True if int(temp[1]) else False, filler=bytes(chr(int(temp[2:], base=2)), encoding=...
Read Partial Order Connection Service Profile option. Positional arguments: * size - int, length of option * kind - int, 10 (POC-Serv Profile) Returns: * dict -- extracted Partial Order Connection Service Profile (POC-SP) option Structure of TCP POC-SP Opti...
343,035
def vote(self, request, pk=None): choice = self.get_object() choice.vote() serializer = self.get_serializer(choice) return Response(serializer.data)
post: A description of the post method on the custom action.
343,036
def rotate_secret(self, id): params = {: id } url = self._url( % id) return self.client.get(url, params=params)
Rotate a client secret. The generated secret is NOT base64 encoded. Args: id (str): Client ID of the application. body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Clients/post_rotate_secret
343,037
def _GetNormalizedTimestamp(self): if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = decimal.Decimal(self._timestamp) if self.fraction_of_second is not None: fraction_of_second = decimal.Decimal(self.fraction_of_second) ...
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
343,038
def bel_to_spia_matrices(graph: BELGraph) -> Mapping[str, pd.DataFrame]: index_nodes = get_matrix_index(graph) spia_matrices = build_spia_matrices(index_nodes) for u, v, edge_data in graph.edges(data=True): if isinstance(u, CentralDogma) and isinstance(v, CentralDogma): ...
Create an excel sheet ready to be used in SPIA software. :param graph: BELGraph :return: dictionary with matrices
343,039
def followers(self): from .author import Author, ANONYMOUS self._make_soup() gotten_data_num = 20 data = { : self.xsrf, : , : 0 } while gotten_data_num == 20: res = self._session.post( Topic_Get_More...
获取话题关注者 :return: 话题关注者,返回生成器 :rtype: Author.Iterable
343,040
def RtlGetVersion(os_version_info_struct): rc = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version_info_struct)) if rc != 0: raise OSError("Getting Windows version failed.")
Wraps the lowlevel RtlGetVersion routine. Args: os_version_info_struct: instance of either a RTL_OSVERSIONINFOW structure or a RTL_OSVERSIONINFOEXW structure, ctypes.Structure-wrapped, with the dwOSVersionInfoSize field preset to...
343,041
def _constructor(cls, mapping, configuration): sequence_type, default_factory, pass_key = configuration return cls(default_factory, mapping, sequence_type=sequence_type, pass_key=pass_key)
A standardized constructor.
343,042
def dfilter(self, **kwds): starting_list = self[:] filtered_list = [] for key, value in six.iteritems(kwds): for item in starting_list: if self._match(item, key, value): filtered_list.append(item) starting_list = filtered_list ...
Returns a DictRegister which contains only the elements that match the given specifications.
343,043
def _find_config(self): for search_path in self.config_paths: for ext in self._fmt_to_ext.get(self.config_format): path = os.path.abspath(os.path.join(search_path, self.config_name + ext)) if os.path.isfile(path): self.config_file = path ...
Searches through the configured `config_paths` for the `config_name` file. If there are no `config_paths` defined, this will raise an error, so the caller should take care to check the value of `config_paths` first. Returns: str: The fully qualified path to the configuratio...
343,044
def create_widget(self): d = self.declaration self.widget = RatingBar(self.get_context(), None, d.style or )
Create the underlying widget.
343,045
def ledger(self, ledger_id): endpoint = .format(ledger_id=ledger_id) return self.query(endpoint)
The ledger details endpoint provides information on a single ledger. `GET /ledgers/{sequence} <https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_ :param int ledger_id: The id of the ledger to look up. :return: The details of a single ledger. :...
343,046
def process_job(self, job_request): try: validation_errors = [ Error( code=error.code, message=error.message, field=error.pointer, ) for error in (JobRequestSchema.error...
Validate, execute, and run the job request, wrapping it with any applicable job middleware. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse :raise: JobError
343,047
def get_default_config(self): config = super(SentryHandler, self).get_default_config() config.update({ : , }) return config
Return the default config for the handler
343,048
def call(self, command, *args): if not command: return try: res = self.registered[command][](self, *args) return Response(, res, None) except KeyError: res, err = self.client.call(command, *args) ...
Execute local OR remote command and show response
343,049
def links(self, base_link, current_page) -> dict: max_pages = self.max_pages - 1 if \ self.max_pages > 0 else self.max_pages base_link = % (base_link.strip("/")) self_page = current_page prev = current_page - 1 if current_page is not 0 else None prev_...
Return JSON paginate links
343,050
def algorithm(self): if self._algorithm is None: self._algorithm = self[][].native return self._algorithm
:return: A unicode string of "rsa", "dsa" or "ec"
343,051
def get_data_item_by_uuid(self, data_item_uuid: uuid_module.UUID) -> DataItem: data_item = self._document_model.get_data_item_by_uuid(data_item_uuid) return DataItem(data_item) if data_item else None
Get the data item with the given UUID. .. versionadded:: 1.0 Status: Provisional Scriptable: Yes
343,052
def sys_chdir(self, path): path_str = self.current.read_string(path) logger.debug(f"chdir({path_str})") try: os.chdir(path_str) return 0 except OSError as e: return e.errno
chdir - Change current working directory :param int path: Pointer to path
343,053
def crypto_box_seed_keypair(seed): ensure(isinstance(seed, bytes), "seed must be bytes", raising=TypeError) if len(seed) != crypto_box_SEEDBYTES: raise exc.ValueError("Invalid seed") pk = ffi.new("unsigned char[]", crypto_box_PUBLICKEYBYTES) sk = ffi.new("unsigned ch...
Returns a (public, secret) keypair deterministically generated from an input ``seed``. .. warning:: The seed **must** be high-entropy; therefore, its generator **must** be a cryptographic quality random function like, for example, :func:`~nacl.utils.random`. .. warning:: The seed **must** ...
343,054
def get_minimizer_options(method): if method == : return {: 2, : None, : } elif method == : return {: 200, : 1.0, : 0.5, : 2.0, : 0.5, : 0.1, : True} elif method == : return {: 250, : 100.0, : 1, : 30} elif m...
Return a dictionary with the default options for the given minimization method. Args: method (str): the name of the method we want the options off Returns: dict: a dictionary with the default options
343,055
def generate(bits, progress_func=None): rsa = RSA.generate(bits, os.urandom, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param function progress_func: an optional function to call at key points in key generation (used ...
343,056
def _reform_templatelc_for_tfa(task): try: (lcfile, lcformat, lcformatdir, tcol, mcol, ecol, timebase, interpolate_type, sigclip) = task try: formatinfo = get_lcformat(lcformat, use_lcformat_dir=lcformatdir) if f...
This is a parallel worker that reforms light curves for TFA. task[0] = lcfile task[1] = lcformat task[2] = lcformatdir task[3] = timecol task[4] = magcol task[5] = errcol task[6] = timebase task[7] = interpolate_type task[8] = sigclip
343,057
def optout_saved(sender, instance, **kwargs): if instance.identity is None: identities = Identity.objects.filter_by_addr( instance.address_type, instance.address ) if identities.count() == 1: instance.identity = identities[0]
This is a duplicte of the view code for DRF to stop future internal Django implementations breaking.
343,058
def being(self): try: if self.connection is not None: self.lock() c = self.getCursor() c.execute() c.close() except Exception, e: pass
Being a Transaction @author: Nick Verbeck @since: 5/14/2011
343,059
def diff_analysis(using): python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) return compare_dicts(es_analysis, python_analysis)
Returns a diff string comparing the analysis defined in ES, with the analysis defined in Python land for the connection `using`
343,060
def dump(obj, f, preserve=False): if not f.write: raise TypeError() encoder = Encoder(f, preserve=preserve) return encoder.write_dict(obj)
Write dict object into file :param obj: the object to be dumped into toml :param f: the file object :param preserve: optional flag to preserve the inline table in result
343,061
def spectral(data, lambd, *kwargs): fftdata = np.fft.fftn(data) fftdata[0, 0] = 0 kx = 2 * np.pi * np.fft.fftfreq(data.shape[0]).reshape(1, -1) ky = 2 * np.pi * np.fft.fftfreq(data.shape[1]).reshape(-1, 1) kmax = (2 * np.pi) / (2 * lambd) fftdat...
Compute spectral contrast of image Performs bandpass filtering in Fourier space according to optical limit of detection system, approximated by twice the wavelength. Parameters ---------- data : 2d ndarray the image to compute the norm from lambd : float wavelength of the ligh...
343,062
def set_minmax(field, render_kw=None, force=False): if render_kw is None: render_kw = {} for validator in field.validators: if isinstance(validator, MINMAX_VALIDATORS): if not in render_kw or force: v_min = getattr(validator, , -1) if v_min not i...
Returns *render_kw* with *min* and *max* set if validators use them. Sets *min* and / or *max* keys if a `Length` or `NumberRange` validator is using them. ..note:: This won't change keys already present unless *force* is used.
343,063
def p_ioports(self, p): if isinstance(p[3], str): t = None for r in reversed(p[1]): if isinstance(r.first, Input): t = Ioport(Input(name=p[3], width=r.first.width, lineno=p.lineno(3)), lineno=p.lineno(3)) ...
ioports : ioports COMMA ioport
343,064
def fetch_sorted_metric(self, *args, **kwargs): return sorted(self.fetch_metric(*args, **kwargs).items(), key=lambda x: float(x[0]))
Fetch and sort time series data from OpenTSDB Takes the same parameters as `fetch_metric`, but returns a list of (timestamp, value) tuples sorted by timestamp.
343,065
def _get_integration_function_name(self, method_config): if not isinstance(method_config, dict) or self._INTEGRATION_KEY not in method_config: return None integration = method_config[self._INTEGRATION_KEY] if integration \ and isinstance(integration, dict) ...
Tries to parse the Lambda Function name from the Integration defined in the method configuration. Integration configuration is defined under the special "x-amazon-apigateway-integration" key. We care only about Lambda integrations, which are of type aws_proxy, and ignore the rest. Integration URI is com...
343,066
def get_complete_slug(self, language=None, hideroot=True): if not language: language = settings.PAGE_DEFAULT_LANGUAGE if self._complete_slug and language in self._complete_slug: return self._complete_slug[language] self._complete_slug = cache.get(self.PAGE_URL_...
Return the complete slug of this page by concatenating all parent's slugs. :param language: the wanted slug language.
343,067
def stackscripts(self, *filters, **kwargs): return self.client._get_and_filter(StackScript, *filters)
Returns a list of :any:`StackScripts<StackScript>`, both public and private. You may filter this query to return only :any:`StackScripts<StackScript>` that match certain criteria. You may also request only your own private :any:`StackScripts<StackScript>`:: my_stackscripts = client...
343,068
def nanvl(col1, col2): sc = SparkContext._active_spark_context return Column(sc._jvm.functions.nanvl(_to_java_column(col1), _to_java_column(col2)))
Returns col1 if it is not NaN, or col2 if col1 is NaN. Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`). >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) >>> df.select(nanvl("a", "b").alias("r1"), nanvl(df.a, df.b).alias("r2"))....
343,069
def _handle_tag_defineedittext(self): obj = _make_object("DefineEditText") obj.CharacterID = unpack_ui16(self._src) obj.Bounds = self._get_struct_rect() bc = BitConsumer(self._src) obj.HasText = bc.u_get(1) obj.WordWrap = bc.u_get(1) obj.Multiline = bc.u...
Handle the DefineEditText tag.
343,070
def process_ems(self, doc: Document) -> List[Document]: new_docs = list() for a_em in self.em_lst: if a_em.document_selector(doc): self.log(" processing with " + str(type(a_em)) + ". Process", "info", doc.doc_id, doc.url) fresh_docs = a_em.process_do...
Factory method to wrap input JSON docs in an ETK Document object. Args: doc (Document): process on this document Returns: a Document object and a KnowledgeGraph object
343,071
def _bind_variables(self, instance, space): instance.api = self if space: instance.space = space return instance
Bind related variables to the instance
343,072
def set_full_screen(self, keybind="<Escape>"): self.tk.attributes("-fullscreen", True) self._full_screen = True self.events.set_event("<FullScreen.Escape>", keybind, self.exit_full_screen)
Make this window full screen and bind the Escape key (or given key) to exit full screen mode
343,073
def vector_sum(vector1, vector2, coeff=1.0): summed_vector = [v1 + (coeff * v2) for v1, v2 in zip(vector1, vector2)] return summed_vector
Sums the vectors. This function computes the result of the vector operation :math:`\\overline{v}_{1} + c * \\overline{v}_{2}`, where :math:`\\overline{v}_{1}` is ``vector1``, :math:`\\overline{v}_{2}` is ``vector2`` and :math:`c` is ``coeff``. :param vector1: vector 1 :type vector1: list, tuple :...
343,074
def get_tuple_parameter(self, ast, name): assert ast == for i in range(len(ast)): assert ast[i][0] == node = ast[i][0][0] if (node == and node[0] == ASSIGN_TUPLE_PARAM(name)): del ast[i] ...
If the name of the formal parameter starts with dot, it's a tuple parameter, like this: # def MyFunc(xx, (a,b,c), yy): # print a, b*2, c*42 In byte-code, the whole tuple is assigned to parameter '.1' and then the tuple gets unpacked to 'a', 'b' and 'c'. ...
343,075
def verify_upload(self): if self.request.status_code == 204: return True else: raise TusUploadFailed(, self.request.status_code, self.request.response_content)
Confirm that the last upload was sucessful. Raises TusUploadFailed exception if the upload was not sucessful.
343,076
def pop(self, nbytes): size = 0 popped = [] with self._lock_packets: while size < nbytes: try: packet = self._packets.pop(0) size += len(packet.data.data) self._remaining -= len(packet.data.data) ...
pops packets with _at least_ nbytes of payload
343,077
def split_segment_ids(segment_ids): def split_segment_id(segment_id): temp = segment_id.split() if len(temp) == 2: temp.append(None) elif temp[2] == : temp[2] = None else: temp[2] = int(temp[2]) return temp retur...
Given an array of strings of the form ifo:name and ifo:name:version, returns an array of tuples of the form (ifo, name, version) where version may be None
343,078
def device_slug_to_id(slug): if not isinstance(slug, str): raise ArgumentError("Invalid device slug that is not a string", slug=slug) try: device_slug = IOTileDeviceSlug(slug, allow_64bits=False) except ValueError: raise ArgumentError("Unable to recognize {} as a device id".fo...
Convert a d-- device slug to an integer. Args: slug (str): A slug in the format d--XXXX-XXXX-XXXX-XXXX Returns: int: The device id as an integer Raises: ArgumentError: if there is a malformed slug
343,079
def contains_merged_cell(self): for tc in self.iter_tcs(): if tc.gridSpan > 1: return True if tc.rowSpan > 1: return True if tc.hMerge: return True if tc.vMerge: return True return Fa...
True if one or more cells in range are part of a merged cell.
343,080
def is_endpoint(G, node, strict=True): neighbors = set(list(G.predecessors(node)) + list(G.successors(node))) n = len(neighbors) d = G.degree(node) if node in neighbors: return True elif G.out_degree(node)==0 or G.in_degree(node)==0: return True eli...
Return True if the node is a "real" endpoint of an edge in the network, \ otherwise False. OSM data includes lots of nodes that exist only as points \ to help streets bend around curves. An end point is a node that either: \ 1) is its own neighbor, ie, it self-loops. \ 2) or, has no incoming edges or no...
343,081
def inject_dll(self): self.logger.info() injector_dir = os.path.join(get_dll_directory(), ) for file in [, , , ]: file_path = os.path.join(get_dll_directory(), file) if not os.path.isfile(file_path): raise FileNotFoundError(f ...
Calling this function will inject the DLL without GUI DLL will return status codes from 0 to 5 which correspond to injector_codes DLL injection is only valid if codes are 0->'INJECTION_SUCCESSFUL' or 3->'RLBOT_DLL_ALREADY_INJECTED' It will print the output code and if it's not valid it will kill...
343,082
def get_version(self, cached=True): if hasattr(self.__class__, ) and cached: version = self.__class__._version else: repo = self.get_repo() if repo is not None: head = repo.head version = head.commit.hexsha if r...
Get a git version (i.e. a git commit hash) for this instance.
343,083
def execfile(fname, variables): with open(fname) as f: code = compile(f.read(), fname, ) exec(code, variables)
This is builtin in python2, but we have to roll our own on py3.
343,084
def has_commit(self, client_key=None): if client_key is None and self.current_client is None: raise ClientNotExist() if client_key: if not self.clients.has_client(client_key): raise ClientNotExist() client = self.clients.get_client(client_ke...
Return True if client has new commit. :param client_key: The client key :type client_key: str :return: :rtype: boolean
343,085
def set_defaults(self): rfields, sfields = self.get_write_fields() for f in rfields: self.set_default(f) for f in sfields: self.set_default(f)
Set defaults for fields needed to write the header if they have defaults. Notes ----- - This is NOT called by `rdheader`. It is only automatically called by the gateway `wrsamp` for convenience. - This is also not called by `wrheader` since it is supposed to ...
343,086
def send_to_websocket(self, data): data = json.dumps(data) self.websocket.send(data)
Send (data) directly to the websocket.
343,087
def _one_q_state_prep(oneq_state: _OneQState): label = oneq_state.label if label == : return _one_q_sic_prep(oneq_state.index, oneq_state.qubit) elif label in [, , ]: return _one_q_pauli_prep(label, oneq_state.index, oneq_state.qubit) else: raise ValueError(f"Bad state label...
Prepare a one qubit state. Either SIC[0-3], X[0-1], Y[0-1], or Z[0-1].
343,088
def eps_compare(f1, f2, eps): res = f1 - f2 if abs(res) <= eps: return 0 elif res < 0: return -1 return 1
Return true if |f1-f2| <= eps.
343,089
def get(self, key, mem_map=True): self.raise_error_if_not_open() if key in self._file: data = self._file[key] if not mem_map: data = data[()] return data else: return None
Read and return the data stored for the given key. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in ...
343,090
def add_oauth_header(self): oauth_token = self._get_token() if not oauth_token: return self.headers["Authorization"] = "token " + oauth_token url = self._api_url("user") raw_resp = self.requests.get(url) resp = raw_resp.json() ...
Validate token and add the proper header for further requests. :return: (None)
343,091
def get_student_enrollments(self): resp = self.requester.get( urljoin(self.base_url, self.enrollment_url)) resp.raise_for_status() return Enrollments(resp.json())
Returns an Enrollments object with the user enrollments Returns: Enrollments: object representing the student enrollments
343,092
def create(self, server): for chunk in self.__cut_to_size(): server.post( , chunk.as_payload(), replacements={ : chunk.challenge.slug})
Create the tasks on the server
343,093
def config_cred(config, providers): expected = [, , , ] cred = {} to_remove = [] for item in providers: if any(item.startswith(itemb) for itemb in expected): try: cred[item] = dict(list(config[item].items())) except KeyError as e: prin...
Read credentials from configfile.
343,094
def compare_version(self, version_string, op): from pkg_resources import parse_version from monty.operator import operator_from_str op = operator_from_str(op) return op(parse_version(self.version), parse_version(version_string))
Compare Abinit version to `version_string` with operator `op`
343,095
def command_chars(string, vargs): try: ipa_string = IPAString( unicode_string=string, ignore=vargs["ignore"], single_char_parsing=vargs["single_char_parsing"] ) for c in ipa_string: print(u"\t%s (%s)" % (c.unicode_repr, c.name, unicode_to_...
Print a list of all IPA characters in the given string. It will print the Unicode representation, the full IPA name, and the Unicode "U+"-prefixed hexadecimal codepoint representation of each IPA character. :param str string: the string to act upon :param dict vargs: the command line arguments
343,096
def to_gremlin(self): self.validate() template = ( u u u) field_representations = ( u.format(name=key, expr=self.fields[key].to_gremlin()) for key in sorted(self.fields.keys()) ) return template.format(u.joi...
Return a unicode object with the Gremlin representation of this block.
343,097
def _init_params(self): train_config = self.config["train_config"] if isinstance(train_config["prec_init"], (int, float)): prec_init = train_config["prec_init"] * torch.ones(self.m) else: prec_init = torch.from_numpy...
Initialize the learned params - \mu is the primary learned parameter, where each row corresponds to the probability of a clique C emitting a specific combination of labels, conditioned on different values of Y (for each column); that is: self.mu[i*self.k + j, y] = P(\lambda_i = j |...
343,098
def _set_router_interface(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("router_ve",router_interface.router_interface, yang_name="router-interface", rest_name="router-interface", parent=self, is_container=, user_ordered=False, path_help...
Setter method for router_interface, mapped from YANG variable /bridge_domain/router_interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_router_interface is considered as a private method. Backends looking to populate this variable should do so via calling th...
343,099
def find_root(self): self.find_parents() index = 0 while len(self.vertices[index].parents)>0: index = self.vertices[index].parents[0] return index
Finds the index of the root node of the tree.