Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
11,500
def get_field_def( schema: GraphQLSchema, parent_type: GraphQLType, field_node: FieldNode ) -> Optional[GraphQLField]: name = field_node.name.value if name == "__schema" and schema.query_type is parent_type: return SchemaMetaFieldDef if name == "__type" and schema.query_type is parent_type:...
Get field definition. Not exactly the same as the executor's definition of `get_field_def()`, in this statically evaluated environment we do not always have an Object type, and need to handle Interface and Union types.
11,501
def update(self, feedforwardInputI, feedforwardInputE, v, recurrent=True, envelope=False, iSpeedTuning=False, enforceDale=True): self.instantaneousI.fill(0) self.instantaneousEL.fill(0) self.instantaneousER.fill(0) self.instantaneousI += feedforwardInputI self.instantaneousEL += ...
Do one update of the CAN network, of length self.dt. :param feedforwardInputI: The feedforward input to inhibitory cells. :param feedforwardInputR: The feedforward input to excitatory cells. :param v: The current velocity. :param recurrent: Whether or not recurrent connections should be used. :param...
11,502
def cat_top_keywords(self, session, cat, up=True, offset=0, offsets=[]): print %(str(cat), str(cat.level)) print %offset response = [] if not offsets or offset==0: url = %(cat.parent.cid, if cat.level==2 else str(cat.cid), if up else , offset) print u...
Get top keywords in a specific category
11,503
def add_namespaces(spec_dict): for ns in spec_dict["namespaces"]: spec_dict["namespaces"][ns]["list"] = [] spec_dict["namespaces"][ns]["list_long"] = [] spec_dict["namespaces"][ns]["list_short"] = [] spec_dict["namespaces"][ns]["to_short"] = {} spec_dict["namespaces"][...
Add namespace convenience keys, list, list_{short|long}, to_{short|long}
11,504
def parse_info_frags(info_frags): new_scaffolds = {} with open(info_frags, "r") as info_frags_handle: current_new_contig = None for line in info_frags_handle: if line.startswith(">"): current_new_contig = str(line[1:-1]) new_scaffolds[current_new...
Import an info_frags.txt file and return a dictionary where each key is a newly formed scaffold and each value is the list of bins and their origin on the initial scaffolding.
11,505
def __connect(self): self.__methods = _get_methods_by_uri(self.sqluri) uri_connect_method = self.__methods[METHOD_CONNECT] self.__dbapi2_conn = uri_connect_method(self.sqluri)
Connect to the database.
11,506
def assign(self, object_type, object_uuid, overwrite=False): if self.is_deleted(): raise PIDInvalidAction( "You cannot assign objects to a deleted/redirected persistent" " identifier." ) if not isinstance(object_uuid, uuid.UUID): ...
Assign this persistent identifier to a given object. Note, the persistent identifier must first have been reserved. Also, if an existing object is already assigned to the pid, it will raise an exception unless overwrite=True. :param object_type: The object type is a string that identif...
11,507
def _placement_points_generator(self, skyline, width): skyline_r = skyline[-1].right skyline_l = skyline[0].left ppointsl = (s.left for s in skyline if s.left+width <= skyline_r) ppointsr = (s.right-width for s in skyline if s.right-width >= skyline_l) ...
Returns a generator for the x coordinates of all the placement points on the skyline for a given rectangle. WARNING: In some cases could be duplicated points, but it is faster to compute them twice than to remove them. Arguments: skyline (list): Skyline HSegment lis...
11,508
def main(): parser = __build_option_parser() args = parser.parse_args() analyze_ws = AnalyzeWS(args) try: analyze_ws.set_file(args.file_[0]) except IOError: print sys.exit(3) if args.to_file or args.to_browser: analyze_ws.to_file_mode() if args...
Main method of the script
11,509
def add_segy_view_widget(self, ind, widget, name=None): if self._context is None: self._segywidgets.append(widget) self.initialize() return 0 self._tab_widget.updatesEnabled = False widget.show_toolbar(toolbar=True, layout_combo=False, colormap=Tru...
:param widget: The SegyViewWidget that will be added to the SegyTabWidget :type widget: SegyViewWidget
11,510
def update(self, dict): for field in self.sorted_fields(): if field in dict: if dict[field] is None: delattr(self, field) else: setattr(self, field, dict[field])
Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted from the `MediaFile`.
11,511
def expand_to_vector(x, tensor_name=None, op_name=None, validate_args=False): with tf.name_scope(op_name or "expand_to_vector"): x = tf.convert_to_tensor(value=x, name="x") ndims = tensorshape_util.rank(x.shape) if ndims is None: if validate_args: x = with_dependencies([ ...
Transform a 0-D or 1-D `Tensor` to be 1-D. For user convenience, many parts of the TensorFlow Probability API accept inputs of rank 0 or 1 -- i.e., allowing an `event_shape` of `[5]` to be passed to the API as either `5` or `[5]`. This function can be used to transform such an argument to always be 1-D. NO...
11,512
def default_user_agent(name="python-requests"): _implementation = platform.python_implementation() if _implementation == : _implementation_version = platform.python_version() elif _implementation == : _implementation_version = % (sys.pypy_version_info.major, ...
Return a string representing the default user agent.
11,513
def _remove_none_values(dictionary): return list(map(dictionary.pop, [i for i in dictionary if dictionary[i] is None]))
Remove dictionary keys whose value is None
11,514
def clone(self, fp): return self.__class__(fp, self._mangle_from_, None, policy=self.policy)
Clone this generator with the exact same options.
11,515
def check_type(self, value, attr, data): root_value = super(InstructionParameter, self).check_type( value, attr, data) if is_collection(value): _ = [super(InstructionParameter, self).check_type(item, attr, data) for item in value] ...
Customize check_type for handling containers.
11,516
def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True): util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Extracting %s ..." % archive) return _extract_archive(archive, verbosity=verbosity, interactive=interactive, outdir=outdir, program=pro...
Extract given archive.
11,517
def add_sibling(self, pos=None, **kwargs): pos = self._prepare_pos_var_for_add_sibling(pos) if len(kwargs) == 1 and in kwargs: newobj = kwargs[] if newobj.pk: raise NodeAlreadySaved("Attempted to add a tree node that is "\ ...
Adds a new node as a sibling to the current node object.
11,518
def _get_mean(self, sites, C, ln_y_ref, exp1, exp2, v1): z1pt0 = sites.z1pt0 eta = epsilon = 0 ln_y = ( ln_y_ref + C[] * np.log(np.clip(sites.vs30, -np.inf, v1) / 1130) + C[] * (exp1 - ex...
Add site effects to an intensity. Implements eq. 5
11,519
def create_payload(self): payload = super(OverrideValue, self).create_payload() if hasattr(self, ): del payload[] if hasattr(self, ): del payload[] return payload
Remove ``smart_class_parameter_id`` or ``smart_variable_id``
11,520
def get_config_values(config_path, section, default=): values = {} if not os.path.isfile(config_path): raise IpaUtilsException( % config_path ) config = configparser.ConfigParser() try: config.read(config_path) except Exception: raise IpaUtilsExce...
Parse ini config file and return a dict of values. The provided section overrides any values in default section.
11,521
def from_center(self, x=None, y=None, z=None, r=None, theta=None, h=None, reference=None): coords_to_endpoint = None if all([isinstance(i, numbers.Number) for i in (x, y, z)]): coords_to_endpoint = self.from_cartesian(x, y, z) if all([isinstance(i, numbe...
Accepts a set of (:x:, :y:, :z:) ratios for Cartesian or (:r:, :theta:, :h:) rations/angle for Polar and returns :Vector: using :reference: as origin
11,522
def motif4struct_wei(W): from scipy import io import os fname = os.path.join(os.path.dirname(__file__), motiflib) mot = io.loadmat(fname) m4 = mot[] m4n = mot[] id4 = mot[].squeeze() n4 = mot[].squeeze() n = len(W) I = np.zeros((199, n)) Q = np.zeros((199, n)) F...
Structural motifs are patterns of local connectivity. Motif frequency is the frequency of occurrence of motifs around a node. Motif intensity and coherence are weighted generalizations of motif frequency. Parameters ---------- W : NxN np.ndarray weighted directed connection matrix (all weig...
11,523
def _select_options(self, options, keys, invert=False): options = self._merge_options(options) result = {} for key in options: if (invert and key not in keys) or (not invert and key in keys): result[key] = options[key] return result
Select the provided keys out of an options object. Selects the provided keys (or everything except the provided keys) out of an options object.
11,524
def assert_array(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r try: if shape is not None: if not np.array_equal(np.shape(A), shape): raise AssertionError(+str(shape)++str(np.shape(A))) if uniform is not None: shapearr = np.ar...
r""" Asserts whether the given array or sparse matrix has the given properties Parameters ---------- A : ndarray, scipy.sparse matrix or array-like the array under investigation shape : shape, optional, default=None asserts if the array has the requested shape. Be careful with vectors ...
11,525
def cluster(list_of_texts, num_clusters=3): pipeline = Pipeline([ ("vect", CountVectorizer()), ("tfidf", TfidfTransformer()), ("clust", KMeans(n_clusters=num_clusters)) ]) try: clusters = pipeline.fit_predict(list_of_texts) except ValueError: clusters = list...
Cluster a list of texts into a predefined number of clusters. :param list_of_texts: a list of untokenized texts :param num_clusters: the predefined number of clusters :return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1]
11,526
def matches_query(self, key, query): dumped = query.dump() dumped[] = query._query_class._class_name self._add_condition(key, , dumped) return self
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果相同。 :param key: 查询条件字段名 :param query: 查询对象 :type query: Query :rtype: Query
11,527
def __extract_modules(self, loader, name, is_pkg): mod = loader.find_module(name).load_module(name) if hasattr(mod, ): module_router = ModuleRouter(mod, ignore_names=self.__serialize_module_paths() ...
if module found load module and save all attributes in the module found
11,528
def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False): cached_wheels_dir = os.path.join(tempfile.gettempdir(), ) if not os.path.isdir(cached_wheels_dir): os.makedirs(cached_wheels_dir) wheel_file = .format(package_name, package_version,...
Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it.
11,529
def get_pose_error(target_pose, current_pose): error = np.zeros(6) target_pos = target_pose[:3, 3] current_pos = current_pose[:3, 3] pos_err = target_pos - current_pos r1 = current_pose[:3, 0] r2 = current_pose[:3, 1] r3 = current_pose[:3, 2] r1d = target_pose[:3, 0] ...
Computes the error corresponding to target pose - current pose as a 6-dim vector. The first 3 components correspond to translational error while the last 3 components correspond to the rotational error. Args: target_pose: a 4x4 homogenous matrix for the target pose current_pose: a 4x4 homog...
11,530
def scan(self, restrict): while True: best_pat = None best_pat_len = 0 for p, regexp in self.patterns: if best_pat is None: msg = "Bad Token" if restrict: ...
Should scan another token and add it to the list, self.tokens, and add the restriction to self.restrictions
11,531
def delete(cls, bucket_id): bucket = cls.get(bucket_id) if not bucket or bucket.deleted: return False bucket.deleted = True return True
Delete a bucket. Does not actually delete the Bucket, just marks it as deleted.
11,532
def default_package(self): packages = [pk for pk in self.packages() if pk.get() == ] if packages: return packages[0] else: return None
:: GET /:login/packages :Returns: the default package for this datacenter :rtype: :py:class:`dict` or ``None`` Requests all the packages in this datacenter, filters for the default, and returns the corresponding dict, if a default has been defined.
11,533
def count_above_mean(x): m = np.mean(x) return np.where(x > m)[0].size
Returns the number of values in x that are higher than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
11,534
def _set_config_path(self): self._path = os.getenv("CLOEEPY_CONFIG_PATH") if self._path is None: msg = "CLOEEPY_CONFIG_PATH is not set. Exiting..." sys.exit(msg)
Reads config path from environment variable CLOEEPY_CONFIG_PATH and sets as instance attr
11,535
def bbin(obj: Union[str, Element]) -> str: return obj.name if isinstance(obj, Element ) else f if obj in builtin_names else obj
Boldify built in types @param obj: object name or id @return:
11,536
def add_menu(self, menu): self._menus.append(menu) self._menus = sorted(list(set(self._menus)), key=lambda x: x.title()) for action in menu.actions(): action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addActions(menu.actions())
Adds a sub-menu to the editor context menu. Menu are put at the bottom of the context menu. .. note:: to add a menu in the middle of the context menu, you can always add its menuAction(). :param menu: menu to add
11,537
def prepare(args): p = OptionParser(prepare.__doc__ + FastqNamings) p.add_option("-K", default=51, type="int", help="K-mer size") p.set_cpus(cpus=32) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) genomesize = float(args[0]) / 1000 fnames = args...
%prog prepare genomesize *.fastq Prepare MERACULOUS configuation file. Genome size should be entered in Mb.
11,538
def remove(self, module=True, force=False, configuration=True, dry_run=False): if not (module or configuration): raise ValueError("Need to specify to delete at least the module, or the configuration") nc = 0 for csm in self.children(): nc += 1 ...
Remove this submodule from the repository. This will remove our entry from the .gitmodules file and the entry in the .git/config file. :param module: If True, the module checkout we point to will be deleted as well. If the module is currently on a commit which is not part of any...
11,539
def _isdst(dt): if type(dt) == datetime.date: dt = datetime.datetime.combine(dt, datetime.datetime.min.time()) dtc = dt.replace(year=datetime.datetime.now().year) if time.localtime(dtc.timestamp()).tm_isdst == 1: return True return False
Check if date is in dst.
11,540
def _connect(self): def tryConnect(): self.connector = d = maybeDeferred(connect) d.addCallback(cbConnect) d.addErrback(ebConnect) def connect(): endpoint = self._endpointFactory(self._reactor, self.host, self.port) log.debug(, self, ...
Connect to the Kafka Broker This routine will repeatedly try to connect to the broker (with backoff according to the retry policy) until it succeeds.
11,541
def send(self, pkt): iff = pkt.route()[0] if iff is None: iff = conf.iface if self.assigned_interface != iff: try: fcntl.ioctl(self.outs, BIOCSETIF, struct.pack("16s16x", iff.encode())) except IOError: ...
Send a packet
11,542
def _claim(cls, cdata: Any) -> "Tileset": self = object.__new__(cls) if cdata == ffi.NULL: raise RuntimeError("Tileset initialized with nullptr.") self._tileset_p = ffi.gc(cdata, lib.TCOD_tileset_delete) return self
Return a new Tileset that owns the provided TCOD_Tileset* object.
11,543
def _parse_triggered_hits(self, file_obj): for _ in range(self.n_triggered_hits): dom_id, pmt_id = unpack(, file_obj.read(5)) tdc_time = unpack(, file_obj.read(4))[0] tot = unpack(, file_obj.read(1))[0] trigger_mask = unpack(, file_obj.read(8)) ...
Parse and store triggered hits.
11,544
def __fetch(self, url, payload): r = requests.get(url, params=payload, auth=self.auth, verify=self.verify) try: r.raise_for_status() except requests.exceptions.HTTPError as e: raise e return r
Fetch requests from groupsio API
11,545
def getMaxStmIdForStm(stm): maxId = 0 if isinstance(stm, Assignment): return stm._instId elif isinstance(stm, WaitStm): return maxId else: for _stm in stm._iter_stms(): maxId = max(maxId, getMaxStmIdForStm(_stm)) return maxId
Get maximum _instId from all assigments in statement
11,546
def connect_paragraph(self, paragraph, paragraphs): if paragraph.depth > 0: n = range(len(paragraphs)) n.reverse() for i in n: if paragraphs[i].depth == paragraph.depth-1: paragraph.parent = paragraphs[i] ...
Create parent/child links to other paragraphs. The paragraphs parameters is a list of all the paragraphs parsed up till now. The parent is the previous paragraph whose depth is less. The parent's children include this paragraph. Called from parse_paragr...
11,547
def _fetch_cached_output(self, items, result): if not appsettings.FLUENT_CONTENTS_CACHE_OUTPUT or not self.use_cached_output: result.add_remaining_list(items) return for contentitem in items: result.add_ordering(contentitem) output = None ...
First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database.
11,548
async def get_config(self): config_facade = client.ModelConfigFacade.from_connection( self.connection() ) result = await config_facade.ModelGet() config = result.config for key, value in config.items(): config[key] = ConfigValue.from_json(value) ...
Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes.
11,549
def _get_reciprocal(self): orign = self.portal[] destn = self.portal[] if ( destn in self.board.arrow and orign in self.board.arrow[destn] ): return self.board.arrow[destn][orign] else: return None
Return the :class:`Arrow` that connects my origin and destination in the opposite direction, if it exists.
11,550
def smt_dataset(directory=, train=False, dev=False, test=False, train_filename=, dev_filename=, test_filename=, extracted_name=, check_files=[], url=, fine_grai...
Load the Stanford Sentiment Treebank dataset. Semantic word spaces have been very useful but cannot express the meaning of longer phrases in a principled way. Further progress towards understanding compositionality in tasks such as sentiment detection requires richer supervised training and evaluation reso...
11,551
def fake_keypress(self, key, repeat=1): for _ in range(repeat): self.mediator.fake_keypress(key)
Fake a keypress Usage: C{keyboard.fake_keypress(key, repeat=1)} Uses XTest to 'fake' a keypress. This is useful to send keypresses to some applications which won't respond to keyboard.send_key() @param key: they key to be sent (e.g. "s" or "<enter>") @param repeat: number of t...
11,552
def format_python2_stmts(python_stmts, show_tokens=False, showast=False, showgrammar=False, compile_mode=): parser_debug = {: False, : False, : showgrammar, : True, : True, : True } parsed = parse_python2(python_stmts, show_tokens=show_token...
formats python2 statements
11,553
def from_resolver(cls, spec_resolver): spec_validators = cls._get_spec_validators(spec_resolver) return validators.extend(Draft4Validator, spec_validators)
Creates a customized Draft4ExtendedValidator. :param spec_resolver: resolver for the spec :type resolver: :class:`jsonschema.RefResolver`
11,554
def matrix2map(data_matrix, map_shape): r map_shape = np.array(map_shape) image_shape = np.sqrt(data_matrix.shape[0]).astype(int) layout = np.array(map_shape // np.repeat(image_shape, 2), dtype=) data_map = np.zeros(map_shape) temp = data_matrix.reshape(image_shape, image_shape, da...
r"""Matrix to Map This method transforms a 2D matrix to a 2D map Parameters ---------- data_matrix : np.ndarray Input data matrix, 2D array map_shape : tuple 2D shape of the output map Returns ------- np.ndarray 2D map Raises ------ ValueError For ...
11,555
def derationalize_denom(expr): r_pos = -1 p_pos = -1 numerator = S.Zero denom_sq = S.One post_factors = [] if isinstance(expr, Mul): for pos, factor in enumerate(expr.args): if isinstance(factor, Rational) and r_pos < 0: r_pos = pos numera...
Try to de-rationalize the denominator of the given expression. The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from ``sqrt(2)/2``. Specifically, this matches `expr` against the following pattern:: Mul(..., Rational(n, d), Pow(d, Rational(1, 2)), ...) and returns a tuple ``(numerato...
11,556
def kill(self, signal=None): return self.client.api.kill(self.id, signal=signal)
Kill or send a signal to the container. Args: signal (str or int): The signal to send. Defaults to ``SIGKILL`` Raises: :py:class:`docker.errors.APIError` If the server returns an error.
11,557
def updateRules( self ): terms = sorted(self._rules.keys()) for child in self.lineWidgets(): child.setTerms(terms)
Updates the query line items to match the latest rule options.
11,558
def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument(, type=argparse.FileType(), help= ) parser.add_argument(, , action=, help=) parser.add_argument(, , type=argparse.FileType(), ...
Parse passed in cooked single HTML.
11,559
def temperature_effectiveness_TEMA_H(R1, NTU1, Ntp, optimal=True): r if Ntp == 1: A = 1./(1 + R1/2.)*(1. - exp(-NTU1*(1. + R1/2.)/2.)) D = exp(-NTU1*(1. - R1/2.)/2.) if R1 != 2: B = (1. - D)/(1. - R1*D/2.) else: B = NTU1/(2. + NTU1) E = (A + B - A*...
r'''Returns temperature effectiveness `P1` of a TEMA H type heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of number of tube passes `Ntp`. For the two tube pass case, there are two possible orientations, one inefficient and one efficient controlled by the `op...
11,560
def YiqToRgb(y, i, q): (%g, %g, %g)(1, 0.5, 5.442e-07) r = y + (i * 0.9562) + (q * 0.6210) g = y - (i * 0.2717) - (q * 0.6485) b = y - (i * 1.1053) + (q * 1.7020) return (r, g, b)
Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1]...
11,561
def _iterdump(self, file_name, headers=None): if headers is None: headers = ["Discharge_Capacity", "Charge_Capacity"] step_txt = self.headers_normal[] point_txt = self.headers_normal[] cycle_txt = self.headers_normal[] self.logger.debug("iterating through f...
Function for dumping values from a file. Should only be used by developers. Args: file_name: name of the file headers: list of headers to pick default: ["Discharge_Capacity", "Charge_Capacity"] Returns: pandas.DataFrame
11,562
def parse(self, scope): assert (len(self.tokens) == 3) expr = self.process(self.tokens, scope) A, O, B = [ e[0] if isinstance(e, tuple) else e for e in expr if str(e).strip() ] try: a, ua = utility.analyze_number(A, ) b, ub...
Parse Node args: scope (Scope): Scope object raises: SyntaxError returns: str
11,563
def cli(obj, purge): client = obj[] if obj[] == : r = client.http.get() click.echo(json.dumps(r[], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj[] headers = { : , : , : , : , : , : , : , : , : , : , : , : , : , :...
List alert suppressions.
11,564
def get_swagger_view(title=None, url=None, patterns=None, urlconf=None): class SwaggerSchemaView(APIView): _ignore_model_permissions = True exclude_from_schema = True permission_classes = [AllowAny] renderer_classes = [ CoreJSONRenderer, renderers.OpenAPI...
Returns schema view which renders Swagger/OpenAPI.
11,565
def get_base_route(cls): base_route = cls.__name__.lower() if cls.base_route is not None: base_route = cls.base_route base_rule = parse_rule(base_route) cls.base_args = [r[2] for r in base_rule] return base_route.strip("/")
Returns the route base to use for the current class.
11,566
def _trace_dispatch(frame, event, arg): code = frame.f_code key = id(code) n = sampling_counters.get(key, 0) if n is None: return if event == : sampling_counters[key] = n + 1 if n not in sampling_sequence: if n > LAS...
This is the main hook passed to setprofile(). It implement python profiler interface. Arguments are described in https://docs.python.org/2/library/sys.html#sys.settrace
11,567
def wait(self, time): self._wait = Event() return not self._wait.wait(time)
Pauses the thread for a specified time. Returns False if interrupted by another thread and True if the time runs out normally.
11,568
def get_collection(self, url): url = self.BASE_API2 + url while url is not None: response = self.get_data(url) for value in response[]: yield value url = response.get(, None)
Pages through an object collection from the bitbucket API. Returns an iterator that lazily goes through all the 'values' of all the pages in the collection.
11,569
def postprocess_segments(self): for iseg, seg in enumerate(self.segs): mask = np.zeros(self._adata.shape[0], dtype=bool) mask[seg] = True self.segs[iseg] = mask self.segs = np.array(self.segs) self.segs_tips = np.array(self....
Convert the format of the segment class members.
11,570
def solve(self, scenario, solver): clusters = set(self.clustering.busmap.values) n = len(clusters) self.stats = {: pd.DataFrame( index=sorted(clusters), columns=["decompose", "spread", "transfer"])} profile = cProfile.Profile() for i, cluster in e...
Decompose each cluster into separate units and try to optimize them separately :param scenario: :param solver: Solver that may be used to optimize partial networks
11,571
def stop(self): if self.is_run: self._service.shutdown() self._service.server_close()
Stop the server. Do nothing if server is already not running.
11,572
def regressOut(Y, X, return_b=False): Xd = la.pinv(X) b = Xd.dot(Y) Y_out = Y-X.dot(b) if return_b: return Y_out, b else: return Y_out
regresses out X from Y
11,573
def Transformer(source_vocab_size, target_vocab_size, mode=, num_layers=6, feature_depth=512, feedforward_depth=2048, num_heads=8, dropout=0.1, shared_embedding=True, max_len=2...
Transformer model. Args: source_vocab_size: int: source vocab size target_vocab_size: int: target vocab size mode: str: 'train' or 'eval' num_layers: int: number of encoder/decoder layers feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads...
11,574
def _default_hparams(): return hparam.HParams( loss_multiplier=1.0, batch_size_multiplier=1, stop_at_eos=False, modality={}, vocab_size={}, ...
A set of basic model hyperparameters.
11,575
def generate_dict_schema(size, valid): schema = {} generator_items = [] for i in range(0, size): while True: key_schema, key_generator = generate_random_schema(valid) if key_schema not in schema: break value_schema, value_generator = ge...
Generate a schema dict of size `size` using library `lib`. In addition, it returns samples generator :param size: Schema size :type size: int :param samples: The number of samples to generate :type samples: int :param valid: Generate valid samples? :type valid: bool :returns
11,576
def before(point): if not point: return True if isinstance(point, six.string_types): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() <= point
True if point datetime specification is before now. NOTE: If point is specified it is supposed to be in local time. Not UTC/GMT !! This is because that is what gmtime() expects.
11,577
def reminder_validator(input_str): match = re.match(REMINDER_REGEX, input_str) if match or input_str == : return input_str else: raise ValidationError( )
Allows a string that matches utils.REMINDER_REGEX. Raises ValidationError otherwise.
11,578
def crypto_config_from_table_info(materials_provider, attribute_actions, table_info): ec_kwargs = table_info.encryption_context_values if table_info.primary_index is not None: ec_kwargs.update( {"partition_key_name": table_info.primary_index.partition, "sort_key_name": table_info.primar...
Build a crypto config from the provided values and table info. :returns: crypto config and updated kwargs :rtype: tuple(CryptoConfig, dict)
11,579
def trim_snapshots(self, hourly_backups = 8, daily_backups = 7, weekly_backups = 4): now = datetime.utcnow() last_hour = datetime(now.year, now.month, now.day, now.hour) last_midnig...
Trim excess snapshots, based on when they were taken. More current snapshots are retained, with the number retained decreasing as you move back in time. If ebs volumes have a 'Name' tag with a value, their snapshots will be assigned the same tag when they are created. The values ...
11,580
def extract_pool_attr(cls, req): attr = {} if in req: attr[] = int(req[]) if in req: attr[] = req[] if in req: attr[] = req[] if in req: attr[] = req[] if in req: attr[] = int(req[]) if in...
Extract pool attributes from arbitary dict.
11,581
def delete_report(report): for path in glob.glob(os.path.join(_get_reports_path(), report)): shutil.rmtree(path)
Delete report(s), supports globbing.
11,582
def cnvlGauss2D(idxPrc, aryBoxCar, aryMdlParamsChnk, tplPngSize, varNumVol, queOut): varChnkSze = np.size(aryMdlParamsChnk, axis=0) varNumMtnDrtn = aryBoxCar.shape[2] aryOut = np.zeros([varChnkSze, varNumMtnDrtn, varNumVol]) for idxMtn in range(0, varNumMtnDrt...
Spatially convolve boxcar functions with 2D Gaussian. Parameters ---------- idxPrc : 2d numpy array, shape [n_samples, n_measurements] Description of input 1. aryBoxCar : float, positive Description of input 2. aryMdlParamsChnk : 2d numpy array, shape [n_samples, n_measurements] ...
11,583
def list_metrics(): for name, operator in ALL_OPERATORS.items(): print(f"{name} operator:") if len(operator.cls.metrics) > 0: print( tabulate.tabulate( headers=("Name", "Description", "Type"), tabular_data=operator.cls.metrics,...
List metrics available.
11,584
def search_variants( self, variant_set_id, start=None, end=None, reference_name=None, call_set_ids=None): request = protocol.SearchVariantsRequest() request.reference_name = pb.string(reference_name) request.start = pb.int(start) request.end = pb.int(end)...
Returns an iterator over the Variants fulfilling the specified conditions from the specified VariantSet. :param str variant_set_id: The ID of the :class:`ga4gh.protocol.VariantSet` of interest. :param int start: Required. The beginning of the window (0-based, inclusive) ...
11,585
def get_slide_vars(self, slide_src, source=None): presenter_notes = None find = re.search(r, slide_src, re.DOTALL | re.UNICODE | re.IGNORECASE) if find: if self.presenter_notes: presenter_notes = slide_src[find.end():].strip() ...
Computes a single slide template vars from its html source code. Also extracts slide informations for the table of contents.
11,586
def _correctArtefacts(self, image, threshold): image = np.nan_to_num(image) medianThreshold(image, threshold, copy=False) return image
Apply a thresholded median replacing high gradients and values beyond the boundaries
11,587
def autodiscover(): global LOADED if LOADED: return LOADED = True for app in get_app_name_list(): try: module = import_module(app) except ImportError: pass else: try: import_module("%s.page_processors" % app) ...
Taken from ``django.contrib.admin.autodiscover`` and used to run any calls to the ``processor_for`` decorator.
11,588
def unique(func, num_args=0, max_attempts=100, cache=None): if cache is None: cache = _cache_unique @wraps(func) def wrapper(*args): key = "%s_%s" % (str(func.__name__), str(args[:num_args])) attempt = 0 while attempt < max_attempts: attempt += 1 ...
wraps a function so that produce unique results :param func: :param num_args: >>> import random >>> choices = [1,2] >>> a = unique(random.choice, 1) >>> a,b = a(choices), a(choices) >>> a == b False
11,589
def drain_events(self, timeout=None): chanmap = self.channels chanid, method_sig, args, content = self._wait_multiple( chanmap, None, timeout=timeout, ) channel = chanmap[chanid] if (content and channel.auto_encode_decode and ...
Wait for an event on a channel.
11,590
def _read_fasta_files(f, args): seq_l = {} sample_l = [] idx = 1 for line1 in f: line1 = line1.strip() cols = line1.split("\t") with open(cols[0], ) as fasta: sample_l.append(cols[1]) for line in fasta: if line.startswith(">"): ...
read fasta files of each sample and generate a seq_obj with the information of each unique sequence in each sample :param f: file containing the path for each fasta file and the name of the sample. Two column format with `tab` as field separator :returns: * :code:`seq_l`: is a list of seq_obj obje...
11,591
def parse_boolargs(self, args): if not isinstance(args, list): args = [args] return_vals = [] bool_args = [] for arg in args: if not isinstance(arg, tuple): return_val = arg bool_arg = None elif len(arg...
Returns an array populated by given values, with the indices of those values dependent on given boolen tests on self. The given `args` should be a list of tuples, with the first element the return value and the second argument a string that evaluates to either True or False for each ele...
11,592
def set_nsxcontroller_ip(self, **kwargs): name = kwargs.pop() ip_addr = str((kwargs.pop(, None))) nsxipaddress = ip_interface(unicode(ip_addr)) if nsxipaddress.version != 4: raise ValueError() ip_args = dict(name=name, address=ip_addr) method_name = ...
Set nsx-controller IP Args: IP (str): IPV4 address. callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
11,593
def getAddPerson(self): fragment = AddPersonFragment(self.organizer) fragment.setFragmentParent(self) return fragment
Return an L{AddPersonFragment} which is a child of this fragment and which will add a person to C{self.organizer}.
11,594
def assets(lon=None, lat=None, begin=None, end=None): base_url = "https://api.nasa.gov/planetary/earth/assets?" if not lon or not lat: raise ValueError( "assets endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: ...
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/assets QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin YYYY-MM-DD n/a beginning of date range end YYYY-MM-DD today end of date range api_key string DEMO_KEY api.nasa....
11,595
def visit_BinaryOperation(self, node): self.visit(node.left) self.visit(node.right)
Visitor for `BinaryOperation` AST node.
11,596
def make_shift_function(alphabet): def shift_case_sensitive(shift, symbol): case = [case for case in alphabet if symbol in case] if not case: return symbol case = case[0] index = case.index(symbol) return case[(index - shift) % len(case)] return shift_c...
Construct a shift function from an alphabet. Examples: Shift cases independently >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase]) <function make_shift_function.<locals>.shift_case_sensitive> Additionally shift punctuation characters >>> make_shift...
11,597
def new_job(frontier, job_conf): validate_conf(job_conf) job = Job(frontier.rr, { "conf": job_conf, "status": "ACTIVE", "started": doublethink.utcnow()}) if "id" in job_conf: job.id = job_conf["id"] if "max_claimed_sites" in job_conf: job.max_claimed_...
Returns new Job.
11,598
def run_unlock(device_type, args): util.setup_logging(verbosity=args.verbose) with device_type() as d: log.info(, d)
Unlock hardware device (for future interaction).
11,599
def get_metric_parsers(metric_packages=tuple(), include_defaults=True): metric_parsers = set() if include_defaults: import git_code_debt.metrics metric_parsers.update(discover(git_code_debt.metrics, is_metric_cls)) for metric_package in metric_packages: metric_parsers.update(d...
Gets all of the metric parsers. Args: metric_packages - Defaults to no extra packages. An iterable of metric containing packages. A metric inherits DiffParserBase and does not have __metric__ = False A metric package must be imported using import a.b.c include_d...