Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,200
def _from_string(cls, serialized): try: def_key, aside_type = _split_keys_v2(serialized) return cls(DefinitionKey.from_string(def_key), aside_type) except ValueError as exc: raise InvalidKeyError(cls, exc.args)
Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKeyError: Should be raised if `serialized` is not a valid...
355,201
def cli_main(pid, include_greenlet, debugger, verbose): try: print_stack(pid, include_greenlet, debugger, verbose) except DebuggerNotFound as e: click.echo( % e.args[0], err=True) click.get_current_context().exit(1)
Print stack of python process. $ pystack <pid>
355,202
def get_palette(num_colors=256): pallete = [0]*(num_colors*3) for j in range(0, num_colors): lab = j pallete[j*3+0] = 0 pallete[j*3+1] = 0 pallete[j*3+2] = 0 i = 0 while (lab > 0): pallete[j*3+0] |= (((lab >> 0) & 1) << (7-i)) pallete[...
generates the colormap for visualizing the segmentation mask Args: num_colors (int): the number of colors to generate in the output palette Returns: string: the supplied extension, if assertion is successful.
355,203
def show_error_dialog(self, message, details=None): dlg = Gtk.MessageDialog(type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, message_format=message) if details is not None: dlg.format_secondary_text(details) dlg.run() dlg.destr...
Convenience method for showing an error dialog.
355,204
def form_valid_bridge(self, form, field, model, related_field, error_message): external = form.cleaned_data[field] related_object = get_external_model(model).objects.filter(pk=external.pk).first() if related_object: try: with transaction...
call from form_valid. @form: it is form of form_valid (type: form) @field: name of the form field referring to the brigde (type: string) @model: form's model (type class) @related_field: name of the related_name of the brigde (type: string) @error_message: list of message errors ...
355,205
def vapour_density(Temperature, element, isotope=None): r atom = Atom(element, isotope) if atom.isotope is None: rho = 0.0 for iso in atom.isotopes: atom = Atom(element, iso) rho += vapour_number_density(Temperature, element) *\ atom.mass*atom.abundanc...
r"""This function returns the density in a rubidium or cesium vapour in kg/m^-3. It receives as input the temperature in Kelvins, the name of the element, and optionally the isotope. If no isotope is specified, the density of a vapour with the natural abundances will be returned. This is calculated...
355,206
def humanize_api_path(api_path): return reduce(lambda val, func: func(val), [parameterize, underscore, camelize], unicode(api_path))
Converts an API path to a humaized string, for example: # >>> In [2]: humanize_api_path('/api/vlan/{id}') # >>> Out[2]: u'ApiVlanId' Parameters ---------- api_path : str An API path string. Returns ------- str - humazined form.
355,207
def _parse_requirements_file(requirements_file): parsed_requirements = [] with open(requirements_file) as rfh: for line in rfh.readlines(): line = line.strip() if not line or line.startswith((, )): continue parsed_requirements.append(line) ret...
Parse requirements.txt and return list suitable for passing to ``install_requires`` parameter in ``setup()``.
355,208
def _f90repr(self, value): if isinstance(value, bool): return self._f90bool(value) elif isinstance(value, numbers.Integral): return self._f90int(value) elif isinstance(value, numbers.Real): return self._f90float(value) elif isinstance(value, n...
Convert primitive Python types to equivalent Fortran strings.
355,209
def skips(self, ticket): return self._get(self._build_url(self.endpoint.skips(id=ticket)))
Skips for ticket See Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.
355,210
def _process_phendesc(self, limit): if self.test_mode: graph = self.testgraph else: graph = self.graph model = Model(graph) raw = .join((self.rawdir, )) LOG.info("processing G2P") line_counter = 0 with open(raw, ) as f: ...
The description of the resulting phenotypes with the genotype+environment :param limit: :return:
355,211
def extract(self, obj, bypass_ref=False): for i in range(0, self.stages): try: obj = obj.parent_obj except AttributeError: raise UnstagedError(obj, .format(obj)) if self.member: return ...
Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used
355,212
def delete_entity_signal_handler(sender, instance, **kwargs): if instance.__class__ in entity_registry.entity_registry: Entity.all_objects.delete_for_obj(instance)
Defines a signal handler for syncing an individual entity. Called when an entity is saved or deleted.
355,213
def validate_set_ops(df, other): if df.columns.values.tolist() != other.columns.values.tolist(): not_in_df = [col for col in other.columns if col not in df.columns] not_in_other = [col for col in df.columns if col not in other.columns] error_string = if len(not_in_df): ...
Helper function to ensure that DataFrames are valid for set operations. Columns must be the same name in the same order, and indices must be of the same dimension with the same names.
355,214
def from_int(value: int) -> ulid.ULID: if value < 0: raise ValueError() length = (value.bit_length() + 7) // 8 if length > 16: raise ValueError(.format(length)) return ulid.ULID(value.to_bytes(16, byteorder=))
Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~int` value. :param value: 128 bit integer :type value: :class:`~int` :return: ULID from integer value :rtype: :class:`~ulid.ulid.ULID` :raises ValueError: when the value is not a 128 bit integer
355,215
def get_heteroatoms(self, elements=None): heteroatoms = set() for node in self.molgraph.graph.nodes(): if elements is not None: if str(self.species[node]) in elements: heteroatoms.add(node) else: if str(self.species[n...
Identify non-H, non-C atoms in the MoleculeGraph, returning a list of their node indices. :param elements: List of elements to identify (if only certain functional groups are of interest). :return: set of ints representing node indices
355,216
def schema2jsonschema(self, schema): fields = get_fields(schema) Meta = getattr(schema, "Meta", None) partial = getattr(schema, "partial", None) ordered = getattr(schema, "ordered", False) jsonschema = self.fields2jsonschema(fields, partial=partial, ordered=ordered) ...
Return the JSON Schema Object for a given marshmallow :class:`Schema <marshmallow.Schema>` instance. Schema may optionally provide the ``title`` and ``description`` class Meta options. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject Example: :: ...
355,217
def deploy_windows(host, port=445, timeout=900, username=, password=None, name=None, sock_dir=None, conf_file=None, start_action=None, parallel=False...
Copy the install files to a remote Windows box, and execute them
355,218
def add_dos(self, label, dos): densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities self._doses[label] = {: dos.frequencies, : densities}
Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object
355,219
def find_comment_markers(cellsource): found = {} for line in cellsource.splitlines(): line = line.strip() if line.startswith(): comment = line.lstrip().strip() if comment in comment_markers: marker = comment_markers[comme...
Look through the cell source for comments which affect nbval's behaviour Yield an iterable of ``(MARKER_TYPE, True)``.
355,220
def _update_indexes_for_deleted_object(collection, obj): for index in _db[collection].indexes.values(): _remove_from_index(index, obj)
If an object is deleted, it should no longer be indexed so this removes the object from all indexes on the given collection.
355,221
def calc_tools_spacing(tools_layout): metrics = { : (32, 0), : (21, 3), : (24, 0), : (21, 3), : (28, -1), : (38, -2), : (27, 0), : (26, 0), : (32, 0), } style_name = qapplication().style().property() key = % (...
Return a spacing (int) or None if we don't have the appropriate metrics to calculate the spacing. We're trying to adapt the spacing below the tools_layout spacing so that the main_widget has the same vertical position as the editor widgets (which have tabs above). The required spacing is ...
355,222
def set_val(self, nval): file_obj = file(os.path.join(self._base, self._attr), ) try: file_obj.write(str(nval) + ) finally: file_obj.close()
Sets new attribute's value. @param nval: replaces current value by nval. @type nval: int @raise IOError: if corresponding file in /proc/sys cannot be written.
355,223
def _get_or_create_user(self, force_populate=False): save_user = False username = self.backend.ldap_to_django_username(self._username) self._user, created = self.backend.get_or_create_user(username, self) self._user.ldap_user = self self._user.ldap_username = self._use...
Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER.
355,224
def cmd(send, *_): try: output = subprocess.check_output([], universal_newlines=True) except subprocess.CalledProcessError: output = for line in output.splitlines(): send(line)
Returns the Discordian date. Syntax: {command}
355,225
def measure_bw(type_, total_size, threads_per_core, max_threads_per_core, cores_per_socket, sockets): groups = [] for s in range(sockets): groups += [ , + str(s) + + str(total_size) + + str(threads_per_core * cores_per_socket) + + s...
*size* is given in kilo bytes
355,226
def _read_para_seq(self, code, cbit, clen, *, desc, length, version): if clen != 4: raise ProtocolError(f) _upid = self._read_unpack(4) seq = dict( type=desc, critical=cbit, length=clen, id=_upid, ) return se...
Read HIP SEQ parameter. Structure of HIP SEQ parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ...
355,227
def syllabify(word): word = split(word) compound = True if re.search(r, word) else False syllabify = _syllabify_compound if compound else _syllabify syll, rules = syllabify(word) yield syll, rules n = 3 if in rules: yield syllabify(word, T4=False) n -= 1 if i...
Syllabify the given word, whether simplex or complex.
355,228
def clear_boxes(self): self.tmin_box.Clear() self.tmin_box.SetStringSelection("") if self.current_fit: self.tmin_box.SetItems(self.T_list) self.tmin_box.SetSelection(-1) self.tmax_box.Clear() self.tmax_box.SetStringSelection("") if self.c...
Clear all boxes
355,229
def clean(self, suffixes=None): if suffixes is None: suffixes = [DONE_SUFFIX, LOCK_SUFFIX, PART_SUFFIX] for suffix in suffixes: listing = self.working_context.get_listing(suffix) for filename in listing: self.working_context.remove(filename)
Remove all persistence-related files from the directory.
355,230
def getmembers(_object, _predicate): observers = [] for key in dir(_object): try: m = getattr(_object, key) except AttributeError: continue if _predicate(m): observers.append((key, m)) pass return observers
This is an implementation of inspect.getmembers, as in some versions of python it may be buggy. See issue at http://bugs.python.org/issue1785
355,231
def attrs( maybe_cls=None, type=None, context=None, translate=None, **attrs_kwargs ): if isinstance(type, (list, tuple, set)): types = list(type) else: types = [type] if type is not None else [] context = context or {} translate = translate or {} def wrap(cls): ...
Wrap an attr enabled class.
355,232
def _create_dct_matrix(self): self.s2dct = numpy.zeros((self.mfcc_size, self.filter_bank_size)) for i in range(0, self.mfcc_size): freq = numpy.pi * float(i) / self.filter_bank_size self.s2dct[i] = numpy.cos(freq * numpy.arange(0.5, 0.5 + self.filter_bank_size, 1.0, )) ...
Create the not-quite-DCT matrix as used by Sphinx, and store it in ```self.s2dct```.
355,233
def lookup_table(values, key=None, keyval=None, unique=False, use_lists=False): if keyval is None: if key is None: keyval = lambda v: v else: keyval = lambda v: (key(v), v) if unique: return dict(keyval(v) for v in values) lut = {} for value in val...
Builds a dict-based lookup table (index) elegantly. Supports building normal and unique lookup tables. For example: >>> assert lookup_table( ... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == { ... 'b': {'bar', 'baz'}, ... 'f': {'foo'}, ... 'q': {'quux', 'qux'} ....
355,234
def selected_unit(self): item = self.lstUnits.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except (AttributeError, NameError): return None
Obtain the unit selected by user. :returns: Metadata of the selected unit. :rtype: dict, None
355,235
def path(self): return "/projects/%s/datasets/%s/models/%s" % ( self._proto.project_id, self._proto.dataset_id, self._proto.model_id, )
str: URL path for the model's APIs.
355,236
def trim_Ns(self): i = 0 while i < len(self) and self.seq[i] in : i += 1 self.seq = self.seq[i:] self.qual = self.qual[i:] self.seq = self.seq.rstrip() self.qual = self.qual[:len(self.seq)]
Removes any leading or trailing N or n characters from the sequence
355,237
def type_suffix(self): if not self.type or self.type.lower() == : return return % self.type.lower()
This is used in compose ID.
355,238
def update_changes(changes,newtext,change): "decide whether to compact the newest change into the old last; return new change list. assumes changes is safe to mutate.\ note: newtext MUST be the result of applying change to changes, and is only passed to save doing the computation again." if not cha...
decide whether to compact the newest change into the old last; return new change list. assumes changes is safe to mutate.\ note: newtext MUST be the result of applying change to changes, and is only passed to save doing the computation again.
355,239
def get_snmp_information(self): snmp_information = {} snmp_config = junos_views.junos_snmp_config_table(self.device) snmp_config.get() snmp_items = snmp_config.items() if not snmp_items: return snmp_information snmp_information = { py23...
Return the SNMP configuration.
355,240
def _pkcs1imify(self, data): size = len(util.deflate_long(self.n, 0)) filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) - 3) return zero_byte + one_byte + filler + zero_byte + SHA1_DIGESTINFO + data
turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre.
355,241
def _ps(self, sys_output): import re gap_pattern = re.compile() container_list = [] output_lines = sys_output.split() column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pa...
a helper method for parsing docker ps output
355,242
def on_resize(self, event): if self._aspect is None: return w, h = self._canvas.size aspect = self._aspect / (w / h) self.scale = (self.scale[0], self.scale[0] / aspect) self.shader_map()
Resize handler Parameters ---------- event : instance of Event The event.
355,243
def populator(self, sample): from accessoryFunctions.accessoryFunctions import GenObject if sample.general.bestassemblyfile != : profile = setattr(sample, self.analysistype, GenObject()) sample[self.analysistype].analyse = True if self.analysisty...
Populates objects with the necessary attributes :param sample: sample object
355,244
def _prt_qualifiers(associations, prt=sys.stdout): prt.write() for fld, cnt in cx.Counter(q for nt in associations for q in nt.Qualifier).most_common(): prt.write(.format(N=cnt, FLD=fld))
Print Qualifiers found in the annotations. QUALIFIERS: 1,462 colocalizes_with 1,454 contributes_to 1,157 not 13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs) 4 not contributes_to (TBD: CHK - Seen in...
355,245
def already_downloaded(track, title, filename): global arguments already_downloaded = False if os.path.isfile(filename): already_downloaded = True if arguments[] and can_convert(filename) \ and os.path.isfile(filename[:-4] + ".flac"): already_downloaded =...
Returns True if the file has already been downloaded
355,246
def initrepo(repopath, bare, shared): ag = activegit.ActiveGit(repopath, bare=bare, shared=shared)
Initialize an activegit repo. Default makes base shared repo that should be cloned for users
355,247
def objective_value(self): if self._f is None: raise RuntimeError("Problem has not been optimized yet") if self.direction == "max": return -self._f + self.offset else: return self._f + self.offset
Returns the optimal objective value
355,248
def _show_tables(self, *args): v = self.connection.lowest_server_version schema_name = \ "table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name" table_filter = \ " AND table_type = " if v >= TABLE_TYPE_MIN_VERSION else "" self._exec("SELECT fo...
print the existing tables within the 'doc' schema
355,249
def remove_action_callback(self, *event): if react_to_event(self.view, self.tree_view, event) and \ not (self.active_entry_widget and not is_event_of_key_string(event, )): self.on_remove(None) return True
Callback method for remove action The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality of maybe active a entry widget. If a entry widget is active the remove callback return with None.
355,250
def _set_seo_models(self, value): seo_models = [] for model_name in value: if "." in model_name: app_label, model_name = model_name.split(".", 1) model = apps.get_model(app_label, model_name) if model: seo_models.ap...
Gets the actual models to be used.
355,251
def get_lastfunction_header(self, header, default_return_value=None): if self._last_call is None: raise TwythonError() return self._last_call[].get(header, default_return_value)
Returns a specific header from the last API call This will return None if the header is not present :param header: (required) The name of the header you want to get the value of Most useful for the following header information: x-rate-limit-limit, ...
355,252
def recv(self): if self._closed and not self.recv_ready(): raise ChannelClosed() got = self._recv() return got
Receive a value from the channel. Receiving will always block if no value is available. If the channel is already closed, :class:`goless.ChannelClosed` will be raised. If the channel closes during a blocking ``recv``, :class:`goless.ChannelClosed` will be raised. (#TODO)
355,253
def wer_201_2018(): r dlf = DigitalFilter(, ) dlf.base = np.array([ 8.653980893285999343e-04, 9.170399868578506730e-04, 9.717635708540675208e-04, 1.029752738345341345e-03, 1.091202360259058363e-03, 1.156318936280037154e-03, 1.225321288786770891e-03, 1.298441298197734088e-03...
r"""Werthmüller 201 pt Hankel filter, 2018. Designed with the empymod add-on ``fdesign``, see https://github.com/empymod/article-fdesign. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_.
355,254
async def add_reactions(self): self.statuslog.info("Loading buttons") for e in ("⏯", "⏮", "⏹", "⏭", "🔀", "🔉", "🔊"): try: if self.embed is not None: await client.add_reaction(self.embed.sent_embed, e) except discord.DiscordException ...
Adds the reactions buttons to the current message
355,255
def cleanup(api_instance=None): api = api_instance or get_api() r = api.list_job_for_all_namespaces() delete_opts = kubernetes.client.V1DeleteOptions( propagation_policy="Background") for job in r.items: if job.status.succeeded == job.spec.completions: print(job.meta...
Remove completed jobs from the cluster
355,256
def shot_add_asset(self, *args, **kwargs): if not self.cur_shot: return dialog = AssetAdderDialog(shot=self.cur_shot) dialog.exec_() assets = dialog.assets atypes = {} for c in self.shot_asset_model.root.childItems: atypes[c.internal_data(...
Add more assets to the shot. :returns: None :rtype: None :raises: None
355,257
def run_migrations(): with engine.connect() as connection: context.configure( connection=connection, target_metadata=Model.metadata) with context.begin_transaction(): context.run_migrations()
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
355,258
def _transientSchedule(self, when, now): if self.store.parent is not None: subStore = self.store.parent.getItemByID(self.store.idInParent) hook = self.store.parent.findOrCreate( _SubSchedulerParentHook, subStore=subStore) hook._schedul...
If this service's store is attached to its parent, ask the parent to schedule this substore to tick at the given time. @param when: The time at which to tick. @type when: L{epsilon.extime.Time} @param now: Present for signature compatibility with L{_SiteScheduler._transient...
355,259
def fit_from_image(self, data, voxelsize, seeds, unique_cls): fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls) self.fit(fvs, clsselected)
This Method allows computes feature vector and train model. :cls: list of index number of requested classes in seeds
355,260
def update_gates(self, gate_update_metadata, project, gate_step_id): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if gate_step_id is not None: route_values[] = self._serialize.url(, gate_step_id, ) content = ...
UpdateGates. [Preview API] Updates the gate for a deployment. :param :class:`<GateUpdateMetadata> <azure.devops.v5_0.release.models.GateUpdateMetadata>` gate_update_metadata: Metadata to patch the Release Gates. :param str project: Project ID or project name :param int gate_step_id: Gate...
355,261
def barrier(events, sid, kind=): events[sid].set() if kind==: if sid > 0: logging.debug("{0} is waiting for {1}".format(sid, sid - 1)) events[sid - 1].wait() if sid < len(bkg_events) - 1: logging.debug("{0} is waiting for {1}".format(sid, sid + 1)) ...
act as a multiprocessing barrier
355,262
def clear_halt(self, ep): r if isinstance(ep, Endpoint): ep = ep.bEndpointAddress self._ctx.managed_open() self._ctx.backend.clear_halt(self._ctx.handle, ep)
r""" Clear the halt/stall condition for the endpoint ep.
355,263
def train(args): if not args.model.lower() in [, ]: logging.error(, args.model) sys.exit(1) if args.data.lower() == : data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment=)[:2]) data, vocab, idx_to_counts = preprocess_dataset( data, max_vocab_size=args.max_...
Training helper.
355,264
def IterReferenceInstancePaths(self, InstanceName, ResultClass=None, Role=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCo...
Retrieve the instance paths of the association instances that reference a source instance, using the Python :term:`py:generator` idiom to return the result. *New in pywbem 0.10 as experimental and finalized in 0.12.* This method uses the corresponding pull operations if supported by th...
355,265
def _reload_maybe(self): ConfigModel = apps.get_model() data = dict( ConfigModel.objects .filter(key=) .values_list(, )) if (not hasattr(self, ) or self._updated_at != data.get()): self._reload()
Reload the config if the config\ model has been updated. This is called\ once on every request by the middleware.\ Should not be called directly.
355,266
def display_system(sys, style=): v = QtViewer() v.add_post_processing(SSAOEffect) if style == : sr = v.add_renderer(AtomRenderer, sys.r_array, sys.type_array, backend=) if style == : sr = v.add_renderer(BallAndStickRenderer, ...
Display the system *sys* with the default viewer.
355,267
def get_template_names(self): site = self._contextual_vals.current_site template_names = [] menu_str = self.menu_short_name if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site: hostname = site.hostname template_names.extend([ "menus/%s/%s/lev...
Return a list (or tuple) of template names to search for when rendering an instance of this class. The list should be ordered with most specific names first, since the first template found to exist will be used for rendering.
355,268
def update(self, w, offset=0): time = self.time x = self.x exp_xw = numpy.exp(offset + numpy.dot(x, w)) n_samples, n_features = x.shape gradient = numpy.zeros((1, n_features), dtype=float) hessian = numpy.zeros((n_features, n_features), dtype=float) inv...
Compute gradient and Hessian matrix with respect to `w`.
355,269
def partial_derivative(f, x, n, nargs, delta=DELTA): dx = np.zeros((nargs, len(x[n]))) dx[n] += np.where(x[n], x[n] * delta, delta) x_dx = zip(*[xi + (dxi, -dxi) for xi, dxi in zip(x, dx)]) return (f(x_dx[0]) - f(x_dx[1])) / dx[n] / 2.0
Calculate partial derivative using central finite difference approximation. :param f: function :param x: sequence of arguments :param n: index of argument derivateve is with respect to :param nargs: number of arguments :param delta: optional step size, default is :math:`\\epsilon^{1/3}` where...
355,270
def B3(formula): if isinstance(formula, true) or formula is True or formula == Boolean3.Top.name or formula == Boolean3.Top.value: return Boolean3.Top if isinstance(formula, false) or formula is False or formula == Boolean3.Bottom.name or formula == Boolean3.Bottom.value: return Boolean3.Bo...
Rewrite formula eval result into Boolean3 :param formula: :return: Boolean3
355,271
def run(self, func=None): args = self.parser.parse_args() if self.__add_vq is not None and self.__config_logging: self.__config_logging(args) if self.__show_version_func and args.version and callable(self.__show_version_func): self.__show_version_func(self, args)...
Run the app
355,272
def migrate(self) -> None: assert self.ormSessionCreator, "ormSessionCreator is not defined" connection = self._dbEngine.connect() isDbInitialised = self._dbEngine.dialect.has_table( connection, , schema=self._metadata.schema) connection.close() ...
Migrate Perform a database migration, upgrading to the latest schema level.
355,273
def get_calendar_event(self, calendar_event): from canvasapi.calendar_event import CalendarEvent calendar_event_id = obj_or_id(calendar_event, "calendar_event", (CalendarEvent,)) response = self.__requester.request( , .format(calendar_event_id) ) ...
Return single Calendar Event by id :calls: `GET /api/v1/calendar_events/:id \ <https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.show>`_ :param calendar_event: The object or ID of the calendar event. :type calendar_event: :class:`canvasapi.calendar_...
355,274
def _initialize(self, provide_data: List[mx.io.DataDesc], provide_label: List[mx.io.DataDesc], default_bucket_key: Tuple[int, int]): source = mx.sym.Variable(C.SOURCE_NAME) source_words = source.split(num_outputs=self.config.config_emb...
Initializes model components, creates training symbol and module, and binds it.
355,275
def history_mean(self, nb=5): _, v = zip(*self._history) return sum(v[-nb:]) / float(v[-1] - v[-nb])
Return the mean on the <nb> values in the history.
355,276
def load(cls, partname, content_type, blob, package): return cls(partname, content_type, blob)
Called by ``docx.opc.package.PartFactory`` to load an image part from a package being opened by ``Document(...)`` call.
355,277
def reward_bonus(self, assignment_id, amount, reason): try: return self.mturkservice.grant_bonus(assignment_id, amount, reason) except MTurkServiceException as ex: logger.exception(str(ex))
Reward the Turker for a specified assignment with a bonus.
355,278
def snapshot_agent(self): protocols = [i.get_agent_side() for i in self._protocols.values()] return (self.agent, protocols, )
Gives snapshot of everything related to the agent
355,279
def iscontinuous(self): return all(self[i].end == self[i+1].start for i in range(len(self) - 1))
Checks if a path is continuous with respect to its parameterization.
355,280
def get_covers(work, args): with contextlib.ExitStack() as cm: if args.filename == EMBEDDED_ALBUM_ART_SYMBOL: tmp_prefix = "%s_" % (os.path.splitext(os.path.basename(inspect.getfile(inspect.currentframe())))[0]) tmp_dir = cm.enter_context(tempfile.TemporaryDirectory(prefix=tmp_prefix)) s...
Get missing covers.
355,281
def _to_DOM(self): root_node = ET.Element("location") name_node = ET.SubElement(root_node, "name") name_node.text = self._name coords_node = ET.SubElement(root_node, "coordinates") lon_node = ET.SubElement(coords_node, "lon") lon_node.text = str(self._lon) ...
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
355,282
def fast_sync_import(working_dir, import_url, public_keys=config.FAST_SYNC_PUBLIC_KEYS, num_required=len(config.FAST_SYNC_PUBLIC_KEYS), verbose=False): def logmsg(s): if verbose: print s else: log.debug(s) def logerr(s): if verbose: print >> sys...
Fast sync import. Verify the given fast-sync file from @import_path using @public_key, and then uncompress it into @working_dir. Verify that at least `num_required` public keys in `public_keys` signed. NOTE: `public_keys` needs to be in the same order as the private keys that signed.
355,283
def create_asset_timeline(self, asset_list): results = dict() for asset in asset_list: time_key = dateutil.parser.parse(asset[]) load_time = int(asset[]) if time_key in results: results[time_key].append(asset) else: ...
Returns a ``dict`` of the timeline for the requested assets. The key is a datetime object (down to the millisecond) of ANY time where at least one of the requested assets was loaded. The value is a ``list`` of ALL assets that were loading at that time. :param asset_list: ``list`` of the...
355,284
def get_stories(self, *args, **kwargs): from .story import Story, StoryDataWrapper return self.get_related_resource(Story, StoryDataWrapper, args, kwargs)
Returns a full StoryDataWrapper object for this creator. /creators/{creatorId}/stories :returns: StoriesDataWrapper -- A new request to API. Contains full results set.
355,285
def create_autoscale_rule(subscription_id, resource_group, vmss_name, metric_name, operator, threshold, direction, change_count, time_grain=, time_window=, cool_down=): PT1MPT5MPT1M metric_trigger = {: metric_name} metric_trigger[] = metric_trigger[] ...
Create a new autoscale rule - pass the output in a list to create_autoscale_setting(). Args: subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of scale set to apply scale events to. metric_name (str): Name of metric ...
355,286
def _validate_resources(self): resources = self.options.resources for key in [, , ]: if key in resources and resources[key] != 1: raise exceptions.FeatureNotAvailable( "Cannot set resource to value for {}: parallelization is not supported, " ...
Validate the resources defined in the options.
355,287
def load_environment(global_conf, app_conf): root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = dict(root=root, controllers=os.path.join(root, ), static_files=os.path.join(root, ), templates=[os.path.join(root, )]) co...
Configure the Pylons environment via the ``pylons.config`` object
355,288
def _to_kraus(rep, data, input_dim, output_dim): if rep == : return data if rep == : return _stinespring_to_kraus(data, input_dim, output_dim) if rep == : return _from_operator(, data, input_dim, output_dim) if rep != : data = _to_choi(rep, data, input_dim, outp...
Transform a QuantumChannel to the Kraus representation.
355,289
def getConfiguration(self): configuration = c_int() mayRaiseUSBError(libusb1.libusb_get_configuration( self.__handle, byref(configuration), )) return configuration.value
Get the current configuration number for this device.
355,290
def tabulate_state_transitions(x, states, pos=None): x = asarray_ndim(x, 1) check_integer_dtype(x) x = memoryview_safe(x) switch_points, transitions, _ = state_transitions(x, states) items = [(, transitions[:, 0]), (, transitions[:, 1]), (, switch_poi...
Construct a dataframe where each row provides information about a state transition. Parameters ---------- x : array_like, int 1-dimensional array of state values. states : set Set of states of interest. Any state value not in this set will be ignored. pos : array_like, int, optional...
355,291
def address(self, value): if value is not None: assert type(value) is unicode, " attribute: type is not !".format( "address", value) self.__address = value
Setter for **self.__address** attribute. :param value: Attribute value. :type value: unicode
355,292
def contains(self, key): for store in self._stores: if store.contains(key): return True return False
Returns whether the object is in this datastore.
355,293
def clone(gandi, name, vhost, directory, origin): if vhost != : directory = vhost else: directory = name if not directory else directory return gandi.paas.clone(name, vhost, directory, origin)
Clone a remote vhost in a local git repository.
355,294
def standardize_role(role): role = role.lower() if any(c in role for c in {, , , , , }): return return role
Convert role text into standardized form.
355,295
def _update_options(model, connection=None): ks_name = model._get_keyspace() msg = format_log_context("Checking %s for option differences", keyspace=ks_name, connection=connection) log.debug(msg, model) model_options = model.__options__ or {} table_meta = _get_table_metadata(model, connection=...
Updates the table options for the given model if necessary. :param model: The model to update. :param connection: Name of the connection to use :return: `True`, if the options were modified in Cassandra, `False` otherwise. :rtype: bool
355,296
def super_mro(self): if not isinstance(self.mro_pointer, scoped_nodes.ClassDef): raise exceptions.SuperError( "The first argument to super must be a subtype of " "type, not {mro_pointer}.", super_=self, ) if isinstance(sel...
Get the MRO which will be used to lookup attributes in this super.
355,297
def serialize(self): res = super(Module, self).serialize() cls = self.__class__ for prop in self.__dict__: if prop in cls.properties or prop in cls.running_properties or prop in [, ]: ...
A module may have some properties that are not defined in the class properties list. Serializing a module is the same as serializing an Item but we also also include all the existing properties that are not defined in the properties or running_properties class list. We must also exclude...
355,298
async def build_pool_upgrade_request(submitter_did: str, name: str, version: str, action: str, _sha256: str, _timeout: Optional[int], ...
Builds a POOL_UPGRADE request. Request to upgrade the Pool (sent by Trustee). It upgrades the specified Nodes (either all nodes in the Pool, or some specific ones). :param submitter_did: DID of the submitter stored in secured Wallet. :param name: Human-readable name for the upgrade. :param version: The...
355,299
def clone_workspace(self) -> None: def clone_clicked(text): if text: command = Workspace.CloneWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(command) self.pose_get_string_message_box(caption...
Pose a dialog to name and clone a workspace.