Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
375,000
def delPlayer(name): player = getPlayer(name) try: os.remove(player.filename) except IOError: pass try: del getKnownPlayers()[player.name] except: pass return player
forget about a previously defined PlayerRecord setting by deleting its disk file
375,001
def remove_users_from_user_group(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.remove_users_from_user_group_with_http_info(id, **kwargs) else: (data) = self.remove_users_from_user_group_with_http_info(id, **kwargs) return dat...
Remove multiple users from a specific user group # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_users_from_user_group(id, async_req=True) >>> result = ...
375,002
def _delay_call(self): now = time.time() time_since_last = now - self.last_call_time if time_since_last < DELAY_TIME: time.sleep(DELAY_TIME - time_since_last) self.last_call_time = now
Makes sure that web service calls are at least 0.2 seconds apart.
375,003
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec()
Reraise an exception from an exception info tuple.
375,004
def mark_running(self): with self._lock: self._set_state(self._RUNNING, self._PAUSED)
Moves the service to the Running state. Raises if the service is not currently in the Paused state.
375,005
def start_timer(self, duration, func, *args): t = threading.Timer(duration, self._timer_callback, (func, args)) self._timer_callbacks[func] = t t.start() self.log.info("Scheduled call to %s in %ds", func.__name__, duration)
Schedules a function to be called after some period of time. * duration - time in seconds to wait before firing * func - function to be called * args - arguments to pass to the function
375,006
def reset(name): ret = {} client = salt.client.get_local_client(__opts__[]) data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event({: .format(name)}, ) return host = next(six.iterkeys(data)) try: cmd_ret = client.cmd_iter( host, ...
Force power down and restart an existing VM
375,007
def hardware_info(self, mask=0xFFFFFFFF): buf = (ctypes.c_uint32 * 32)() res = self._dll.JLINKARM_GetHWInfo(mask, ctypes.byref(buf)) if res != 0: raise errors.JLinkException(res) return list(buf)
Returns a list of 32 integer values corresponding to the bitfields specifying the power consumption of the target. The values returned by this function only have significance if the J-Link is powering the target. The words, indexed, have the following significance: 0. If ``1`...
375,008
def check_initial_subdomain(cls, subdomain_rec): if subdomain_rec.n != 0: return False if subdomain_rec.independent: return False return True
Verify that a first-ever subdomain record is well-formed. * n must be 0 * the subdomain must not be independent of its domain
375,009
def post_grade(self, grade): message_identifier_id = self.message_identifier_id() operation = lis_result_sourcedid = self.lis_result_sourcedid score = float(grade) if 0 <= score <= 1.0: xml = generate_request_xml( message_identifier_...
Post grade to LTI consumer using XML :param: grade: 0 <= grade <= 1 :return: True if post successful and grade valid :exception: LTIPostMessageException if call failed
375,010
def do_clearrep(self, line): self._split_args(line, 0, 0) self._command_processor.get_session().get_replication_policy().clear() self._print_info_if_verbose("Cleared the replication policy")
clearrep Set the replication policy to default. The default replication policy has no preferred or blocked member nodes, allows replication and sets the preferred number of replicas to 3.
375,011
def notify_init(self): _session_count = len(self._sessions) self._update_session_count(1, _session_count) if _session_count == 1: self._run_queued_callbacks()
run the queed callback for just the first session only
375,012
def stat(self, path): path = self._adjust_cwd(path) self._log(DEBUG, % path) t, msg = self._request(CMD_STAT, path) if t != CMD_ATTRS: raise SFTPError() return SFTPAttributes._from_msg(msg)
Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python's C{stat} structure as returned by C{os.stat}, except that it contains fewer fields. An SFTP server may return as much or as little info as it w...
375,013
def find(wave, dep_var, der=None, inst=1, indep_min=None, indep_max=None): r ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) close_min = np.isclose(min(ret._dep_vector), dep_var, FP_RTOL, FP_ATOL) close_max = np.isclose(max(ret._dep_vector), dep_var, FP_RTOL, FP_ATOL) if ((...
r""" Return the independent variable point associated with a dependent variable point. If the dependent variable point is not in the dependent variable vector the independent variable vector point is obtained by linear interpolation :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` ...
375,014
def index_relations(sender, pid_type, json=None, record=None, index=None, **kwargs): if not json: json = {} pid = PersistentIdentifier.query.filter( PersistentIdentifier.object_uuid == record.id, PersistentIdentifier.pid_type == pid_type, ).one_or_none() ...
Add relations to the indexed record.
375,015
def imap_unordered(requests, stream=True, pool=None, size=2, exception_handler=None): def send(r): return r.send(stream=stream) pool = pool if pool else Pool(size) with contextlib.closing(Pool(size)) as pool: for request in pool.imap_unordered(send, requests): if request....
Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If False, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_...
375,016
def get_uids_from_record(self, record, key): value = record.get(key, None) if value is None: return [] if isinstance(value, basestring): value = value.split(",") return filter(lambda uid: uid, value)
Returns a list of parsed UIDs from a single form field identified by the given key. A form field ending with `_uid` can contain an empty value, a single UID or multiple UIDs separated by a comma. This method parses the UID value and returns a list of non-empty UIDs.
375,017
def is_ready_update(self): size_of_buffer = len(self.training_buffer.update_buffer[]) return size_of_buffer > max(int(self.trainer_parameters[] / self.policy.sequence_length), 1)
Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run
375,018
def get_nodes(self, coord, coords): def get_coord(coord): return coords.get(coord, self.ds.coords.get(coord)) return list(map(get_coord, coord.attrs.get(, ).split()[:2]))
Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates
375,019
def self_consistent_update(u_kn, N_k, f_k): u_kn, N_k, f_k = validate_inputs(u_kn, N_k, f_k) states_with_samples = (N_k > 0) log_denominator_n = logsumexp(f_k[states_with_samples] - u_kn[states_with_samples].T, b=N_k[states_with_samples], axis=1) return -1. * logsumexp(-log_de...
Return an improved guess for the dimensionless free energies Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of samples in ...
375,020
def upsert(self, doc, namespace, timestamp, update_spec=None): index, doc_type = self._index_and_mapping(namespace) doc_id = u(doc.pop("_id")) metadata = { : namespace, : timestamp } action = { : , : inde...
Insert a document into Elasticsearch.
375,021
def main(args): ui = getUI(args) if ui.optionIsSet("test"): unittest.main(argv=[sys.argv[0]]) elif ui.optionIsSet("help"): ui.usage() else: verbose = ui.optionIsSet("verbose") stranded = ui.optionIsSet("stranded") if stranded: sys.stderr.write("Sorry, stranded mo...
main entry point for the GenomicIntIntersection script. :param args: the arguments for this script, as a list of string. Should already have had things like the script name stripped. That is, if there are no args provided, this should be an empty list.
375,022
def record_magic(dct, magic_kind, magic_name, func): if magic_kind == : dct[][magic_name] = dct[][magic_name] = func else: dct[magic_kind][magic_name] = func
Utility function to store a function as a magic of a specific kind. Parameters ---------- dct : dict A dictionary with 'line' and 'cell' subdicts. magic_kind : str Kind of magic to be stored. magic_name : str Key to store the magic as. func : function Callable object ...
375,023
def _to_dict(self): _dict = {} if hasattr(self, ) and self.status is not None: _dict[] = self.status if hasattr(self, ) and self.message is not None: _dict[] = self.message return _dict
Return a json dictionary representing this model.
375,024
def bonds(self): seen = set() for n, m_bond in self._adj.items(): seen.add(n) for m, bond in m_bond.items(): if m not in seen: yield n, m, bond
iterate other all bonds
375,025
def token_of_request( self, method, host, url, qheaders, content_type=None, body=None): parsed_url = urlparse(url) netloc = parsed_url.netloc path = parsed_url.path query = parsed_url.query ...
<Method> <PathWithRawQuery> Host: <Host> Content-Type: <ContentType> [<X-Qiniu-*> Headers] [<Body>] #这里的 <Body> 只有在 <ContentType> 存在且不为 application/octet-stream 时才签进去。
375,026
def _do_multivalued_field_facets(self, results, field_facets): facet_dict = {} for field in field_facets: facet_list = {} if not self._multi_value_field(field): continue for result in results: field_value = getattr(result, fi...
Implements a multivalued field facet on the results. This is implemented using brute force - O(N^2) - because Xapian does not have it implemented yet (see http://trac.xapian.org/ticket/199)
375,027
def maybe_replace_any_if_equal(name, expected, actual): is_equal = expected == actual if not is_equal and Config.replace_any: actual_str = minimize_whitespace(str(actual)) if actual_str and actual_str[0] in {, "Anytyping.Anyt.Any'} if not is_equal: expected_annotation = minimiz...
Return the type given in `expected`. Raise ValueError if `expected` isn't equal to `actual`. If --replace-any is used, the Any type in `actual` is considered equal. The implementation is naively checking if the string representation of `actual` is one of "Any", "typing.Any", or "t.Any". This is done...
375,028
def information_content(values): "Number of bits to represent the probability distribution in values." probabilities = normalize(removeall(0, values)) return sum(-p * log2(p) for p in probabilities)
Number of bits to represent the probability distribution in values.
375,029
def repr(self, changed_widgets=None): if changed_widgets is None: changed_widgets={} local_changed_widgets = {} self._set_updated() return .join((, self.type, , self.innerHTML(local_changed_widgets), , self.type, ))
It is used to automatically represent the object to HTML format packs all the attributes, children and so on. Args: changed_widgets (dict): A dictionary containing a collection of tags that have to be updated. The tag that have to be updated is the key, and the value is its ...
375,030
def _identify(self, dataframe): idx = ~idx return idx
Returns a list of indexes containing only the points that pass the filter. Parameters ---------- dataframe : DataFrame
375,031
def _make_request(self, opener, request, timeout=None): timeout = timeout or self.timeout try: return opener.open(request, timeout=timeout) except HTTPError as err: exc = handle_error(err) exc.__cause__ = None raise exc
Make the API call and return the response. This is separated into it's own function, so we can mock it easily for testing. :param opener: :type opener: :param request: url payload to request :type request: urllib.Request object :param timeout: timeout value or None ...
375,032
def verify_checksum(*lines): for line in lines: checksum = line[68:69] if not checksum.isdigit(): continue checksum = int(checksum) computed = compute_checksum(line) if checksum != computed: complaint = ( ) rai...
Verify the checksum of one or more TLE lines. Raises `ValueError` if any of the lines fails its checksum, and includes the failing line in the error message.
375,033
def processRequest(self, request: Request, frm: str): logger.debug("{} received client request: {} from {}". format(self.name, request, frm)) self.nodeRequestSpikeMonitorData[] += 1
Handle a REQUEST from the client. If the request has already been executed, the node re-sends the reply to the client. Otherwise, the node acknowledges the client request, adds it to its list of client requests, and sends a PROPAGATE to the remaining nodes. :param request: the R...
375,034
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
convert bytes array to unicode string
375,035
def get_base_url(self, force_http=False): base_url = SHConfig().aws_metadata_url.rstrip() if force_http else aws_bucket = SHConfig().aws_s3_l1c_bucket if self.data_source is DataSource.SENTINEL2_L1C else \ SHConfig().aws_s3_l2a_bucket return .format(base_url, aws_bucket)
Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str
375,036
def search(self, start_ts, end_ts): for meta_collection_name in self._meta_collections(): meta_coll = self.meta_database[meta_collection_name] for ts_ns_doc in meta_coll.find( {"_ts": {"$lte": end_ts, "$gte": start_ts}} ): yield ts_ns_...
Called to query Mongo for documents in a time range.
375,037
def postprocess_result(morphresult, trim_phonetic, trim_compound): word, analysis = morphresult return { : deconvert(word), : [postprocess_analysis(a, trim_phonetic, trim_compound) for a in analysis] }
Postprocess vabamorf wrapper output.
375,038
def __create(self, account_id, name, short_description, amount, period, **kwargs): params = { : account_id, : name, : short_description, : amount, : period } return self.make_call(self.__create, params, kwargs)
Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
375,039
def _init_multi_count_metrics(self, pplan_helper): to_in_init = [self.metrics[i] for i in self.inputs_init if i in self.metrics and isinstance(self.metrics[i], MultiCountMetric)] for in_stream in pplan_helper.get_my_bolt().inputs: stream_id = in_stream.stream.id global_st...
Initializes the default values for a necessary set of MultiCountMetrics
375,040
def to_java_doubles(m): global _java if _java is None: _init_registration() m = np.asarray(m) dims = len(m.shape) if dims > 2: raise ValueError() bindat = serialize_numpy(m, ) return (_java.jvm.nben.util.Numpy.double2FromBytes(bindat) if dims == 2 else _java.jvm.nben.util.Nu...
to_java_doubles(m) yields a java array object for the vector or matrix m.
375,041
def unset(entity, *types): if not types: types = (TypedField,) fields = list(entity._fields.keys()) remove = (x for x in fields if isinstance(x, types)) for field in remove: del entity._fields[field]
Unset the TypedFields on the input `entity`. Args: entity: A mixbox.Entity object. *types: A variable-length list of TypedField subclasses. If not provided, defaults to TypedField.
375,042
def monitor_session_span_command_direction(self, **kwargs): config = ET.Element("config") monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span") session = ET.SubElement(monitor, "session") session_number_key = ET.SubElement(session, "session-number...
Auto Generated Code
375,043
def cube(width, height, depth, center=(0.0, 0.0, 0.0), normals=True, uvs=True) -> VAO: width, height, depth = width / 2.0, height / 2.0, depth / 2.0 pos = numpy.array([ center[0] + width, center[1] - height, center[2] + depth, center[0] + width, center[1] + height, center[2] + depth, ...
Creates a cube VAO with normals and texture coordinates Args: width (float): Width of the cube height (float): Height of the cube depth (float): Depth of the cube Keyword Args: center: center of the cube as a 3-component tuple normals: (bool) Include normals uvs...
375,044
def nps_survey_response_show(self, survey_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/nps-api/responses api_path = "/api/v2/nps/surveys/{survey_id}/responses/{id}.json" api_path = api_path.format(survey_id=survey_id, id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/nps-api/responses#show-response
375,045
def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]: if isinstance(expression, (list, tuple)): function_transitions, return_type, argument_types = self._get_function_transitions(expression[0], ...
This is used when converting a logical form into an action sequence. This piece recursively translates a lisp expression into an action sequence, making sure we match the expected type (or using the expected type to get the right type for constant expressions).
375,046
def draw_data_value_rect(cairo_context, color, value_size, name_size, pos, port_side): c = cairo_context rot_angle = .0 move_x = 0. move_y = 0. if port_side is SnappedSide.RIGHT: move_x = pos[0] + name_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0],...
This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label ...
375,047
def from_pb(cls, app_profile_pb, instance): match_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name) if match_app_profile_name is None: raise ValueError( "AppProfile protobuf name was not in the " "expected format.", app_profile_pb.nam...
Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. ...
375,048
def search(self, terms): images = {} response = self._request_builder(, , params={: terms}) if self._validate_response(response): body = json.loads(response.content.decode())[] for image in body: images[image[]] = image return images
returns a dict {"name": "image_dict"}
375,049
def cash_table(self): _cash = pd.DataFrame( data=[self.cash[1::], self.time_index_max], index=[, ] ).T _cash = _cash.assign( date=_cash.datetime.apply(lambda x: pd.to_datetime(str(x)[0:10])) ).assign(accoun...
现金的table
375,050
def drop_curie(self, name): curies = self.o[LINKS_KEY][self.draft.curies_rel] if isinstance(curies, dict) and curies[] == name: del self.o[LINKS_KEY][self.draft.curies_rel] return for i, curie in enumerate(curies): if curie[] == name: ...
Removes a CURIE. The CURIE link with the given name is removed from the document.
375,051
def reconstruct_emds(edm, Om, all_points, method=None, **kwargs): from .point_set import dm_from_edm N = all_points.shape[0] d = all_points.shape[1] dm = dm_from_edm(edm) if method is None: from .mds import superMDS Xhat, __ = superMDS(all_points[0, :], N, d, Om=Om, dm=dm) e...
Reconstruct point set using E(dge)-MDS.
375,052
def get_asn_verbose_dns(self, asn=None): if asn[0:2] != : asn = .format(asn) zone = .format(asn) try: log.debug(.format(zone)) data = self.dns_resolver.query(zone, ) return str(data[0]) except (dns.resolver.NXDOMAIN, dns.reso...
The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`str`): The AS number (required). Returns: str: T...
375,053
def update_domain(self, domain, emailAddress=None, ttl=None, comment=None): if not any((emailAddress, ttl, comment)): raise exc.MissingDNSSettings( "No settings provided to update_domain().") uri = "/domains/%s" % utils.get_id(domain) body = {"comment": c...
Provides a way to modify the following attributes of a domain record: - email address - ttl setting - comment
375,054
def to_triangulation(self): from matplotlib.tri import Triangulation conn = self.split("simplices").unstack() coords = self.nodes.coords.copy() node_map = pd.Series(data = np.arange(len(coords)), index = coords.index) conn = node_map.loc[conn.values.flatten()].values.reshape(*conn.shape) r...
Returns the mesh as a matplotlib.tri.Triangulation instance. (2D only)
375,055
def maybe_cythonize_extensions(top_path, config): is_release = os.path.exists(os.path.join(top_path, )) if is_release: build_from_c_and_cpp_files(config.ext_modules) else: message = ( ).format( CYTHON_MIN_VERSION) try: impor...
Tweaks for building extensions between release and development mode.
375,056
def get_target_extraction_context(self, build_file_path: str) -> dict: extraction_context = {} for name, builder in Plugin.builders.items(): extraction_context[name] = extractor(name, builder, build_file_path, self) return ext...
Return a build file parser target extraction context. The target extraction context is a build-file-specific mapping from builder-name to target extraction function, for every registered builder.
375,057
def getAdaptedTraveltime(self, edgeID, time): self._connection._beginMessage(tc.CMD_GET_EDGE_VARIABLE, tc.VAR_EDGE_TRAVELTIME, edgeID, 1 + 4) self._connection._string += struct.pack( "!Bi", tc.TYPE_INTEGER, time) return self._connection...
getAdaptedTraveltime(string, double) -> double Returns the travel time value (in s) used for (re-)routing which is valid on the edge at the given time.
375,058
def setup_logging(verbosity, filename=None): levels = [logging.WARNING, logging.INFO, logging.DEBUG] level = levels[min(verbosity, len(levels) - 1)] logging.root.setLevel(level) fmt = logging.Formatter( ) hdlr = logging.StreamHandler() hdlr.setFormatter(fmt) ...
Configure logging for this tool.
375,059
def register_intent_parser(self, intent_parser, domain=0): if domain not in self.domains: self.register_domain(domain=domain) self.domains[domain].register_intent_parser( intent_parser=intent_parser)
Register a intent parser with a domain. Args: intent_parser(intent): The intent parser you wish to register. domain(str): a string representing the domain you wish register the intent parser to.
375,060
def device_destroy(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.device_destroy_with_http_info(id, **kwargs) else: (data) = self.device_destroy_with_http_info(id, **kwargs) return data
Delete a device. # noqa: E501 Delete device. Only available for devices with a developer certificate. Attempts to delete a device with a production certicate will return a 400 response. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request,...
375,061
def get(self, wheel=False): try: url = get_url(self.client, self.name, self.version, wheel, hashed_format=True)[0] except exceptions.MissingUrlException as e: raise SystemExit(e) if wheel: self.temp_dir = tempfile.mkdtemp() ...
Downloads the package from PyPI. Returns: Full path of the downloaded file. Raises: PermissionError if the save_dir is not writable.
375,062
def precompute_begin_state(self): begin_state = tuple([ BEGIN ] * self.state_size) choices, weights = zip(*self.model[begin_state].items()) cumdist = list(accumulate(weights)) self.begin_cumdist = cumdist self.begin_choices = choices
Caches the summation calculation and available choices for BEGIN * state_size. Significantly speeds up chain generation on large corpuses. Thanks, @schollz!
375,063
def ndim(self): if self.is_raster(): return { FeatureType.DATA: 4, FeatureType.MASK: 4, FeatureType.SCALAR: 2, FeatureType.LABEL: 2, FeatureType.DATA_TIMELESS: 3, FeatureType.MASK_TIMELESS: 3, ...
If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.
375,064
def get_victoria_day(self, year): may_24th = date(year, 5, 24) shift = may_24th.weekday() or 7 victoria_day = may_24th - timedelta(days=shift) return (victoria_day, "Victoria Day")
Return Victoria Day for Edinburgh. Set to the Monday strictly before May 24th. It means that if May 24th is a Monday, it's shifted to the week before.
375,065
def _event_duration(vevent): if hasattr(vevent, ): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, ) and vevent.duration.value: return vevent.duration.value return timedelta(0)
unify dtend and duration to the duration of the given vevent
375,066
def initialize(self, store): assert isinstance(store, stores.BaseStore) self.messages = Queue() self.store = store self.store.register(self)
Common initialization of handlers happens here. If additional initialization is required, this method must either be called with ``super`` or the child class must assign the ``store`` attribute and register itself with the store.
375,067
def flatten(suitable_for_isinstance): types = set() if not isinstance(suitable_for_isinstance, tuple): suitable_for_isinstance = (suitable_for_isinstance,) for thing in suitable_for_isinstance: if isinstance(thing, tuple): types.update(flatten(thing)) else: ...
isinstance() can accept a bunch of really annoying different types: * a single type * a tuple of types * an arbitrary nested tree of tuples Return a flattened tuple of the given argument.
375,068
def DbPutClassAttributeProperty2(self, argin): self._log.debug("In DbPutClassAttributeProperty2()") class_name = argin[0] nb_attributes = int(argin[1]) self.db.put_class_attribute_property2(class_name, nb_attributes, argin[2:])
This command adds support for array properties compared to the previous one called DbPutClassAttributeProperty. The old comman is still there for compatibility reason :param argin: Str[0] = Tango class name Str[1] = Attribute number Str[2] = Attribute name Str[3] = Property numb...
375,069
def creds_display(creds: dict, filt: dict = None, filt_dflt_incl: bool = False) -> dict: rv = {} if filt is None: filt = {} for cred_uuid in creds.get(, {}): for cred in creds[][cred_uuid]: cred_info = cred[] if cred_info[] in rv: continue ...
Find indy-sdk creds matching input filter from within input creds structure, json-loaded as returned via HolderProver.get_creds(), and return human-legible summary. :param creds: creds structure returned by HolderProver.get_creds(); e.g., :: { "attrs": { "attr0_uuid": ...
375,070
def get_averaged_bias_matrix(bias_sequences, dtrajs, nstates=None): r from pyemma.thermo.extensions.util import (logsumexp as _logsumexp, logsumexp_pair as _logsumexp_pair) nmax = int(_np.max([dtraj.max() for dtraj in dtrajs])) if nstates is None: nstates = nmax + 1 elif nstates < nmax + 1:...
r""" Computes a bias matrix via an exponential average of the observed frame wise bias energies. Parameters ---------- bias_sequences : list of numpy.ndarray(T_i, num_therm_states) A single reduced bias energy trajectory or a list of reduced bias energy trajectories. For every simulatio...
375,071
def download_apcor(self, uri): local_file = os.path.basename(uri) if os.access(local_file, os.F_OK): fobj = open(local_file) else: fobj = storage.vofile(uri, view=) fobj.seek(0) str = fobj.read() fobj.close() apcor_str = str ...
Downloads apcor data. Args: uri: The URI of the apcor data file. Returns: apcor: ossos.downloads.core.ApcorData
375,072
def iterate_analogy_datasets(args): for dataset_name in args.analogy_datasets: parameters = nlp.data.list_datasets(dataset_name) for key_values in itertools.product(*parameters.values()): kwargs = dict(zip(parameters.keys(), key_values)) yield dataset_name, kwargs, nlp.d...
Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
375,073
def _get_role(rolename): path = os.path.join(, rolename + ) if not os.path.exists(path): abort("Couldnrfullname'] = rolename return role
Reads and parses a file containing a role
375,074
def _symmetrize_correlograms(correlograms): n_clusters, _, n_bins = correlograms.shape assert n_clusters == _ correlograms[..., 0] = np.maximum(correlograms[..., 0], correlograms[..., 0].T) sym = correlograms[..., 1:][..., ::-1] sym = np.t...
Return the symmetrized version of the CCG arrays.
375,075
def get_status_badge(self, project, definition, branch_name=None, stage_name=None, job_name=None, configuration=None, label=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if definition is not None: route_values[...
GetStatusBadge. [Preview API] <p>Gets the build status for a definition, optionally scoped to a specific branch, stage, job, and configuration.</p> <p>If there are more than one, then it is required to pass in a stageName value when specifying a jobName, and the same rule then applies for both if passing a conf...
375,076
def enable_service_freshness_checks(self): if not self.my_conf.check_service_freshness: self.my_conf.modified_attributes |= \ DICT_MODATTR["MODATTR_FRESHNESS_CHECKS_ENABLED"].value self.my_conf.check_service_freshness = True self.my_conf.explode_globa...
Enable service freshness checks (globally) Format of the line that triggers function call:: ENABLE_SERVICE_FRESHNESS_CHECKS :return: None
375,077
def detect_with_url( self, url, return_face_id=True, return_face_landmarks=False, return_face_attributes=None, recognition_model="recognition_01", return_recognition_model=False, custom_headers=None, raw=False, **operation_config): image_url = models.ImageUrl(url=url) url ...
Detect human faces in an image, return face rectangles, and optionally with faceIds, landmarks, and attributes.<br /> * Optional parameters including faceId, landmarks, and attributes. Attributes include age, gender, headPose, smile, facialHair, glasses, emotion, hair, makeup, occlusion,...
375,078
def fnmatch_multiple(candidates, pattern): try: candidates_iter = iter(candidates) except TypeError: return None for candidate in candidates_iter: try: if fnmatch.fnmatch(candidate, pattern): return candidate except TypeError: ...
Convenience function which runs fnmatch.fnmatch() on each element of passed iterable. The first matching candidate is returned, or None if there is no matching candidate.
375,079
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r, clean_lines.lines[linenum]) if matched:
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number ...
375,080
def visit_and_update_expressions(self, visitor_fn): new_fields = {} for key, value in six.iteritems(self.fields): new_value = value.visit_and_update(visitor_fn) if new_value is not value: new_fields[key] = new_value if new_fields: re...
Create an updated version (if needed) of the ConstructResult via the visitor pattern.
375,081
def count_emails(self, conditions={}): url = self.EMAILS_COUNT_URL + "?" for key, value in conditions.items(): if key is : value = ",".join(value) url += % (key, value) connection = Connection(self.token) connection.set_url(self.produc...
Count all certified emails
375,082
def autofix_codeblock(codeblock, max_line_len=80, aggressive=False, very_aggressive=False, experimental=False): r import autopep8 arglist = [, ] if aggressive: arglist.extend([]) if very_aggressive: arglist.e...
r""" Uses autopep8 to format a block of code Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> codeblock = ut.codeblock( ''' def func( with , some = 'Problems' ): syntax ='Ok' but = 'Its very messy' if None: ...
375,083
def samples(dataset=, index=0, batchsize=1, shape=(224, 224), data_format=): from PIL import Image images, labels = [], [] basepath = os.path.dirname(__file__) samplepath = os.path.join(basepath, ) files = os.listdir(samplepath) for idx in range(index, index + batchsize): ...
Returns a batch of example images and the corresponding labels Parameters ---------- dataset : string The data set to load (options: imagenet, mnist, cifar10, cifar100, fashionMNIST) index : int For each data set 20 example images exist. The returned batch contains the i...
375,084
def _routes_updated(self, ri): new_routes = ri.router[] old_routes = ri.routes adds, removes = bc.common_utils.diff_list_of_dict(old_routes, new_routes) for route in adds: LOG.debug("Added route entry is ", route...
Update the state of routes in the router. Compares the current routes with the (configured) existing routes and detect what was removed or added. Then configure the logical router in the hosting device accordingly. :param ri: RouterInfo corresponding to the router. :return: None...
375,085
def check_len_in(self, min_len, max_len, item): if max_len is None: if min_len: self.add_check("_coconut.len(" + item + ") >= " + str(min_len)) elif min_len == max_len: self.add_check("_coconut.len(" + item + ") == " + str(min_len)) elif not min_l...
Checks that the length of item is in range(min_len, max_len+1).
375,086
def __densify_border(self): if isinstance(self._input_geom, MultiPolygon): polygons = [polygon for polygon in self._input_geom] else: polygons = [self._input_geom] points = [] for polygon in polygons: if len(polygon.interiors) == 0: ...
Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list: a list of points where each point is represente...
375,087
def as_float_array(a): return np.asarray(a, dtype=np.quaternion).view((np.double, 4))
View the quaternion array as an array of floats This function is fast (of order 1 microsecond) because no data is copied; the returned quantity is just a "view" of the original. The output view has one more dimension (of size 4) than the input array, but is otherwise the same shape.
375,088
def update(self, name=None, description=None, privacy_policy=None, subscription_policy=None, is_managed=None): with db.session.begin_nested(): if name is not None: self.name = name if description is not None: self.description = desc...
Update group. :param name: Name of group. :param description: Description of group. :param privacy_policy: PrivacyPolicy :param subscription_policy: SubscriptionPolicy :returns: Updated group
375,089
def record_to_fs(self): fr = self.record fn_path = self.file_name if fr.contents: if six.PY2: with self._fs.open(fn_path, ) as f: self.record_to_fh(f) else: with self._fs.open(fn_path, , newl...
Create a filesystem file from a File
375,090
def get_alpha_value(self): if isinstance(self.__alpha_value, float) is False: raise TypeError("The type of __alpha_value must be float.") return self.__alpha_value
getter Learning rate.
375,091
def IsDesktopLocked() -> bool: isLocked = False desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p(), 0, 0, 0x0100) if desk: isLocked = not ctypes.windll.user32.SwitchDesktop(desk) ctypes.windll.user32.CloseDesktop(desk) return isLocked
Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.
375,092
def post(self): self._construct_post_data() post_args = {"json": self.post_data} self.http_method_args.update(post_args) return self.http_method("POST")
Makes the HTTP POST to the url sending post_data.
375,093
def zone_compare(timezone): *America/Denver if in __grains__[] or in __grains__[]: return timezone == get_zone() if in __grains__[]: if not os.path.isfile(_get_localtime_path()): return timezone == get_zone() tzfile = _get_localtime_path() zonepath = _get_zone_file(t...
Compares the given timezone name with the system timezone name. Checks the hash sum between the given timezone, and the one set in /etc/localtime. Returns True if names and hash sums match, and False if not. Mostly useful for running state checks. .. versionchanged:: 2016.3.0 .. note:: On...
375,094
def job_exists(name=None): * if not name: raise SaltInvocationError(name\) server = _connect() if server.job_exists(name): return True else: return False
Check whether the job exists in configured Jenkins jobs. :param name: The name of the job is check if it exists. :return: True if job exists, False if job does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.job_exists jobname
375,095
def record_schemas( fn, wrapper, location, request_schema=None, response_schema=None): has_acceptable = hasattr(fn, ) if request_schema is not None: wrapper._request_schema = wrapper._request_schema = request_schema wrapper._request_schema_location = location ...
Support extracting the schema from the decorated function.
375,096
def get(self, request, format=None): bots = Bot.objects.filter(owner=request.user) serializer = BotSerializer(bots, many=True) return Response(serializer.data)
Get list of bots --- serializer: BotSerializer responseMessages: - code: 401 message: Not authenticated
375,097
def patch_conf(settings_patch=None, settings_file=None): if settings_patch is None: settings_patch = {} reload_config() os.environ[ENVIRONMENT_VARIABLE] = settings_file if settings_file else from bernard.conf import settings as l_settings r_settings = l_settings._settings r...
Reload the configuration form scratch. Only the default config is loaded, not the environment-specified config. Then the specified patch is applied. This is for unit tests only! :param settings_patch: Custom configuration values to insert :param settings_file: Custom settings file to read
375,098
def param_title(param_values, slug): for val in param_values: if val.param.slug == slug: return val.param.title return None
Отображает наименование параметра товара Пример использования:: {% param_title item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return:
375,099
def cluster_elongate(): "Not so applicable for this sample" start_centers = [[1.0, 4.5], [3.1, 2.7]] template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION) template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criter...
Not so applicable for this sample