Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
342,700
def field_dict(self, model): if self.field_names is None: return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)]) else: return dict([(f.name, f) for f in model._meta.fields ...
Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes that into account when building the dictionary.
342,701
def _appendReportKeys(keys, prefix, results): allKeys = results.keys() allKeys.sort() for key in allKeys: if hasattr(results[key], ): _appendReportKeys(keys, "%s%s:" % (prefix, key), results[key]) else: keys.add("%s%s" % (prefix, key))
Generate a set of possible report keys for an experiment's results. A report key is a string of key names separated by colons, each key being one level deeper into the experiment results dict. For example, 'key1:key2'. This routine is called recursively to build keys that are multiple levels deep from the resu...
342,702
def is_all_field_none(self): if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._invoice_date is not None: return False if self._invoice...
:rtype: bool
342,703
def p_levelsigs_comma(self, p): p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
levelsigs : levelsigs COMMA levelsig
342,704
def _make_req(self, method, url, methname, headers=None): hset = hdrs.HeaderDict() for hdr, value in self._headers.items(): if value: hset[hdr] = value if headers is not None: hset.update(hea...
Create a request object for the specified method and url.
342,705
def get_help_data(filepath): try: with open(filepath, ) as file: return _json.load(file, object_pairs_hook=OrderedDict) except Exception as e: logger.error("Could not load file {}".format(filepath)) logger.exception(e) return {}
Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file
342,706
def _get_config(self, node): if self._run_conf.config is None: log.debug() config = self._get_config_by_discovery(node) else: log.debug(, self._run_conf.config) if not os.path.exists(self._run_conf.config): raise IllegalConfigurati...
Get and cache the run configuration for `node`. If no configuration exists (not local and not for the parent node), returns and caches a default configuration. The algorithm: ------------- * If the current directory's configuration exists in `self._cache` - return it...
342,707
def raw_to_bv(self): if self.symbolic: return BVS(next(iter(self.variables)).replace(self.STRING_TYPE_IDENTIFIER, self.GENERATED_BVS_IDENTIFIER), self.length) else: return BVV(ord(self.args[0]), self.length)
A counterpart to FP.raw_to_bv - does nothing and returns itself.
342,708
def shear_vel_at_depth(self, y_c): sl = self.get_soil_at_depth(y_c) if y_c <= self.gwl: saturation = False else: saturation = True if hasattr(sl, "get_shear_vel_at_v_eff_stress"): v_eff = self.get_v_eff_stress_at_depth(y_c) vs = sl...
Get the shear wave velocity at a depth. :param y_c: float, depth from surface :return:
342,709
def intervals_between(lon1, lat1, depth1, lon2, lat2, depth2, length): assert length > 0 hdist = geodetic_distance(lon1, lat1, lon2, lat2) vdist = depth2 - depth1 total_distance = round(numpy.sqrt(hdist ** 2 + vdist ** 2), 7) num_intervals = int...
Find a list of points between two given ones that lie on the same great circle arc and are equally spaced by ``length`` km. :param float lon1, lat1, depth1: Coordinates of a point to start placing intervals from. The first point in the resulting list has these coordinates. :param float lon2...
342,710
def reduce_value(value, default=EMPTY_STR): if hasattr(value, ): vlen = len(value) if vlen == 0: return default elif vlen == 1: if isinstance(value, set): return value.pop() elif isinstance(value, _reduce_types): retu...
:return: a single value from lists, tuples or sets with one item; otherwise, the value itself if not empty or the default if it is.
342,711
def FindHeader(self, header): for section_list in self.include_list: for f in section_list: if f[0] == header: return f[1] return -1
Check if a header has already been included. Args: header: header to check. Returns: Line number of previous occurrence, or -1 if the header has not been seen before.
342,712
def trigger_actions(self, source, actions): ret = [] for action in actions: if isinstance(action, EventListener): self.log("Registering event listener %r on %r", action, self) action.once = True if source.type == CardType.SPELL: listener = source.controller else: liste...
Performs a list of `actions` from `source`. This should seldom be called directly - use `queue_actions` instead.
342,713
def update_file(self, filepath, creator, status): file_handle = self.get_handle(filepath) if status in [FileStatus.exists, FileStatus.superseded]: fullpath = file_handle.fullpath if not os.path.exists(fullpath): raise ValueError("File %s does...
Update a file in the archive If the file does not exists, this raises a `KeyError` Parameters ---------- filepath : str The path to the file creatror : int A unique key for the job that created this file status : `FileStatus` Enume...
342,714
def split_in_columns(filterform, fields_per_column=None): nfields = len(filterform.fields) if fields_per_column is None: fields_per_column = filterform.fields_per_column ncolumns, tail = divmod(nfields, fields_per_column) if tail > 0: ncolumns += 1 itr = iter(filterform) ...
Return iterator that yields a column (iterator too). By default, flat field list is divided in columns with fields_per_column elements in each (fields_per_column is a class attribute).
342,715
def connectionLost(self, reason): self.setTimeout(None) if reason.check(ResponseDone, PotentialDataLoss): self.deferred.callback(None) else: self.deferred.errback(reason)
Called when the body is complete or the connection was lost. @note: As the body length is usually not known at the beginning of the response we expect a L{PotentialDataLoss} when Twitter closes the stream, instead of L{ResponseDone}. Other exceptions are treated as error conditions.
342,716
def _wns_authenticate(scope="notify.windows.com", application_id=None): client_id = get_manager().get_wns_package_security_id(application_id) client_secret = get_manager().get_wns_secret_key(application_id) if not client_id: raise ImproperlyConfigured( ) if not client_secret: raise ImproperlyConfigured...
Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
342,717
def saliency_map(output, input, name="saliency_map"): max_outp = tf.reduce_max(output, 1) saliency_op = tf.gradients(max_outp, input)[:][0] return tf.identity(saliency_op, name=name)
Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. ...
342,718
def colored(text, color=None, on_color=None, attrs=None): return colorize(text, fg=color, bg=on_color, attrs=attrs)
Colorize text using a reimplementation of the colorizer from https://github.com/pavdmyt/yaspin so that it works on windows. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white....
342,719
def _set_get_last_config_update_time(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=get_last_config_update_time.get_last_config_update_time, is_leaf=True, yang_name="get-last-config-update-time", rest_name="get-last-config-update-time", parent=self, ...
Setter method for get_last_config_update_time, mapped from YANG variable /brocade_vcs_rpc/get_last_config_update_time (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_last_config_update_time is considered as a private method. Backends looking to populate this variab...
342,720
def from_nvim(cls, nvim): return cls(nvim._session, nvim.channel_id, nvim.metadata, nvim.types, nvim._decode, nvim._err_cb)
Create a new Nvim instance from an existing instance.
342,721
def ensure_indirect_subclass(class_, of): if not is_indirect_subclass(class_, of): raise TypeError( "expected an indirect subclass of %r, got %s instead" % ( of, class_.__name__)) return class_
Check whether given is an indirect subclass of another, i.e. there exists at least intermediate base between ``of`` and ``class_``. :param class_: Class to check :param of: Superclass to check against :return: ``class_``, if the check succeeds :raise TypeError: When the check fails .. version...
342,722
def extract_from_dict(data, path): value = data try: for key in path: value = value[key] return value except (KeyError, IndexError, TypeError): return
Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`.
342,723
def parse_systemd_ini(content): deprecated(parse_systemd_ini, "Use the `SystemdConf` class instead.") doc = parse_doc(content) dict_all = {} for section in doc: section_dict = {} option_names = set(o.name for o in section) for name in option_names: options = [...
.. warning:: This function is deprecated, please use :py:class:`SystemdConf` instead. Function to parse config format file, the result format is dictionary.
342,724
def get_nonrentrant_counter(self, key): prefix = NONRENTRANT_STORAGE_OFFSET if key in self._nonrentrant_keys: return self._nonrentrant_keys[key] else: counter = prefix + self._nonrentrant_counter self._nonrentrant_keys[key] = counter self...
Nonrentrant locks use a prefix with a counter to minimise deployment cost of a contract.
342,725
def replace_argument(self, name, *args, **kwargs): new_arg = self.argument_class(name, *args, **kwargs) for index, arg in enumerate(self.args[:]): if new_arg.name == arg.name: del self.args[index] self.args.append(new_arg) break ...
Replace the argument matching the given name with a new version.
342,726
def show_shakemap_importer(self): from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) dialog = ShakemapConverterDialog( self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_()
Show the converter dialog.
342,727
def structure_results(res): out = {: {: []}} keys = [u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, u] for i in res: i_out = {} for k in keys: i_out[k] = i[k] out[][].append(i_out) return out
Format Elasticsearch result as Python dictionary
342,728
def execute_sql( host, username, password, sql, schema=None, param=None, kwargs=None ): kwargs.schema = coalesce(kwargs.schema, kwargs.database) if param: with MySQL(kwargs) as temp: sql = expand_template(sql, quote_param(param)) args = [ ...
EXECUTE MANY LINES OF SQL (FROM SQLDUMP FILE, MAYBE?
342,729
def delete_item(self, payload, last_modified=None): params = None if isinstance(payload, list): params = {"itemKey": ",".join([p["key"] for p in payload])} if last_modified is not None: modified = last_modified else: modified =...
Delete Items from a Zotero library Accepts a single argument: a dict containing item data OR a list of dicts containing item data
342,730
def schema(cls): root = .join([API_ROOT, , cls.__name__]) schema = cls.GET(root) return schema
Retrieves the class' schema.
342,731
def decimate_circmean(self, a, maxpoints, **kwargs): a_rad = numpy.vstack((a[0], numpy.deg2rad(a[1:]))) b = self._decimate(numkit.timeseries.circmean_histogrammed_function, a_rad, maxpoints, **kwargs) y_ma, x_ma = break_array(b[1], threshold=numpy.pi, other=b[0]) v = [y_ma] ...
Return data *a* circmean-decimated on *maxpoints*. Histograms each column into *maxpoints* bins and calculates the weighted circular mean in each bin as the decimated data, using :func:`numkit.timeseries.circmean_histogrammed_function`. The coarse grained time in the first colum...
342,732
def panset_cb(self, setting, value, chviewer, info): return self.panset(chviewer, info.chinfo)
This callback is called when a channel window is panned.
342,733
def _clean_index(self): "Clean index values after loading." for idx_name, idx_def in self.index_defs.items(): if idx_def[] == : self.build_index(idx_name) for index_name, values in self.indexes.items(): for value in values: if not isinstanc...
Clean index values after loading.
342,734
def analyze(self, rows): transposed = zip(*rows) checks = self.get_checks() column_types = [] for i, column in enumerate(transposed): col_vals = [val for val in column if val != ] for check in checks: results = set(check(val) ...
Analyze the given rows and try to determine the type of value stored. :param list rows: A list-of-lists containing one or more rows from a csv file. :returns: A list of peewee Field objects for each column in the CSV.
342,735
def fit(self,Params0=None,grad_threshold=1e-2): lik = limix.CLikNormalNULL() if Params0==None: n_params = self.C1.getNumberParams() n_params+= self.C2.getNumberParams() Params0 = SP.rand(n_params) covar = [] gp =...
fit a variance component model with the predefined design and the initialization and returns all the results
342,736
def folderitems(self): items = [] for ar, pos in self.get_container_mapping().items(): ar = api.get_object_by_uid(ar) ar_id = api.get_id(ar) ar_uid = api.get_uid(ar) ar_url = api.get_url(ar) ar_title = api.get_title(ar) url...
Custom folderitems for Worksheet ARs
342,737
def count(self, signature = None): query = self._session.query(CrashDTO.id) if signature: sig_pickled = pickle.dumps(signature, protocol = 0) query = query.filter_by(signature = sig_pickled) return query.count()
Counts how many crash dumps have been stored in this database. Optionally filters the count by heuristic signature. @type signature: object @param signature: (Optional) Count only the crashes that match this signature. See L{Crash.signature} for more details. @rtype: int ...
342,738
def update(self, *args, **kwargs): for arg in args: if not arg: continue elif isinstance(arg, dict): for k, v in arg.items(): self._update_kv(k, v) elif isinstance(arg, (list, tuple)) and (not isinstance(arg[0], (li...
update() method will *recursively* update nested dict: >>> d=Dict({'a':{'b':{'c':3,'d':4},'h':4}}) >>> d.update({'a':{'b':{'c':'888'}}}) >>> d {'a': {'b': {'c': '888', 'd': 4}, 'h': 4}} please use update_dict() if you do not want this behaviour
342,739
async def prodAllOnce(self): limit = None s = 0 for n in self.prodables: s += await n.prod(limit) return s
Call `prod` once for each Prodable in this Looper :return: the sum of the number of events executed successfully
342,740
def send(self, service, request): if not isinstance(request, list): request = [request] request = [, MDP.C_CLIENT, service] + request if self.verbose: logging.warn("I: send request to service: ", service) dump(re...
Send request to broker
342,741
def _handle_double_click(self, event): if event.get_button()[1] == 1: path_info = self.view.tree_view.get_path_at_pos(int(event.x), int(event.y)) if path_info: path = path_info[0] item_iter = self.tree_store.get_iter(path) ...
Double click with left mouse button focuses the state and toggles the collapse status
342,742
def add_path(G, data, one_way): path_edges = list(zip(path_nodes[:-1], path_nodes[1:])) G.add_edges_from(path_edges, **data) if not one_way: path_edges_opposite_direction = [(v, u) for u, v in path_edges] G.add_edges_from(path_edges_opposite...
Add a path to the graph. Parameters ---------- G : networkx multidigraph data : dict the attributes of the path one_way : bool if this path is one-way or if it is bi-directional Returns ------- None
342,743
def migrate_data(self, data, from_state): for instance in data: if instance.status == : continue container = getattr(instance, self.schema_type, {}) schema = container.pop(self.field[-1]) container[self.new_field] = schema se...
Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state
342,744
def import_string(dotted_path: str) -> ModuleType: try: module_path, class_name = dotted_path.rsplit(, 1) except ValueError: msg = "%s doesnModule "%s" does not define a "%s" attribute/class' % ( module_path, class_name) raise ImportError(msg)
Source: django.utils.module_loading Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed.
342,745
def stream(self, func, *args, **kwargs): self.close() self._stop = False self.return_type = self.get_return_type(func) kwargs[] = True kwargs[] = False self.func = partial(func, *args, **kwargs) return self
Watch an API resource and stream the result back via a generator. :param func: The API function pointer. Any parameter to the function can be passed after this parameter. :return: Event object with these keys: 'type': The type of event such as "ADDED", "DELETED"...
342,746
def parse(document, clean_html=True, unix_timestamp=False, encoding=None): if isinstance(clean_html, bool): cleaner = default_cleaner if clean_html else fake_cleaner else: cleaner = clean_html result = feedparser.FeedParserDict() result[] = feedparser.FeedParserDict() result[] =...
Parse a document and return a feedparser dictionary with attr key access. If clean_html is False, the html in the feed will not be cleaned. If clean_html is True, a sane version of lxml.html.clean.Cleaner will be used. If it is a Cleaner object, that cleaner will be used. If unix_timestamp is True, th...
342,747
def nice_identifier(): big = reduce(mul, struct.unpack(, os.urandom(16)), 1) big = big % 2**128 return uuid.UUID(int=big).hex
do not use uuid.uuid4, because it can block
342,748
def clear(self, fill = 0x00): self._buffer = [ fill ] * ( self.width * self._mem_pages )
! \~english Clear buffer data and fill color into buffer @param fill: a color value, it will fill into buffer.<br> The SSD1306 only chosen two colors: <br> 0 (0x0): black <br> 1 (0x1): white <br> \~chinese 清除缓冲区数据并在缓冲区中填充颜色 ...
342,749
def by_symbol(symbol, country_code=None): res = _data()[].get(symbol) if res: tmp_res = [] for d in res: if country_code in d.countries: tmp_res += [d] if tmp_res: return tmp_res if country_code is None: return res
Get list of possible currencies for symbol; filter by country_code Look for all currencies that use the `symbol`. If there are currencies used in the country of `country_code`, return only those; otherwise return all found currencies. Parameters: symbol: unicode Currency symbo...
342,750
def list_entitlements(owner, repo, page, page_size, show_tokens): client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_list_with_http_info( owner=owner, repo=repo, page=page, page_size=page_size, ...
Get a list of entitlements on a repository.
342,751
def get_rand(num_digit_min, num_digit_max): buf = "" max_len = random.randint(num_digit_min, num_digit_max) for i in range(max_len): buf += str(random.randint(0, 9)) return buf
Generates a character string of digits. Number of digits are between self.num_digit_min and self.num_digit_max Returns ------- str
342,752
def set_mode(self, mode, value=None): if mode in self.user_modes: self.mode_users[mode][value] = 1 else: self.modes[mode] = value
Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value
342,753
def accel_ES_fl(q: np.ndarray): num_bodies: int = 2 dims = 3 * num_bodies f = force_ES(q) a = np.zeros(dims) a[slices[0]] = f[slices[0]] / mass[0] a[slices[1]] = f[slices[1]] / mass[1] return a
Accelaration in the earth-sun system using Fluxion potential energy
342,754
def get_known_topics(self, lang): return [topic[] for topic in self.user_data.language_data[lang][] if topic[]]
Return the topics learned by a user in a language.
342,755
def sink_delete(self, project, sink_name): path = "projects/%s/sinks/%s" % (project, sink_name) self._gapic_api.delete_sink(path)
API call: delete a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink
342,756
def _ParseTriggerStartTime(self, parser_mediator, trigger): time_elements_tuple = ( trigger.start_date.year, trigger.start_date.month, trigger.start_date.day_of_month, trigger.start_time.hours, trigger.start_time.minutes, 0) date_time = None if time_elements_tuple != (0, 0, 0, ...
Parses the start time from a trigger. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. trigger (job_trigger): a trigger. Returns: dfdatetime.DateTimeValues: last run date and time or None if not ...
342,757
def addcommenttocommit(self, project_id, author, sha, path, line, note): data = { : author, : note, : path, : line, : } request = requests.post( .format(self.projects_url, project_id, sha), headers=se...
Adds an inline comment to a specific commit :param project_id: project id :param author: The author info as returned by create mergerequest :param sha: The name of a repository branch or tag or if not given the default branch :param path: The file path :param line: The line numb...
342,758
def config(settings): parameter_settings = Parameter() for k, v in settings.items(): if isinstance(v, OrderedDict): k_settings = Parameter() for ki, vi in v.items(): k_settings[ki] = vi else: k_settings = v parameter_settings[k] = ...
将配置文件转为Parameter :param settings: :return:
342,759
def color_group(self, checked=False, test_color=None): group = self.tabs.currentWidget() if test_color is None: newcolor = QColorDialog.getColor(group.idx_color) else: newcolor = test_color group.idx_color = newcolor self.apply()
Change the color of the group.
342,760
def paint(self): snippet = { : VectorStyle.get_style_value(self.opacity), : VectorStyle.get_style_value(self.color), : VectorStyle.get_style_value(self.width), } if self.translate: ...
Renders a javascript snippet suitable for use as a mapbox-gl line paint entry Returns: A dict that can be converted to a mapbox-gl javascript paint snippet
342,761
def alignUnalignedSeqs(seqs,add_seq_names=True,WorkingDir=None,\ SuppressStderr=None,SuppressStdout=None): if add_seq_names: app = Clustalw(InputHandler=,\ WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\ SuppressStdout=SuppressStdout) else: app = Clustalw(I...
Aligns unaligned sequences seqs: either list of sequence objects or list of strings add_seq_names: boolean. if True, sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of lines of some proper format that the program can handle
342,762
def _vote_legislators(self, yes_no_other): result = [] for voter in self[yes_no_other + ]: if voter[]: result.append(self._legislator_objects.get(voter[])) else: result.append(voter) return result
Return all legislators who votes yes/no/other on this bill.
342,763
def inv(z): z = qdiv(z) z2 = z * z % PRIME z9 = pow2(z2, 2) * z % PRIME z11 = z9 * z2 % PRIME z2_5_0 = (z11*z11) % PRIME * z9 % PRIME z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % PRIME z2_20_0 = pow2(z2_10_0, 10) * z2_10_0 % PRIME z2_40_0 = pow2(z2_20_0, 20) * z2_20_0 % PRI...
$= z^{-1} \mod q$, for z != 0
342,764
def getaddrspec(self): aslist = [] self.gotonext() while self.pos < len(self.field): if self.field[self.pos] == : aslist.append() self.pos += 1 elif self.field[self.pos] == : aslist.append( % self.getquote()) ...
Parse an RFC 2822 addr-spec.
342,765
def get_osid_object_mdata(): return { : { : { : , : str(DEFAULT_LANGUAGE_TYPE), : str(DEFAULT_SCRIPT_TYPE), : str(DEFAULT_FORMAT_TYPE), }, : { : , : str(DEFAULT_LANGUAGE_T...
Return default mdata map for OsidObject
342,766
def _get_certificate(cert_url): global _cache if cert_url in _cache: cert = _cache[cert_url] if cert.has_expired(): _cache = {} else: return cert url = urlparse(cert_url) host = url.netloc.lower() path = posixpath.normpath(url.path) if...
Download and validate a specified Amazon PEM file.
342,767
def handle_profile_form(form): form.process(formdata=request.form) if form.validate_on_submit(): email_changed = False with db.session.begin_nested(): current_userprofile.username = form.username.data current_userprofile.full_name = form.full_name.data ...
Handle profile update form.
342,768
def delete_lines(self): cursor = self.textCursor() self.__select_text_under_cursor_blocks(cursor) cursor.removeSelectedText() cursor.deleteChar() return True
Deletes the document lines under cursor. :return: Method success. :rtype: bool
342,769
def command(self): msg = self.gui.status_message n = len(msg) n_cur = len(self.cursor) return msg[:n - n_cur]
This is used to write a snippet message in the status bar. A cursor is appended at the end.
342,770
def convert_to_wav(self, filename): temp_filename = .format(self.temp_filename()) self.run([, , , , filename, temp_filename]) return temp_filename
Uses sox cmdline tool, to convert audio file to .wav Note: for testing, use - http://www.text2speech.org/, with American Male 2 for best results
342,771
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_enode_ka(self, **kwargs): config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") fcoe_intf_list = ET.Su...
Auto Generated Code
342,772
def contains_key(self, key): check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_contains_key_codec, key=self._to_data(key))
Transactional implementation of :func:`Map.contains_key(key) <hazelcast.proxy.map.Map.contains_key>` :param key: (object), the specified key. :return: (bool), ``true`` if this map contains an entry for the specified key, ``false`` otherwise.
342,773
def runBlot(imageObjectList, output_wcs, configObj={}, wcsmap=wcs_functions.WCSMap, procSteps=None): if procSteps is not None: procSteps.addStep() blot_name = util.getSectionName(configObj, _blot_step_num_) if configObj[blot_name][]: paramDict = buildBlotParamDic...
runBlot(imageObjectList, output_wcs, configObj={}, wcsmap=wcs_functions.WCSMap, procSteps=None)
342,774
def compute_merkleproof_for(merkletree: , element: Keccak256) -> List[Keccak256]: idx = merkletree.layers[LEAVES].index(element) proof = [] for layer in merkletree.layers: if idx % 2: pair = idx - 1 else: pair = idx + 1 if pair < len(layer): ...
Containment proof for element. The proof contains only the entries that are sufficient to recompute the merkleroot, from the leaf `element` up to `root`. Raises: IndexError: If the element is not part of the merkletree.
342,775
def _packet_listener(self): while True: datastream, source = self._sock.recvfrom(BUFFERSIZE) ipaddr, port = source try: sio = io.BytesIO(datastream) dummy1, sec_part = struct.unpack("<HH", ...
Packet listener.
342,776
def lru_cache(maxsize=128, typed=False): if maxsize is not None and not isinstance(maxsize, int): raise TypeError() sentinel = object() make_key = _make_key PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 def decorating_function(use...
Least-recently-used cache decorator, which is a backport of the same function in Python >= 3.2. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) ...
342,777
def validate_stream(stream): if not STREAM_REGEX.match(stream) or len(stream) > MAX_STREAM_LENGTH: raise InvalidStreamName(stream)
Check that the stream name is well-formed.
342,778
def open_file(default_dir=, extensions=None, title=, multiple_files=False, directory=False): Filter Name (example: Image Files)*.png*.whatever* default_dir = os.path.expanduser(default_dir) if not extensions: extensions = {} if system.get_name() == : pass elif system.get_name() == : pass else:...
Start the native file dialog for opening file(s). Starts the system native file dialog in order to open a file (or multiple files). The toolkit used for each platform: +-------------------------------------+------------------------------+ | Windows | Windows API (Win32) | +----------------------------...
342,779
def feed_index(service, opts): indexname = opts.args[0] itype = opts.kwargs[] try: index = service.indexes[indexname] except KeyError: print("Index %s not found" % indexname) return if itype in ["stream", "submit"]: stream = index.attach() else: ...
Feed the named index in a specific manner.
342,780
def p_ploymorphic_event_spec(self, p): p[0] = EventSpecNode(identifier=p[1], meaning=p[3], event_data=p[4])
event_specification : identifier TIMES event_meaning event_data
342,781
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, candidates=None, ): if candidates is None: candidates = self.candidates if candidates is None: candidates = 1 if candidate...
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
342,782
def _init_caches(self): from collections import defaultdict from .cache import Cache, NodesCache, EdgesCache self._where_cached = defaultdict(list) self._global_cache = self.query._global_cache = {} self._node_objs = node_objs = WeakValueDictionary() self._get_node_stuff ...
Immediate children of a branch
342,783
def get_record_collections(record, matcher): collections = current_collections.collections if collections is None: collections = current_collections.collections = dict(_build_cache()) output = set() for collections in matcher(collections, record): output |= collections ...
Return list of collections to which record belongs to. :param record: Record instance. :param matcher: Function used to check if a record belongs to a collection. :return: list of collection names.
342,784
def _classify(cls, response, objects): for subtype_key in cls.__dict__.get(, {}).keys(): subtype_value = None rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None...
Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. Remove the polymorphic key from the initial data.
342,785
def _get_uuid(self, context, issuer, id): data = { "idp": issuer, "id": id, "redirect_endpoint": "%s/account_linking%s" % (self.base_url, self.endpoint) } jws = JWS(json.dumps(data), alg=self.signing_key.alg).sign_compact([self.signing_key]) ...
Ask the account linking service for a uuid. If the given issuer/id pair is not linked, then the function will return a ticket. This ticket should be used for linking the issuer/id pair to the user account :type context: satosa.context.Context :type issuer: str :type id: str ...
342,786
async def begin_nested(self): if self._transaction is None: self._transaction = RootTransaction(self) await self._begin_impl() else: self._transaction = NestedTransaction(self, self._transaction) self._transaction._savepoint = await self._savepoin...
Begin a nested transaction and return a transaction handle. The returned object is an instance of :class:`.NestedTransaction`. Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may .commit() and .rollback(), however the outermos...
342,787
def _kendall_tau_subtract(self, len_old, diff_neg, tau_old): return 2./(len_old-2)*(-float(diff_neg)/(len_old-1)+tau_old)
Compute Kendall tau delta. The new sequence has length len_old - 1. Parameters ---------- len_old : int The length of the old sequence, used to compute tau_old. diff_neg : int Difference between concordant and non-concordant pairs. tau_old : floa...
342,788
def t_file_or_func(self, s): r"\t \n:][^\\.+\\ maybe_funcname = True if s == : self.add_token(, s) return if s[0] in frozenset((, "") and s.endswith("[a-zA-Z_][[a-zA-Z_.0-9\[\]]+\(\)FUNCNAMEFILENAME', base) self.pos = pos + len(s)
r'(?:[^*-+,\d\'"\t \n:][^\'"\t \n:,]*)|(?:^""".+""")|(?:\'\'\'.+\'\'\')
342,789
def validate_protected_resource_request(self, uri, http_method=, body=None, headers=None, realms=None): try: request = self._create_request(uri, http_method, body, headers) except errors.OAuth1Error: return False, None ...
Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :pa...
342,790
def get_object(self, **kwargs) ->Model: queryset = self.filter_queryset( queryset=self.get_queryset(**kwargs), **kwargs ) lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field assert lookup_url_kwarg in kwargs, ( ...
Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf.
342,791
def _to_graph(self, contexts): prev = None for context in contexts: if prev is None: prev = context continue yield prev[0], context[1], context[0] prev = context
This is an iterator that returns each edge of our graph with its two nodes
342,792
def filter_flags(parsed_flags, valid_flags): def valid_argv(argv): flagname_match = FLAG_RE.match(argv) if not flagname_match: return True flagname = flagname_match.group() return flagname in valid_flags return list(filter(valid_argv, parsed_flags))
Return the subset of `parsed_flags` that are found in the list `valid_flags`
342,793
def is_iequivalent(self, model): if not isinstance(model, DAG): raise TypeError() skeleton = nx.algorithms.isomorphism.GraphMatcher(self.to_undirected(), model.to_undirected()) if skeleton.is_isomorphic() and self.get_immoralities() == model.get_immoralities(): r...
Checks whether the given model is I-equivalent Two graphs G1 and G2 are said to be I-equivalent if they have same skeleton and have same set of immoralities. Note: For same skeleton different names of nodes can work but for immoralities names of nodes must be same Parameters ...
342,794
def find_package_docs(package_dir, skippedNames=None): logger = logging.getLogger(__name__) if skippedNames is None: skippedNames = [] doc_dir = os.path.join(package_dir, ) modules_yaml_path = os.path.join(doc_dir, ) if not os.path.exists(modules_yaml_path): raise NoPackageDo...
Find documentation directories in a package using ``manifest.yaml``. Parameters ---------- package_dir : `str` Directory of an EUPS package. skippedNames : `list` of `str`, optional List of package or module names to skip when creating links. Returns ------- doc_dirs : name...
342,795
def update(self, uid): if self.userinfo.role[0] > : pass else: return False post_data = self.get_post_data() post_data[] = self.userinfo.user_name if self.userinfo else cur_info = MWiki.get_by_uid(uid) MWikiHist.create_wiki_history(cur_i...
Update the post via ID.
342,796
def to_string(self): from pandas import Series frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: info_line = ( .format(name=type(self.frame).__name__, col=pprint_thing(frame.columns), ...
Render a DataFrame to a console-friendly tabular output.
342,797
def enable_fundamental_type_wrappers(self): self.enable_fundamental_type_wrappers = lambda: True import pkgutil headers = pkgutil.get_data( , ).decode() from clang.cindex import TypeKind size = str(self.parser.get_ctypes...
If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid.
342,798
def ToolMatches(tools=None, version=): matches = [] if tools: for tool in tools: match_version = version if tool[1] != : match_version = tool[1] match = if tool[0].endswith(): match = tool[0][:-1] elif tool...
Get the tools paths and versions that were specified
342,799
def __hosting_wechat_img(self, content_info, hosting_callback): assert callable(hosting_callback) content_img_list = content_info.pop("content_img_list") content_html = content_info.pop("content_html") for idx, img_url in enumerate(content_img_list): hosting_img_url...
将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 } hosting_callback : callable 托管回调函数,传入单个图片链接,返回托管后的图片链接...