Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
342,800
def average(self, rho): r def marginal(f, rho): remaining = len(f.shape) if remaining == 0: return rho rho = sum([f[i]*rho[i] for i in range(rho.shape[0])]) f = np.sum(f, 0) return marginal(f, rho) return marginal(self....
r"""Return the average density matrix of an inhomogeneous ensemble.
342,801
def mask_roi_digi(self): A = np.vstack([self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse]).T B = self.mask_roi_unique AA = np.ascontiguousarray(A) BB = np.ascontiguousarray(B) dt = np.dtype((np.void, AA.dtype.itemsize * AA.shape[1])) a ...
Get the index of the unique magnitude tuple for each pixel in the ROI.
342,802
def maximize(self) -> : if self._filled is not None: return self._filled for broader in self.broaden(): tag = broader.to_tag() if tag in LIKELY_SUBTAGS: result = Language.get(LIKELY_SUBTAGS[tag], normalize=False) result = resu...
The Unicode CLDR contains a "likelySubtags" data file, which can guess reasonable values for fields that are missing from a language tag. This is particularly useful for comparing, for example, "zh-Hant" and "zh-TW", two common language tags that say approximately the same thing via rat...
342,803
def compute_similarity(F, bound_idxs, dirichlet=False, xmeans=False, k=5, offset=4): feat_segments = get_feat_segments(F, bound_idxs) fmcs = feat_segments_to_2dfmc_max(feat_segments, offset) if len(fmcs) == 0: return np.arange(len(bound_idxs) - 1) if ...
Main function to compute the segment similarity of file file_struct. Parameters ---------- F: np.ndarray Matrix containing one feature vector per row. bound_idxs: np.ndarray Array with the indeces of the segment boundaries. dirichlet: boolean Whether to use the dirichlet est...
342,804
def scheduledTimes(self, runnable): events = self.store.query( TimedEvent, TimedEvent.runnable == runnable) return (event.time for event in events if not event.running)
Return an iterable of the times at which the given item is scheduled to run.
342,805
def compile_theme(theme_id=None): from engineer.processors import convert_less from engineer.themes import ThemeManager if theme_id is None: themes = ThemeManager.themes().values() else: themes = [ThemeManager.theme(theme_id)] with(indent(2)): puts(colored.yellow("Comp...
Compiles a theme.
342,806
def message_id(self) -> Optional[UnstructuredHeader]: try: return cast(UnstructuredHeader, self[b][0]) except (KeyError, IndexError): return None
The ``Message-Id`` header.
342,807
def _handler(self, sender, setting, value, **kwargs): if setting.startswith(self.prefix): self._set_attr(setting, value)
handler for ``setting_changed`` signal. @see :ref:`django:setting-changed`_
342,808
def addSuppression(self, suppressionList): for fileRe, warnRe, start, end in suppressionList: if fileRe is not None and isinstance(fileRe, str): fileRe = re.compile(fileRe) if warnRe is not None and isinstance(warnRe, str): warnRe = re.compile(wa...
This method can be used to add patters of warnings that should not be counted. It takes a single argument, a list of patterns. Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END). FILE-RE is a regular expression (string or compiled regexp), or None. If None, the pattern m...
342,809
def topic(self, topic_id): params = { self.PKEY: self.api_key } response = self._call(self.TOPIC, topic_id, params=params) return response
Retrive the topic with `topic_id` identifier. :param topic_id: identifier of the topic to retrieve
342,810
def GetClientsForHashes(cls, hashes, token=None, age=aff4.NEWEST_TIME): if age == aff4.ALL_TIMES: raise ValueError("age==aff4.ALL_TIMES is not supported.") timestamp = aff4.FACTORY.ParseAgeSpecification(age) index_objects = list(aff4.FACTORY.MultiOpen(hashes, token=token)) index_locations = ...
Yields (hash, client_files) pairs for all the specified hashes. Args: hashes: List of RDFURN's. token: Security token. age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in micros...
342,811
def match(self, string): if self.casesensitive: return self.pattern == os.path.normcase(string) else: return self.pattern.lower() == os.path.normcase(string).lower()
Returns True if the argument matches the constant.
342,812
def say(self, text): self._proxy.setBusy(True) self._proxy.notify() i = 0 for word in text.split(): self._proxy.notify(, location=i, length=len(word)) try: i = text.index(, i+1)+1 except Exception: pass ...
Speaks the given text. Generates the following notifications during output: started-utterance: When speech output has started started-word: When a word is about to be spoken. Includes the character "location" of the start of the word in the original utterance text and th...
342,813
def funcdef__26(self, def_loc, ident_tok, args, colon_loc, suite): return ast.FunctionDef(name=ident_tok.value, args=args, returns=None, body=suite, decorator_list=[], at_locs=[], keyword_loc=def_loc, name_loc=ident_tok.loc, ...
(2.6, 2.7) funcdef: 'def' NAME parameters ':' suite
342,814
def _read_sql_with_limit_offset( num_splits, sql, con, index_col, kwargs ): pandas_df = pandas.read_sql(sql, con, index_col=index_col, **kwargs) if index_col is None: index = len(pandas_df) else: index = pandas_df.index return _split_result_for_readers(1, num_splits, pandas_df...
Use a Ray task to read a chunk of SQL source. Note: Ray functions are not detected by codecov (thus pragma: no cover)
342,815
def schedule(self, project, spider, settings=None, **kwargs): url = self._build_url(constants.SCHEDULE_ENDPOINT) data = { : project, : spider } data.update(kwargs) if settings: setting_params = [] for setting_name, value i...
Schedules a spider from a specific project to run. First class, maps to Scrapyd's scheduling endpoint.
342,816
def from_image(cls, image): (w, h) = image.size if w > 512: ratio = 512. / w h = int(h * ratio) image = image.resize((512, h), Image.ANTIALIAS) if image.mode != : image = image.convert() pixels = np.array(list(image.getd...
Create a PrintableImage from a PIL Image :param image: a PIL Image :return:
342,817
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: attempts = filter_user_attempts(request, credentials) if settings.AXES_COOLOFF_TIME is None: log.debug() return attempts threshold = get_cool_off_threshold(request.axes_attempt_time) log.debug(...
Get valid user attempts that match the given request and credentials.
342,818
def female_vulnerability_section_header_element(feature, parent): _ = feature, parent header = female_vulnerability_section_header[] return header.capitalize()
Retrieve female vulnerability section header string from definitions.
342,819
def labels(ctx, *args, **kwargs): from brother_ql.output_helpers import textual_label_description print(textual_label_description(label_sizes))
List the choices for --label
342,820
def qteRegisterApplet(self, cls, replaceApplet: bool=False): if not issubclass(cls, QtmacsApplet): args = (, , inspect.stack()[0][3]) raise QtmacsArgumentError(*args) class_name = cls.__name__ if class_name in self._qteRegist...
Register ``cls`` as an applet. The name of the applet is the class name of ``cls`` itself. For instance, if the applet was defined and registered as class NewApplet17(QtmacsApplet): ... app_name = qteRegisterApplet(NewApplet17) then the applet ...
342,821
def add_element(self, element): try: self.toc[element.group][element.name] = element except KeyError: self.toc[element.group] = {} self.toc[element.group][element.name] = element
Add a new TocElement to the TOC container.
342,822
def i_batch(items, size): for items_batch in iter(lambda: tuple(islice(items, size)), tuple()): yield items_batch
Generator that iteratively batches items to a max size and consumes the items as each batch is yielded.
342,823
def from_value(cls, value, size=None, fmt=, **kwargs): bl = cls(**kwargs) bl.fromvalue(value=value, size=size, fmt=fmt) return bl
Factory method For format characters see: https://docs.python.org/2/library/struct.html
342,824
def pack_chunk(tag, data): to_check = tag + data return (struct.pack(b"!I", len(data)) + to_check + struct.pack(b"!I", zlib.crc32(to_check) & 0xFFFFFFFF))
Pack a PNG chunk for serializing to disk
342,825
def route(cls, rule=None, **kwargs): _restricted_keys = ["route", "decorators"] def decorator(f): if inspect.isclass(f): kwargs.setdefault("route", rule) kwargs["decorators"] = kwargs.get("decorators", []) + f.decorators setattr(f, "...
This decorator defines custom route for both class and methods in the view. It behaves the same way as Flask's @app.route on class: It takes the following args - rule: the root route of the endpoint - decorators: a list of decorators to run on each method ...
342,826
def add_metric(self, labels, buckets, gsum_value, timestamp=None): for bucket, value in buckets: self.samples.append(Sample( self.name + , dict(list(zip(self._labelnames, labels)) + [(, bucket)]), value, timestamp)) self.sampl...
Add a metric to the metric family. Args: labels: A list of label values buckets: A list of pairs of bucket names and values. The buckets must be sorted, and +Inf present. gsum_value: The sum value of the metric.
342,827
def _save_plot(self, *args, extension=, **kwargs): import matplotlib.pyplot as plt tmp_path = make_temp_dir() filename = .format(str(uuid.uuid4()), extension.strip()) filepath = posixpath.join(tmp_path, filename) plt.savefig(filepath, *args, **kwargs) return fi...
Save the plot. Returns ------- str The basename with which the plot has been saved.
342,828
def db_en004(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._db_en004 = value
Corresponds to IDD Field `db_en004` mean coincident dry-bulb temperature to Enthalpy corresponding to 0.4% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `db_en004` Unit: C if `value` is None it will not be checked ...
342,829
def _cache_init(self): cache_ = cache.get(self.CACHE_ENTRY_NAME) if cache_ is None: categories = get_category_model().objects.order_by() ids = {category.id: category for category in categories} aliases = {category.alias: category for category in categories ...
Initializes local cache from Django cache if required.
342,830
def move_active_window(x, y): window_id = get_window_id() cmd=[,, window_id, str(x), str(y)] subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
Moves the active window to a given position given the window_id and absolute co ordinates, --sync option auto passed in, will wait until actually moved before giving control back to us will do nothing if the window is maximized
342,831
def _es_args(self, resource, refresh=None, source_projections=None): datasource = self.get_datasource(resource) args = { : self._resource_index(resource), : datasource[0], } if source_projections: args[] = source_projections if refresh...
Get index and doctype args.
342,832
def encode(cls, value): coerced = unicode(value) if coerced == value: return coerced.encode(cls._encoding) raise InvalidValue()
take a valid unicode string and turn it into utf-8 bytes :param value: unicode, str :return: bytes
342,833
def set_open_viewing(self, open_viewing): if open_viewing: self._open_viewing = open_viewing self._query_params += str(QueryParam.OPEN_VIEWING)
Set to True to only search for properties that have upcoming 'open for viewing' dates. :param open_viewing: :return:
342,834
def get_disease_pathways(self, disease_id=None, disease_name=None, pathway_id=None, pathway_name=None, disease_definition=None, limit=None, as_df=False): q = self.session.query(models.DiseasePathway) q = self._join_disease(query=q, disease_id=disease_id, disease_na...
Get disease pathway link :param bool as_df: if set to True result returns as `pandas.DataFrame` :param disease_id: :param disease_name: :param pathway_id: :param pathway_name: :param disease_definition: :param int limit: maximum number of results ...
342,835
def generateRecord(self, record): assert(len(record)==len(self.fields)) if record is not None: for x in range(len(self.fields)): self.fields[x].addValue(record[x]) else: for field in self.fields: field.addValue(field.dataClass.getNext())
Generate a record. Each value is stored in its respective field. Parameters: -------------------------------------------------------------------- record: A 1-D array containing as many values as the number of fields fields: An object of the class field that specifies the characteristics ...
342,836
def get_good_pos_ngrams(self): if(os.path.isfile(NGRAM_PATH)): good_pos_ngrams = pickle.load(open(NGRAM_PATH, )) elif os.path.isfile(ESSAY_CORPUS_PATH): essay_corpus = open(ESSAY_CORPUS_PATH).read() essay_corpus = util_functions.sub_chars(essay_corpus) ...
Gets a set of gramatically correct part of speech sequences from an input file called essaycorpus.txt Returns the set and caches the file
342,837
def canonicalize_gates(gates: LogicalGates ) -> Dict[frozenset, LogicalGates]: canonicalized_gates = defaultdict(dict ) for indices, gate in gates.items(): indices = tuple(indices) canonicalized_gates[frozenset(indices)][indices] = gate retur...
Canonicalizes a set of gates by the qubits they act on. Takes a set of gates specified by ordered sequences of logical indices, and groups those that act on the same qubits regardless of order.
342,838
def __camel_case(word): word = word.lower() if in word: split_word = word.split() else: split_word = word.split() if len(split_word) > 0: for i, word in enumerate(split_word): if i > 0: split_word[i] = word...
Convert underscore naming into camel case naming :param str word: :return str:
342,839
def process_tag(self, tag_proc_name, tag): tag_processor = self.tag_procs[tag_proc_name] db_entry = (tag_processor.get_name(tag), tag_processor.get_entry_type(tag), tag_processor.get_filename(tag)) self.zeal_db.insert(*db_entry) self.en...
Process a tag with a tag processor and insert a DB entry. Args: tag_proc_name: A string key that maps to the TagProcessor to use. tag: A BeautifulSoup Tag to process.
342,840
def wordlist2cognates(wordlist, source, expert=, ref=): for k in wordlist: yield dict( Form_ID=wordlist[k, ], ID=k, Form=wordlist[k, ], Cognateset_ID=.format( slug(wordlist[k, ]), wordlist[k, ref]), Cognate_Detection_Method=exp...
Turn a wordlist into a cognate set list, using the cldf parameters.
342,841
def setup(self): def rename_file(afile): fnames = [f for f in os.listdir(self.workdir) if f.startswith(afile.basename)] nums = [int(f) for f in [f.split("_")[-1] for f in fnames] if f.isdigit()] last = max(nums) if nums else 0 ...
Abinit has the very *bad* habit of changing the file extension by appending the characters in [A,B ..., Z] to the output file, and this breaks a lot of code that relies of the use of a unique file extension. Here we fix this issue by renaming run.abo to run.abo_[number] if the output file "run.abo" alre...
342,842
def get_declared_fields(mcs, klass, *args, **kwargs): declared_fields = kwargs.get(, dict)() opts = klass.opts model = getattr(opts, , None) if model: converter = opts.model_converter() declared_fields.update(converter.fields_for_model( ...
Updates declared fields with fields converted from the Mongoengine model passed as the `model` class Meta option.
342,843
def copyto_emitter(target, source, env): n_target = [] for t in target: n_target = n_target + [t.File( str( s ) ) for s in source] return (n_target, source)
changes the path of the source to be under the target (which are assumed to be directories.
342,844
def advance(self, id=None): if id and self.token.id != id: raise SyntaxError("Expected {0}".format(id)) self.token = self.next()
Advance to next token, optionally check that current token is 'id'
342,845
def parse_modeString(s): refresh, width, height = None, None, None if in s: s, refresh = s.split(, 1) refresh = int(refresh) if in s: width, height = [int(x) if x.strip() else None for x in s.split...
Parses a modeString like '1024 x 768 @ 60'
342,846
def parse(self, data): self.validate_packet(data) TOTAL_DIVISOR = 223.666 id_ = self.dump_hex(data[4:6]) count = data[6] instant = data[7:11] total = data[11:16] current_watts = self._bytes_to_uint_32(instant) total_watts = self._bytes_to_uint...
Parse a 18 bytes packet in the Electricity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'count': 3, 'current_watts': 692, 'id': "0x2EB2", ...
342,847
def _decode_surrogatepass(data, codec): try: return data.decode(codec, _surrogatepass) except UnicodeDecodeError: if not _codec_can_decode_with_surrogatepass(codec): if _normalize_codec(codec) == "utf-16-be": data = _swap_bytes(data) codec = "utf...
Like data.decode(codec, 'surrogatepass') but makes utf-16-le/be work on Python < 3.4 + Windows https://bugs.python.org/issue27971 Raises UnicodeDecodeError, LookupError
342,848
def status(): * ret = {} apcaccess = _check_apcaccess() res = __salt__[](apcaccess) retcode = res[] if retcode != 0: ret[] = return ret for line in res[].splitlines(): line = line.split() ret[line[0].strip()] = line[1].strip() return ret
Return apcaccess output CLI Example: .. code-block:: bash salt '*' apcups.status
342,849
def to_files(self, array_file, vocab_file): logging.info() np.save(array_file, self.array) logging.info() self.vocab.to_file(vocab_file)
Write the embedding matrix and the vocab to files. :param (file) array_file: file to write array to :param (file) vocab_file: file to write vocab to
342,850
def run(self): listener = EventServer(self.address, EventNotifyHandler) log.info("Event listener running on %s", listener.server_address) while not self.stop_flag.is_set(): listener.handle_request()
Start the server on the local IP at port 1400 (default). Handling of requests is delegated to an instance of the `EventNotifyHandler` class.
342,851
def count_defaultdict(dict_of_lists: Mapping[X, List[Y]]) -> Mapping[X, typing.Counter[Y]]: return { k: Counter(v) for k, v in dict_of_lists.items() }
Count the number of elements in each value of the dictionary.
342,852
def get_profiles(self): out = set() for ft in self.features.values(): out.update(ft.get_profiles()) for ext in self.extensions.values(): out.update(ext.get_profiles()) return out
Returns set of profile names referenced in this Registry :return: set of profile name strings
342,853
def show_description(self): def printit(c, v): underline = "-" * len(dr.get_name(c)) resp = self.responses[v["type"]] name = "%s[%s] %s%s" % (resp.color, resp.label, dr.get_name(c), Style.RESET_ALL) print(name, file=self.stream) print(underli...
Prints the formatted response for the matching return type
342,854
def remover(self, id_script_type): if not is_valid_int_param(id_script_type): raise InvalidParameterError( u) url = + str(id_script_type) + code, xml = self.submit(None, , url) return self.response(code, xml)
Remove Script Type from by the identifier. :param id_script_type: Identifier of the Script Type. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Script Type is null and invalid. :raise TipoRoteiroNaoExisteError: Script Type not regist...
342,855
def get_real_filter(layers, img_size): real_filter = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: real_filter[j] = img_size continue ...
Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks.
342,856
def customwarn(message, category, filename, lineno, *args, **kwargs): if category is PsyPlotWarning: logger.warning(warnings.formatwarning( "\n%s" % message, category, filename, lineno)) elif category is PsyPlotCritical: logger.critical(warnings.formatwarning( "\n%s"...
Use the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.
342,857
def ListOf(cls, **kwargs): def _list_load(value): return [cls.load(d) for d in value] return Property(types=list, load=_list_load, default=list, **kwargs)
A property that is a list of `cls`.
342,858
def plugins(self): if not self.loaded: self.load_modules() return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True, type_filter=self.type_filter)
Newest version of all plugins in the group filtered by ``blacklist`` Returns: dict: Nested dictionary of plugins accessible through dot-notation. Plugins are returned in a nested dictionary, but can also be accessed through dot-notion. Just as when accessing an undefined dictionary...
342,859
def hide_intf_loopback_holder_interface_loopback_ipv6_ipv6_config_address_ipv6_address_address(self, **kwargs): config = ET.Element("config") hide_intf_loopback_holder = ET.SubElement(config, "hide-intf-loopback-holder", xmlns="urn:brocade.com:mgmt:brocade-intf-loopback") interface = ET...
Auto Generated Code
342,860
async def destroy(self, session, *, dc=None): session_id = extract_attr(session, keys=["ID"]) response = await self._api.put("/v1/session/destroy", session_id, params={"dc": dc}) return response.body is True
Destroys a given session Parameters: session (ObjectID): Session ID dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: bool: ``True`` on success
342,861
def select_option(self, option): items_list = self.get_options() for item in items_list: if item.get_attribute("value") == option: item.click() break
Performs selection of provided item from Web List @params option - string item name
342,862
def average(self, default=None): return numpy.asscalar(numpy.average(self.values)) if self.values else default
Calculate the average value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the average value or `None`.
342,863
def _mouseDown(x, y, button): if button == : try: _sendMouseEvent(MOUSEEVENTF_LEFTDOWN, x, y) except (PermissionError, OSError): pass elif button == : try: _sendMouseEvent(MOUSEEVENTF_MIDDLEDOWN, x, y) except (PermissionError, OSError): ...
Send the mouse down event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None
342,864
def pack_small_tensors(tower_grads, max_bytes=0): assert max_bytes >= 0 orig_grads = [g for g, _ in tower_grads[0]] assert all(g.dtype == tf.float32 for g in orig_grads) sizes = [4 * g.shape.num_elements() for g in orig_grads] print_stats(sizes) small_ranges = [] large_indices = []...
Concatenate gradients together more intelligently. Does binpacking Args: tower_grads: List of lists of (gradient, variable) tuples. max_bytes: Int giving max number of bytes in a tensor that may be considered small.
342,865
def load_filter(filter_name): kaiser_fast fname = os.path.join(, os.path.extsep.join([filter_name, ])) data = np.load(pkg_resources.resource_filename(__name__, fname)) return data[], data[], data[]
Retrieve a pre-computed filter. Parameters ---------- filter_name : str The key of the filter, e.g., 'kaiser_fast' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings o...
342,866
def _get_numpy_record_dtype(self, rec): import numpy as np cur_dtypes = rec.dtype col_names = cur_dtypes.names record_type_list = [] has_rec_fix = False for i in xrange(len(cur_dtypes)): curr_type = cur_dtypes[i] ...
Used when converting a pandas.DataFrame to Spark using to_records(), this will correct the dtypes of fields in a record so they can be properly loaded into Spark. :param rec: a numpy record to check field dtypes :return corrected dtype for a numpy.record or None if no correction needed
342,867
def day_of_week(self, abbr: bool = False) -> str: key = if abbr else days = self._data[].get(key) return self.random.choice(days)
Get a random day of week. :param abbr: Abbreviated day name. :return: Day of the week.
342,868
def build(self, **variables): return Locator(self.by, self.locator.format(**variables), self.description)
Formats the locator with specified parameters
342,869
def close(self) -> None: if self.close_task is None: self.close_task = self.loop.create_task(self._close())
Close the server and terminate connections with close code 1001. This method is idempotent.
342,870
def factor_list_to_map(factors): ret = {} for k, g in itertools.groupby(factors): ret[k] = len(list(g)) return ret
Factor list to map factor -> power :param factors: :return:
342,871
def load_task(module, task_name, params_str): if module is not None: __import__(module) task_cls = Register.get_task_cls(task_name) return task_cls.from_str_params(params_str)
Imports task dynamically given a module and a task name.
342,872
def _add_extra_fields(gelf_dict, record): skip_list = ( , , , , , , , , , , , , , , , , , , , , , ) for key, value in record.__dict__.items(): if key not in skip_list and not key.startswith(): gelf_dict[ % ke...
Add extra fields to the given ``gelf_dict`` However, this does not add additional fields in to ``message_dict`` that are either duplicated from standard :class:`logging.LogRecord` attributes, duplicated from the python logging module source (e.g. ``exc_text``), or violate GLEF format (i...
342,873
def _add_default_branch(self, body): assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body = body else: self.else_body._add(body)
Add a default body for this conditional (the `else` branch).
342,874
def parse_comment_node(comment): lines = comment.split() if lines[0].startswith(): lines = lines[1:] post_Q = float(lines[0]) debug_rows = [] comment_splitter = re.compile(r) for line in lines[3:]: if not line: continue columns = comment_split...
Resign Threshold: -0.88 -0.0662 D4 (100) ==> D16 (14) ==> Q16 (3) ==> Q4 (1) ==> Q: -0.07149 move: action Q U P P-Dir N soft-N p-delta p-rel D4 : -0.028, -0.048, 0.020, 0.048, 0.064, 100 0.1096 0.06127 1.27 D16 : -0.024, -0.043, 0.019, 0.044, 0.059, 96 0.1053 0.06135 1.40
342,875
def partition(self, nmin, nmax): if self.n < nmin: return [self] else: ret = subpartition(self, nmin, nmax) return flatten(ret)
This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points. Parameters ---------- thresh : int The minimum numb...
342,876
async def keep_alive(self, command): period = int(command[0]) margin = int(command[1]) await self.core.keep_alive(period, margin)
Periodically send a keep alive message to the Arduino. Frequency of keep alive transmission is calculated as follows: keep_alive_sent = period - (period * margin) :param command: {"method": "keep_alive", "params": [PERIOD, MARGIN]} Period is time period between keepalives. Range is 0-1...
342,877
def raw(self, file_path, ref, streamed=False, action=None, chunk_size=1024, **kwargs): file_path = file_path.replace(, ).replace(, ) path = % (self.path, file_path) query_data = {: ref} result = self.gitlab.http_get(path, query_data=query_data, ...
Return the content of a file for a commit. Args: ref (str): ID of the commit filepath (str): Path of the file to return streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for trea...
342,878
def bgr2gray(img, keepdim=False): out_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if keepdim: out_img = out_img[..., None] return out_img
Convert a BGR image to grayscale image. Args: img (ndarray): The input image. keepdim (bool): If False (by default), then return the grayscale image with 2 dims, otherwise 3 dims. Returns: ndarray: The converted grayscale image.
342,879
def find_parameter(self, name): name = self.normalize_name(name) arg = self.args.get(name) return None if arg is None else arg.parameter
Find parameter by name or normalized arg name.
342,880
def GetAncestor(handle: int, flag: int) -> int: return ctypes.windll.user32.GetAncestor(ctypes.c_void_p(handle), flag)
GetAncestor from Win32. handle: int, the handle of a native window. index: int, a value in class `GAFlag`. Return int, a native window handle.
342,881
def thread_info(self): tid = threading.current_thread().name if tid == : tid = current = fibers.current() fid = getattr(current, ) if current.parent else return .format(tid, fid)
Return a string identifying the current thread and fiber.
342,882
def parse_node(self, node): if node.get() in self.parsed_nodes: return self.parsed_nodes[node.get()] (node_parser, spec_class) = self.parser._get_parser_class(node.tag) if not node_parser or not spec_class: raise ValidationException( "There is n...
Parses the specified child task node, and returns the task spec. This can be called by a TaskParser instance, that is owned by this ProcessParser.
342,883
def mapPointsToCells(self): p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self.polydata(False)) p2c.Update() return self.updateMesh(p2c.GetOutput())
Transform point data (i.e., data specified per point) into cell data (i.e., data specified per cell). The method of transformation is based on averaging the data values of all points defining a particular cell. .. hint:: |mesh_map2cell| |mesh_map2cell.py|_
342,884
def remove_pyname(self, pyname): visitor = actions.RemovePyNameVisitor(self.project, self.pymodule, pyname, self._current_folder()) for import_stmt in self.imports: import_stmt.accept(visitor)
Removes pyname when imported in ``from mod import x``
342,885
def unfreeze(name, path=None, use_vt=None): * _ensure_exists(name, path=path) if state(name, path=path) == : raise CommandExecutionError( {0}\.format(name) ) cmd = if path: cmd += .format(pipes.quote(path)) return _change_state(cmd, name, , path=path, use_vt=...
Unfreeze the named container. path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 use_vt run the command through VT .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.unfreeze ...
342,886
def set(self, item, value): value_is_extension_type = (is_extension_type(value) or is_extension_array_dtype(value)) if value_is_extension_type: def value_getitem(placement): return val...
Set new item in-place. Does not consolidate. Adds new Block if not contained in the current set of items
342,887
def is_seventyfive_moves(self) -> bool: if self.halfmove_clock >= 150: if any(self.generate_legal_moves()): return True return False
Since the 1st of July 2014, a game is automatically drawn (without a claim by one of the players) if the half-move clock since a capture or pawn move is equal to or grather than 150. Other means to end a game take precedence.
342,888
def GetReportData(self, get_report_args, token=None): ret = rdf_report_plugins.ApiReportData( representation_type=RepresentationType.AUDIT_CHART, audit_chart=rdf_report_plugins.ApiAuditChartReportData( used_fields=self.USED_FIELDS)) ret.audit_chart.rows = _LoadAuditEvents( ...
Filter the cron job approvals in the given timerange.
342,889
def get_tree_from_branch(self, ref): try: return self.peel(self.repo.lookup_reference( .format(ref))).tree except KeyError: return None
Return a pygit2.Tree object matching a head ref fetched into refs/remotes/origin/
342,890
def cosh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cosh, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic cosine of x.
342,891
def create_project(session, title, description, currency, budget, jobs): project_data = {: title, : description, : currency, : budget, : jobs } response = make_post_request(session, ...
Create a project
342,892
def do_mfa(self, args): parser = CommandArgumentParser("mfa") parser.add_argument(dest=,help=); parser.add_argument("-p","--profile",dest=,default=AwsConnectionFactory.instance.getProfile(),help=); args = vars(parser.parse_args(args)) token = args[] aws...
Enter a 6-digit MFA token. Nephele will execute the appropriate `aws` command line to authenticate that token. mfa -h for more details
342,893
def get_components(A, no_depend=False): if not np.all(A == A.T): raise BCTParamError( ) A = binarize(A, copy=True) n = len(A) np.fill_diagonal(A, 1) edge_map = [{u,v} for u in range(n) for v in range(n) if A[u,v] == 1] union_sets = [] for ite...
Returns the components of an undirected graph specified by the binary and undirected adjacency matrix adj. Components and their constitutent nodes are assigned the same index and stored in the vector, comps. The vector, comp_sizes, contains the number of nodes beloning to each component. Parameters ...
342,894
def on_to_coordinates(self, speed, x_target_mm, y_target_mm, brake=True, block=True): assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates" self.off(brake=) x_delta = x_target_mm - self.x_pos_mm y_delta = y_target_mm - s...
Drive to (`x_target_mm`, `y_target_mm`) coordinates at `speed`
342,895
def port_profile_qos_profile_cee(self, **kwargs): config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name") name_key.text = kwargs.pop() qos_profile...
Auto Generated Code
342,896
def handle_event(self, event): string = if in event: string += elif in event: if in event: string += string += else: string += if event.get(): string += print(string.for...
Default handling of incoming event (print).
342,897
def is_locked(self, key): check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(map_is_locked_codec, key_data, key=key_data)
Checks the lock for the specified key. If the lock is acquired, it returns ``true``. Otherwise, it returns ``false``. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (...
342,898
def is_correct(self): state = True if self.members: self.members = list(set(self.members)) if self.unknown_members: for member in self.unknown_members: msg = "[%s::%s] as %s, got unknown member " % ( self.my_type, se...
Check if a group is valid. Valid mean all members exists, so list of unknown_members is empty :return: True if group is correct, otherwise False :rtype: bool
342,899
def findOutlet(self, shapefile_path): check_watershed_boundary_geometry(shapefile_path) shapefile = ogr.Open(shapefile_path) source_layer = shapefile.GetLayer(0) source_lyr_proj = source_layer.GetSpatialRef() osr_geographic_proj = osr.Spatial...
Calculate outlet location