Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
367,400
def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None): if target_rest_class is None: adapter_instance = registry.get_adapter_for_persistent_model(persistent_object) else: if inspect.isclass(target_rest_class): target_rest_class = t...
Adapts a single persistent instance to a REST model; at present this is a common method for all persistent backends. Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as for discussion on this feature
367,401
def lag_avgs(self): if not self.interval: return interval = self.interval.mean return dict([(interval/alpha, val) for alpha, val in self.get_expo_avgs().items()])
same data as expo_avgs, but with keys as the average age of the data -- assuming evenly spaced data points -- rather than decay rates
367,402
def temp45(msg): d = hex2bin(data(msg)) sign = int(d[16]) value = bin2int(d[17:26]) if sign: value = value - 512 temp = value * 0.25 temp = round(temp, 1) return temp
Static air temperature. Args: msg (String): 28 bytes hexadecimal message string Returns: float: tmeperature in Celsius degree
367,403
def update(self): stats = self.get_init_value() if self.input_method == : vm_stats = psutil.virtual_memory() ...
Update RAM memory stats using the input method.
367,404
def find(self, pattern): pos = self.current_segment.data.find(pattern) if pos == -1: return -1 return pos + self.current_position
Searches for a pattern in the current memory segment
367,405
def getPassage(self, urn, inventory=None, context=None): return self.call({ "inv": inventory, "urn": urn, "context": context, "request": "GetPassage" })
Retrieve a passage :param urn: URN identifying the text's passage (Minimum depth : 1) :type urn: text :param inventory: Name of the inventory :type inventory: text :param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediat...
367,406
def create_diamond_db(self): my_sequences.dmnd base = self.unaligned_sequence_database_path() cmd = "diamond makedb --in -d " % (self.unaligned_sequence_database_path(), base) extern.run(cmd) diamondb = % base os.rename(diamondb, self.diamond_database_...
Create a diamond database from the unaligned sequences in this package. Returns ------- path to the created diamond db e.g. 'my_sequences.dmnd'
367,407
def _scrollTree( self, value ): if self._scrolling: return tree_bar = self.uiGanttTREE.verticalScrollBar() self._scrolling = True tree_bar.setValue(value) self._scrolling = False
Updates the tree view scrolling to the inputed value. :param value | <int>
367,408
def search(keyword, type=1, offset=0, limit=30): if keyword is None: raise ParamsError() r = NCloudBot() r.method = r.data = { : keyword, : str(limit), : str(type), : str(offset) } r.send() return r.response
搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
367,409
def listFormats(self, vendorSpecific=None): response = self.listFormatsResponse(vendorSpecific) return self._read_dataone_type_response(response, )
See Also: listFormatsResponse() Args: vendorSpecific: Returns:
367,410
def new_qt_console(self, evt=None): return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile)
start a new qtconsole connected to our kernel
367,411
def ensure_dtraj_list(dtrajs): r if isinstance(dtrajs, list): if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i in range(len(dtrajs)): dtrajs[i] = ensure_dtraj(dtrajs[i]) return dtrajs else: return...
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
367,412
def from_ofxparse(data, institution): description = data.desc if hasattr(data, ) else None if data.type == AccountType.Bank: return BankAccount( institution=institution, number=data.account_id, routing_number=data.routing_number, ...
Instantiate :py:class:`ofxclient.Account` subclass from ofxparse module :param data: an ofxparse account :type data: An :py:class:`ofxparse.Account` object :param institution: The parent institution of the account :type institution: :py:class:`ofxclient.Institution` object
367,413
def get_type_data(name): name = name.upper() try: return { : , : , : name, : , : JEFFS_CURRENCY_FORMAT_TYPES[name] + , : JEFFS_CURRENCY_FORMAT_TYPES[name], : ( + JEFFS_CURRENCY_FORMAT_TYP...
Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type
367,414
def to_concat_skip_model(self, start_id, end_id): self.operation_history.append(("to_concat_skip_model", start_id, end_id)) filters_end = self.layer_list[end_id].output.shape[-1] filters_start = self.layer_list[start_id].output.shape[-1] start_node_id = self.layer_id_to_output_n...
Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection.
367,415
def atc(jobid): * atjob_file = .format( job=jobid ) if __salt__[](atjob_file): with salt.utils.files.fopen(atjob_file, ) as rfh: return .join([salt.utils.stringutils.to_unicode(x) for x in rfh.readlines()]) else: return {: {0}\.format(...
Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid>
367,416
def calculate_size(name, service_name): data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(service_name) return data_size
Calculates the request payload size
367,417
def is_credit_card(string, card_type=None): if not is_full_string(string): return False if card_type: if card_type not in CREDIT_CARDS: raise KeyError( .format(card_type, .join(CREDIT_CARDS.keys())) ) return bool(CREDIT_CARDS[card_type].search...
Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card type. :type card_type: str Can be one of these: ...
367,418
def execute_side_effect(side_effect=UNDEFINED, args=UNDEFINED, kwargs=UNDEFINED): if args == UNDEFINED: args = tuple() if kwargs == UNDEFINED: kwargs = {} if isinstance(side_effect, (BaseException, Exception, StandardError)): raise side_effect elif hasattr(side_effect, ):
Executes a side effect if one is defined. :param side_effect: The side effect to execute :type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters. :param tuple args: The arguments passed to the stubbed out method :param dict kwargs: The kwargs passed ...
367,419
def alter(self, operation, timeout=None, metadata=None, credentials=None): new_metadata = self.add_login_metadata(metadata) try: return self.any_client().alter(operation, timeout=timeout, metadata=new_metadata, ...
Runs a modification via this client.
367,420
def set_min_lease(self, min_lease): self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease)
Set the minimum lease period in months. :param min_lease: int
367,421
def run(self): global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects)
function called when thread is started
367,422
def get_time_to_merge_request_response(self, item): review_dates = [str_to_datetime(review[]) for review in item[] if item[][] != review[][]] if review_dates: return min(review_dates) return None
Get the first date at which a review was made on the PR by someone other than the user who created the PR
367,423
def getRnaQuantMetadata(self): rnaQuantId = self.getLocalId() with self._db as dataSource: rnaQuantReturned = dataSource.getRnaQuantificationById( rnaQuantId) self.addRnaQuantMetadata(rnaQuantReturned)
input is tab file with no header. Columns are: Id, annotations, description, name, readGroupId where annotation is a comma separated list
367,424
def initialTrendSmoothingFactors(self, timeSeries): result = 0.0 seasonLength = self.get_parameter("seasonLength") k = min(len(timeSeries) - seasonLength, seasonLength) for i in xrange(0, k): result += (timeSeries[seasonLength + i][1] - timeSeries[i][1]) / seasonLe...
Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0
367,425
def _pretty_size(size): units = [, , , ] while units and size >= 1000: size = size / 1024.0 units.pop() return .format(round(size, 1), units[-1])
Print sizes in a similar fashion as eclean
367,426
def ensure_dirs(filename): dirname, _ = os.path.split(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname)
Make sure the directories exist for `filename`.
367,427
def train_rdp_classifier( training_seqs_file, taxonomy_file, model_output_dir, max_memory=None, tmp_dir=tempfile.gettempdir()): app_kwargs = {} if tmp_dir is not None: app_kwargs[] = tmp_dir app = RdpTrainer(**app_kwargs) if max_memory is not None: app.Parameters[]....
Train RDP Classifier, saving to model_output_dir training_seqs_file, taxonomy_file: file-like objects used to train the RDP Classifier (see RdpTrainer documentation for format of training data) model_output_dir: directory in which to save the files necessary to clas...
367,428
def read_json(self): with reading_ancillary_files(self): metadata = super(GenericLayerMetadata, self).read_json() return metadata
Calls the overridden method. :returns: The read metadata. :rtype: dict
367,429
def _parse_siblings(s, **kw): bracket_level = 0 current = [] for c in (s + ","): if c == "," and bracket_level == 0: yield parse_node("".join(current), **kw) current = [] else: if c == "(": bracket_level += 1 elif c =...
http://stackoverflow.com/a/26809037
367,430
def get_obj_cols(df): obj_cols = [] for idx, dt in enumerate(df.dtypes): if dt == or is_category(dt): obj_cols.append(df.columns.values[idx]) return obj_cols
Returns names of 'object' columns in the DataFrame.
367,431
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None): epmatch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (iv is None or n.iv == iv) and (label is None or n.label == label) and (pred is None or n.pred == pred)) ...
Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matches *label*, and `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* fi...
367,432
def dump(self, config, instance, file_object, prefer=None, **kwargs): file_object.write(self.dumps(config, instance, prefer=prefer, **kwargs))
An abstract method that dumps to a given file object. :param class config: The config class of the instance :param object instance: The instance to dump :param file file_object: The file object to dump to :param str prefer: The preferred serialization module name
367,433
def build_collision_table(aliases, levels=COLLISION_CHECK_LEVEL_DEPTH): collided_alias = defaultdict(list) for alias in aliases: word = alias.split()[0] for level in range(1, levels + 1): collision_regex = r.format(r * (level - 1...
Build the collision table according to the alias configuration file against the entire command table. self.collided_alias is structured as: { 'collided_alias': [the command level at which collision happens] } For example: { 'account': [1, 2] } ...
367,434
def get_all_route_tables(self, route_table_ids=None, filters=None): params = {} if route_table_ids: self.build_list_params(params, route_table_ids, "RouteTableId") if filters: self.build_filter_params(params, dict(filters)) return self.get_list(, params, ...
Retrieve information about your routing tables. You can filter results to return information only about those route tables that match your search parameters. Otherwise, all route tables associated with your account are returned. :type route_table_ids: list :param route_table_ids...
367,435
def trigger_callback(self, sid, namespace, id, data): callback = None try: callback = self.callbacks[sid][namespace][id] except KeyError: self._get_logger().warning() else: del self.callbacks[sid][namespace][id] if callbac...
Invoke an application callback.
367,436
def create_token(user, client, scope, id_token_dic=None): token = Token() token.user = user token.client = client token.access_token = uuid.uuid4().hex if id_token_dic is not None: token.id_token = id_token_dic token.refresh_token = uuid.uuid4().hex token.expires_at = timezone...
Create and populate a Token object. Return a Token object.
367,437
def delete_messages(self, ids): str_ids = self._return_comma_list(ids) return self.request(, {: {: , : str_ids}})
Delete selected messages for the current user :param ids: list of ids
367,438
def set_servo_angle(self, goalangle, goaltime, led): if (self.servomodel==0x06) or (self.servomodel == 0x04): goalposition = scale(goalangle, -159.9, 159.6, 10627, 22129) else: goalposition = scale(goalangle, -150, 150, 21, 1002) self.set_servo_position(goalposi...
Sets the servo angle (in degrees) Enable torque using torque_on function before calling this Args: goalangle (int): The desired angle in degrees, range -150 to 150 goaltime (int): the time taken to move from present position to goalposition led (int): t...
367,439
def validateObjectPath(p): if not p.startswith(): raise MarshallingError() if len(p) > 1 and p[-1] == : raise MarshallingError() if in p: raise MarshallingError() if invalid_obj_path_re.search(p): raise MarshallingError()
Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path
367,440
def fire(self, *args, **kwargs): for token, coro in list(self._connections.items()): keep = yield from coro(*args, **kwargs) if not keep: del self._connections[token]
Emit the signal, calling all coroutines in-line with the given arguments and in the order they were registered. This is obviously a coroutine. Instead of calling :meth:`fire` explicitly, the ad-hoc signal object itself can be called, too.
367,441
def results(self, request): "Match results to given term and return the serialized HttpResponse." results = {} form = self.form(request.GET) if form.is_valid(): options = form.cleaned_data term = options.get(, ) raw_data = self.get_query(request, term)...
Match results to given term and return the serialized HttpResponse.
367,442
def method_selector_fn(self): if callable(self.json_rpc_method): return self.json_rpc_method elif isinstance(self.json_rpc_method, (str,)): return lambda *_: self.json_rpc_method raise ValueError("``json_rpc_method`` config invalid. May be a string or function")
Gets the method selector from the config.
367,443
def _locatedownload(self, remote_path, **kwargs): params = { : remote_path } url = .format(BAIDUPCS_SERVER) return self._request(, , url=url, extra_params=params, **kwargs)
百度云管家获得方式 :param remote_path: 需要下载的文件路径 :type remote_path: str
367,444
def from_descriptions(cls, text, lexicon=None, source=, dlm=, points=False, abbreviations=False, complete=False, order=, ...
Convert a CSV string into a striplog. Expects 2 or 3 fields: top, description OR top, base, description Args: text (str): The input text, given by ``well.other``. lexicon (Lexicon): A lexicon, required to extract components. source (str): ...
367,445
def check_hotkey_unique(self, modifiers, hotKey, newFilterPattern, targetItem): for item in self.allFolders: if model.TriggerMode.HOTKEY in item.modes: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): ret...
Checks that the given hotkey is not already in use. Also checks the special hotkeys configured from the advanced settings dialog. @param modifiers: modifiers for the hotkey @param hotKey: the hotkey to check @param newFilterPattern: @param targetItem: the phrase for whi...
367,446
def insert(self): ret = True schema = self.schema fields = self.depopulate(False) q = self.query q.set_fields(fields) pk = q.insert() if pk: fields = q.fields fields[schema.pk.name] = pk self._populate(fields) ...
persist the field values of this orm
367,447
def get_parser(self, prog_name): parser = argparse.ArgumentParser(description=self.get_description(), prog=prog_name, add_help=False) return parser
Override to add command options.
367,448
def get_parent_repository_ids(self, repository_id): if self._catalog_session is not None: return self._catalog_session.get_parent_catalog_ids(catalog_id=repository_id) return self._hierarchy_session.get_parents(id_=repository_id)
Gets the parent ``Ids`` of the given repository. arg: repository_id (osid.id.Id): a repository ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the repository raise: NotFound - ``repository_id`` is not found raise: NullArgument - ``repository_id`` is ``null`` raise: ...
367,449
def update(self, id, **kwargs): return super(PostController, self).update(id, **self._with_markdown(kwargs))
Updates an existing post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param id: The ID of the existing post :param kwargs: The properties of the post to change :return: The updated `Post` object
367,450
def connect(self, callback, *args, **kwargs): if self.is_connected(callback): raise AttributeError() if self.hard_subscribers is None: self.hard_subscribers = [] self.hard_subscribers.append((callback, args, kwargs))
Connects the event with the given callback. When the signal is emitted, the callback is invoked. .. note:: The signal handler is stored with a hard reference, so you need to make sure to call :class:`disconnect()` if you want the handler to be garbage co...
367,451
def parse_plotPCA(self): self.deeptools_plotPCAData = dict() for f in self.find_log_files(, filehandles=False): parsed_data = self.parsePlotPCAData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotPCAData: log.warning("Re...
Find plotPCA output
367,452
def entry_to_matrix(prodigy_entry): doc = prodigy_entry[] doc = nlp(doc) geo_proced = geo.process_text(doc, require_maj=False) ent_text = np.asarray([gp[] for gp in geo_proced]) match = ent_text == entry[][] anti_match = np.abs(match - 1) match_position = match.arg...
Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating through entities, just get the number of the corr...
367,453
def get_assessment_part_form_for_update(self, assessment_part_id): collection = JSONClientValidated(, collection=, runtime=self._runtime) if not isinstance(assessment_part_id, ABCId): raise errors.Inva...
Gets the assessment part form for updating an existing assessment part. A new assessment part form should be requested for each update transaction. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` return: (osid.assessment.authoring.Assessmen...
367,454
def _athlete_endpoint(self, athlete): return .format( host=self.host, athlete=quote_plus(athlete) )
Construct athlete endpoint from host and athlete name Keyword arguments: athlete -- Full athlete name
367,455
def doesNotMatch(self, value, caseSensitive=True): newq = self.copy() newq.setOp(Query.Op.DoesNotMatch) newq.setValue(value) newq.setCaseSensitive(caseSensitive) return newq
Sets the operator type to Query.Op.DoesNotMatch and sets the \ value to the inputted value. :param value <variant> :return self (useful for chaining) :usage |>>> from orb import Query as Q |>>> query = Q('comments').do...
367,456
def reset(cls): cls.debug = False cls.disabled = False cls.overwrite = False cls.playback_only = False cls.recv_timeout = 5 cls.recv_endmarkers = [] cls.recv_size = None
Reset to default settings
367,457
def InitializeDebuggeeLabels(self, flags): self._debuggee_labels = {} for (label, var_names) in six.iteritems(_DEBUGGEE_LABELS): for name in var_names: value = os.environ.get(name) if value: if label == labels.Debuggee.MODULE and value ==...
Initialize debuggee labels from environment variables and flags. The caller passes all the flags that the the debuglet got. This function will only use the flags used to label the debuggee. Flags take precedence over environment variables. Debuggee description is formatted from available flags. A...
367,458
def network_deconvolution(mat, **kwargs): alpha = kwargs.get(, 1) beta = kwargs.get(, 0.99) control = kwargs.get(, 0) try: assert beta < 1 or beta > 0 assert alpha <= 1 or alpha > 0 except AssertionError: raise ValueError("alpha must be in ]0, 1] and beta in [0, 1...
Python implementation/translation of network deconvolution by MIT-KELLIS LAB. .. note:: code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution) LICENSE: MIT-KELLIS LAB AUTHORS: Algorithm was programmed by Soheil Feizi. Paper authors are S. Feizi,...
367,459
def install(self): domain_settings = DomainSettings.get() with root(): if os.path.exists(self.SMBCONF_FILE): os.remove(self.SMBCONF_FILE) if domain_settings.mode == : domain_settings.adminpass = make_password(15) domain_s...
Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain
367,460
def metablock(parsed): parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",") return escape(strip_tags(decode_entities(parsed)))
Remove HTML tags, entities and superfluous characters from meta blocks.
367,461
def scrollright(self, window_name, object_name): if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException() return self.setmax(window_name, object_name)
Scroll right @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string ...
367,462
def compile_expression(source): _ = coalesce _ = listwrap _ = Date _ = convert _ = Log _ = Data _ = EMPTY_DICT _ = re _ = wrap_leaves _ = is_data fake_locals = {} try: exec( + convert.value2quote(source) + + source + , globals(), ...
THIS FUNCTION IS ON ITS OWN FOR MINIMAL GLOBAL NAMESPACE :param source: PYTHON SOURCE CODE :return: PYTHON FUNCTION
367,463
def eval(self, key, default=None, loc=None, correct_key=True): if correct_key: key = self.corrected_key(key) self[key] = self(key, default, loc) return self[key]
Evaluates and sets the specified option value in environment `loc`. Many options need ``N`` to be defined in `loc`, some need `popsize`. Details ------- Keys that contain 'filename' are not evaluated. For `loc` is None, the self-dict is used as environment :See:...
367,464
def _scale(self, image, width, height): image[][] = % (width, height) image[] = (width, height) return image
Does the resizing of the image
367,465
def _get_destination_paths(self): for dst in self._spec.destinations: for dpath in dst.paths: sdpath = str(dpath) cont, dir = blobxfer.util.explode_azure_path(sdpath) sa = self._creds.get_storage_account( ...
Get destination paths :param Uploader self: this :rtype: tuple :return: (storage account, container, name, dpath)
367,466
def ranges(self, start=None, stop=None): _check_start_stop(start, stop) start_loc = self._bisect_right(start) if stop is None: stop_loc = len(self._keys) else: stop_loc = self._bisect_left(stop) start_val = self._values[start_loc - 1] candidate_keys = [start] + self._keys[start_loc:stop_loc] + [sto...
Generate MappedRanges for all mapped ranges. Yields: MappedRange
367,467
def frombools(cls, bools=()): return cls.fromint(sum(compress(cls._atoms, bools)))
Create a set from an iterable of boolean evaluable items.
367,468
def execute_input_middleware_stream(self, request, controller): start_request = request controller_name = "".join(controller.get_controller_name().split()[:1]) middlewares = list(self.pre_input_middleware) + list(self.input_middleware) for m in middlewares: ...
Request comes from the controller. Returned is a request. controller arg is the name of the controller.
367,469
def tokenProgressFunc(state="update", action=None, text=None, tick=0): print("tokenProgressFunc %s: %s\n%s (%s)"%(state, str(action), str(text), str(tick)))
state: string, "update", "reading sources", "wrapping up" action: string, "stop", "start" text: string, value, additional parameter. For instance ufoname. tick: a float between 0 and 1 indicating progress.
367,470
def set_settings(self, releases=None, default_release=None): super(ShardedClusters, self).set_settings(releases, default_release) ReplicaSets().set_settings(releases, default_release)
set path to storage
367,471
def generation_fluctuating(self): try: return self._generation_fluctuating.loc[[self.timeindex], :] except: return self._generation_fluctuating.loc[self.timeindex, :]
Get generation time series of fluctuating renewables (only active power) Returns ------- :pandas:`pandas.DataFrame<dataframe>` See class definition for details.
367,472
def create_image_summary(name, val): assert isinstance(name, six.string_types), type(name) n, h, w, c = val.shape val = val.astype() s = tf.Summary() imparams = [cv2.IMWRITE_PNG_COMPRESSION, 9] for k in range(n): arr = val[k] if c == 3: arr = cv2.cvtColo...
Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary:
367,473
def _base_repr(self, and_also=None): items = [ "=".join((key, repr(getattr(self, key)))) for key in sorted(self._fields.keys())] if items: output = ", ".join(items) else: output = None if and_also: return "{}({}, {})"...
Common repr logic for subclasses to hook
367,474
def build_arg_parser(): parser = argparse.ArgumentParser(description="Smatch table calculator -- arguments") parser.add_argument("--fl", type=argparse.FileType(), help=) parser.add_argument(, nargs=, help=) parser.add_argument("-p", nargs=, help="User list (can be none)") parser.add_argument("-...
Build an argument parser using argparse. Use it when python version is 2.7 or later.
367,475
def calculate_trip_shape_breakpoints(conn): from gtfspy import shapes cur = conn.cursor() breakpoints_cache = {} FROM trips WHERE trip_I=?SELECT seq, lat, lon, stop_id FROM stop_times LEFT JOIN stops USING (stop_I) W...
Pre-compute the shape points corresponding to each trip's stop. Depends: shapes
367,476
def _decompose(net, wv_map, mems, block_out): def arg(x, i): return wv_map[(net.args[x], i)] def destlen(): return range(len(net.dests[0])) def assign_dest(i, v): wv_map[(net.dests[0], i)] <<= v one_var_ops = { : lambda w: w, : ...
Add the wires and logicnets to block_out and wv_map to decompose net
367,477
def split_flanks(self, _, result): if not result.strip(): self.left, self.right = "", "" return result match = self.flank_re.match(result) assert match, "This regexp should always match" self.left, self.right = match.group(1), match.group(3) retu...
Return `result` without flanking whitespace.
367,478
def update_config(cls, config_file, config): need_save = False if in config and in config[]: del config[][] need_save = True ssh_key = config.get() sshkeys = config.get() if ssh_key and not sshkeys: config.update({:...
Update configuration if needed.
367,479
def _coerceSingleRepetition(self, dataSet): form = LiveForm(lambda **k: None, self.parameters, self.name) return form.fromInputs(dataSet)
Make a new liveform with our parameters, and get it to coerce our data for us.
367,480
def os_details(): bits, linkage = platform.architecture() results = { "platform.arch.bits": bits, "platform.arch.linkage": linkage, "platform.machine": platform.machine(), "platform.process": platform.processor(), ...
Returns a dictionary containing details about the operating system
367,481
def _find_min_start(text, max_width, unicode_aware=True, at_end=False): if 2 * len(text) < max_width: return 0 result = 0 string_len = wcswidth if unicode_aware else len char_len = wcwidth if unicode_aware else lambda x: 1 display_end = string_len(text) while display_end ...
Find the starting point in the string that will reduce it to be less than or equal to the specified width when displayed on screen. :param text: The text to analyze. :param max_width: The required maximum width :param at_end: At the end of the editable line, so allow spaced for cursor. :return: Th...
367,482
def build_command(self, command_name, **kwargs): command_bitvector = bitarray(0, endian=) if command_name not in self.commands: raise ValueError( % command_name) command_object = self.commands[command_name] command_parts = re.split(r, command_object[]) ...
build command from command_name and keyword values Returns ------- command_bitvector : list List of bitarrays. Usage ----- Receives: command name as defined inside xml file, key-value-pairs as defined inside bit stream filed for each command
367,483
def run_ffitch(distfile, outtreefile, intreefile=None, **kwargs): cl = FfitchCommandline(datafile=distfile, outtreefile=outtreefile, \ intreefile=intreefile, **kwargs) r, e = cl.run() if e: print("***ffitch could not run", file=sys.stderr) return None else: prin...
Infer tree branch lengths using ffitch in EMBOSS PHYLIP
367,484
def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray, moderngl.Texture3D, moderngl.TextureCube]: return self._get_resource(label, self._textures, "texture")
Get a texture by label Args: label (str): The label for the texture to fetch Returns: Texture instance
367,485
def receive(organization=None, user=None, team=None, credential_type=None, credential=None, notification_template=None, inventory_script=None, inventory=None, project=None, job_template=None, workflow=None, all=None): from tower_cli.cli.transfer.receive import Receiver receiver = R...
Export assets from Tower. 'tower receive' exports one or more assets from a Tower instance For all of the possible assets types the TEXT can either be the assets name (or username for the case of a user) or the keyword all. Specifying all will export all of the assets of that type.
367,486
def calculate_integral_over_T(self, T1, T2, method): rs `quad` function to perform the integral, with no options. This method can be overwritten by subclasses who may perfer to add analytical methods for some or all methods as this is much faster. If the calculation do...
r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Uses SciPy's `quad` function to perform the integral, with no options. This method can be overwritten by subclasses who may perfer to add analytical method...
367,487
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True): if isinstance(data, unicode): data = data.encode() elif not isinstance(data, basestring): raise ValueError() version = int(version) if level not in levels: raise ValueError() ...
Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version to use. If set to 0, the library picks the smallest version that the data fits in. level...
367,488
def _all_get_or_create_table(self, where, tablename, description, expectedrows=None): where_node = self._hdf5file.get_node(where) if not tablename in where_node: if not expectedrows is None: table = self._hdf5file.create_table(where=where_node, name=tablename, ...
Creates a new table, or if the table already exists, returns it.
367,489
def create(provider, names, opts=None, **kwargs): t1.micro client = _get_client() if isinstance(opts, dict): client.opts.update(opts) info = client.create(provider, names, **kwargs) return info
Create an instance using Salt Cloud CLI Example: .. code-block:: bash salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
367,490
def _tilequeue_rawr_setup(cfg): rawr_yaml = cfg.yml.get() assert rawr_yaml is not None, rawr_postgresql_yaml = rawr_yaml.get() assert rawr_postgresql_yaml, from raw_tiles.formatter.msgpack import Msgpack from raw_tiles.gen import RawrGenerator from raw_tiles.source.conn import Conne...
command to read from rawr queue and generate rawr tiles
367,491
def find_string_ids(self, substring, suffix_tree_id, limit=None): edge, ln = self.find_substring_edge(substring=substring, suffix_tree_id=suffix_tree_id) string_ids = get_string_ids( node_id=edge.dest_node_id, node_repo=self.node_repo, nod...
Returns a set of IDs for strings that contain the given substring.
367,492
def correct(tokens, term_freq): log = [] output = [] for token in tokens: corrected = _correct(token, term_freq) if corrected != token: log.append((token, corrected)) output.append(corrected) return output, log
Correct a list of tokens, according to the term_freq
367,493
def position_after_whitespace(body, start_position): body_length = len(body) position = start_position while position < body_length: code = char_code_at(body, position) if code in ignored_whitespace_characters: position += 1 elif code == 35: posit...
Reads from body starting at start_position until it finds a non-whitespace or commented character, then returns the position of that character for lexing.
367,494
def b_spline_basis(x, edge_knots, n_splines=20, spline_order=3, sparse=True, periodic=True, verbose=True): if np.ravel(x).ndim != 1: raise ValueError(\ .format(np.ravel(x).ndim)) if (n_splines < 1) or not isinstance(n_splines, numbers.Integral): ...
tool to generate b-spline basis using vectorized De Boor recursion the basis functions extrapolate linearly past the end-knots. Parameters ---------- x : array-like, with ndims == 1. edge_knots : array-like contaning locations of the 2 edge knots. n_splines : int. number of splines to generate....
367,495
def _ensure_channel_connected(self, destination_id): if destination_id not in self._open_channels: self._open_channels.append(destination_id) self.send_message( destination_id, NS_CONNECTION, {MESSAGE_TYPE: TYPE_CONNECT, : {}, ...
Ensure we opened a channel to destination_id.
367,496
def _read(self, ti, try_number, metadata=None): if not metadata: metadata = {: 0} if not in metadata: metadata[] = 0 offset = metadata[] log_id = self._render_log_id(ti, try_number) logs = self.es_read(log_id, offset) next_offset = off...
Endpoint for streaming log. :param ti: task instance object :param try_number: try_number of the task instance :param metadata: log metadata, can be used for steaming log reading and auto-tailing. :return: a list of log documents and metadata.
367,497
def remove(args): osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit( ) project = osf.project(args.project) storage, remote_path = split_storage(args.target) store = project.storage(storage) for f in store.files: if norm_remo...
Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used.
367,498
def parse_quantity(string): number, unit = , for char in string: if char.isdigit() or char == : number += char else: unit += char return float(number) * FACTORS.get(unit, 1)
Parse quantity allows to convert the value in the resources spec like: resources: requests: cpu: "100m" memory": "200Mi" limits: memory: "300Mi" :param string: str :return: float
367,499
def print_loop(self, sf, sftag, f=sys.stdout, file_format="nmrstar", tw=3): if file_format == "nmrstar": for field in self[sf][sftag][0]: print(u"{}_{}".format(tw * u" ", field), file=f) print(u"", file=f) for valuesdict ...
Print loop into a file or stdout. :param str sf: Saveframe name. :param str sftag: Saveframe tag, i.e. field name. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `nmrstar` or `json`. :param int tw: Tab width. :return: None ...