Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
20,200
def parse(file_contents, file_name): try: yaml.load(file_contents) except Exception: _, exc_value, _ = sys.exc_info() return("Cannot Parse: {file_name}: \n {exc_value}" .format(file_name=file_name, exc_value=exc_value))
This takes a list of filenames and their paths of expected yaml files and tried to parse them, erroring if there are any parsing issues. Args: file_contents (str): Contents of a yml file Raises: yaml.parser.ParserError: Raises an error if the file contents cannot be ...
20,201
def validate_owner_repo_package(ctx, param, value): form = "OWNER/REPO/PACKAGE" return validate_slashes(param, value, minimum=3, maximum=3, form=form)
Ensure that owner/repo/package is formatted correctly.
20,202
def other_object_webhook_handler(event): if event.parts[:2] == ["charge", "dispute"]: target_cls = models.Dispute else: target_cls = { "charge": models.Charge, "coupon": models.Coupon, "invoice": models.Invoice, "invoiceitem": models.InvoiceItem, "plan": models.Plan, "product": models.P...
Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects. Docs for: - charge: https://stripe.com/docs/api#charges - coupon: https://stripe.com/docs/api#coupons - invoice: https://stripe.com/docs/api#invoices - invoiceitem: https://stripe.com/docs/api#invoiceitems - plan: https:/...
20,203
def freeze(self, dest_dir): for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
Freezes every resource within a context
20,204
def ungeometrize_stops(geo_stops: DataFrame) -> DataFrame: f = geo_stops.copy().to_crs(cs.WGS84) f["stop_lon"], f["stop_lat"] = zip( *f["geometry"].map(lambda p: [p.x, p.y]) ) del f["geometry"] return f
The inverse of :func:`geometrize_stops`. Parameters ---------- geo_stops : GeoPandas GeoDataFrame Looks like a GTFS stops table, but has a ``'geometry'`` column of Shapely Point objects that replaces the ``'stop_lon'`` and ``'stop_lat'`` columns. Returns ------- DataFra...
20,205
async def current_position( self, mount: top_types.Mount, critical_point: CriticalPoint = None) -> Dict[Axis, float]: if not self._current_position: raise MustHomeError async with self._motion_lock: if mount == mount.RIGHT: ...
Return the postion (in deck coords) of the critical point of the specified mount. This returns cached position to avoid hitting the smoothie driver unless ``refresh`` is ``True``. If `critical_point` is specified, that critical point will be applied instead of the default one. ...
20,206
def update(self, arg, allow_overwrite=False): if inspect.isclass(arg) and issubclass(arg, ICatalog) or isinstance(arg, ICatalog): arg = arg._providers if not allow_overwrite: for key in arg: if key in self._providers: raise Ke...
Update our providers from either an ICatalog subclass/instance or a mapping. If arg is an ICatalog, we update from it's ._providers attribute. :param arg: Di/Catalog/Mapping to update from. :type arg: ICatalog or collections.Mapping :param allow_overwrite: If True, allow overwriting ex...
20,207
def calc_effective_permeability(self, inlets=None, outlets=None, domain_area=None, domain_length=None): r phase = self.project.phases()[self.settings[]] d_normal = self._calc_eff_prop(inlets=inlets, outlets=outlets, domai...
r""" This calculates the effective permeability in this linear transport algorithm. Parameters ---------- inlets : array_like The pores where the inlet pressure boundary conditions were applied. If not given an attempt is made to infer them from the ...
20,208
def _inspect(self,obj,objtype=None): gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,): return gen._Dynamic_last else: return gen
Return the last generated value for this parameter.
20,209
def generate_data_for_edit_page(self): if not self.can_edit: return {} if self.edit_form: return self.edit_form.to_dict() return self.generate_simple_data_page()
Generate a custom representation of table's fields in dictionary type if exist edit form else use default representation. :return: dict
20,210
def get_relationship_mdata(): return { : { : { : , : str(DEFAULT_LANGUAGE_TYPE), : str(DEFAULT_SCRIPT_TYPE), : str(DEFAULT_FORMAT_TYPE), }, : { : , : str(DEFAULT_LANGUAGE_...
Return default mdata map for Relationship
20,211
def create_tx(network, spendables, payables, fee="standard", lock_time=0, version=1): Tx = network.tx def _fix_spendable(s): if isinstance(s, Tx.Spendable): return s if not hasattr(s, "keys"): return Tx.Spendable.from_text(s) return Tx.Spendable.from_dict(s...
This function provides the easiest way to create an unsigned transaction. All coin values are in satoshis. :param spendables: a list of Spendable objects, which act as inputs. Each item in the list can be a Spendable, or text from Spendable.as_text, or a dictionary from Spendable.as_dict (whic...
20,212
def add(config, username, filename): try: client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.add(username, user_api, filename) except (ldap3.core.exceptions.LDAPNoSuchAttributeResult,...
Add user's SSH public key to their LDAP entry.
20,213
def map_hmms(input_model, mapping): output_model = copy.copy(input_model) o_hmms = [] for i_hmm in input_model[]: i_hmm_name = i_hmm[] o_hmm_names = mapping.get(i_hmm_name, [i_hmm_name]) for o_hmm_name in o_hmm_names: o_hmm = copy.copy(i_hmm) o_hmm[] =...
Create a new HTK HMM model given a model and a mapping dictionary. :param input_model: The model to transform of type dict :param mapping: A dictionary from string -> list(string) :return: The transformed model of type dict
20,214
def var_window_closed(self, widget): self.action_group.get_action().set_active(False) self.show_vars = False self.var_window = None
Called if user clicked close button on var window :param widget: :return:
20,215
def addvlan(self, vlanid, vlan_name): create_dev_vlan( vlanid, vlan_name, self.auth, self.url, devid = self.devid)
Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name, auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be supported in the HPE IMC Platform VLAN Manager module. :param vlanid: str of VLANId ( valid 1-4094 ) :param vl...
20,216
def get_regulate_amounts(self): p = pb.controlsExpressionWithTemplateReac() s = _bpp() res = s.searchPlain(self.model, p) res_array = [_match_to_array(m) for m in res.toArray()] stmts = [] for res in res_array: c...
Extract INDRA RegulateAmount Statements from the BioPAX model. This method extracts IncreaseAmount/DecreaseAmount Statements from the BioPAX model. It fully reuses BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.controlsExpressionWithTemplateReac pattern to find TemplateReaction...
20,217
def is_full(self): capacity = self.get_true_capacity() if capacity != -1: num_signed_up = self.eighthsignup_set.count() return num_signed_up >= capacity return False
Return whether the activity is full.
20,218
def _log_likelihood_transit_plus_line(theta, params, model, t, data_flux, err_flux, priorbounds): u = [] for ix, key in enumerate(sorted(priorbounds.keys())): if key == : params.rp = theta[ix] elif key == : params.t0 = theta[ix...
Given a batman TransitModel and its proposed parameters (theta), update the batman params object with the proposed parameters and evaluate the gaussian likelihood. Note: the priorbounds are only needed to parse theta.
20,219
def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True): if isinstance(filename, Curve): curve = filename with tempfile.NamedTemporaryFile(, delete=False) as f: curve.save(f) filename = f.name cmdline = ...
Execute autorg. Inputs: filename: either a name of an ascii file, or an instance of Curve. mininterval: the minimum number of points in the Guinier range qminrg: the maximum value of qmin*Rg. Default of autorg is 1.0 qmaxrg: the maximum value of qmax*Rg. Default of autorg is 1.3 ...
20,220
def try_unbuffered_file(file, _alreadyopen={}): try: fileno = file.fileno() except (AttributeError, UnsupportedOperation): return filedesc
Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys.stdout or sys.stderr.
20,221
def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", No...
Scatter plot of 1D histogram.
20,222
def _get_serializer(self, _type): if _type in _serializers: return _serializers[_type] elif _type == : return self._get_array_serializer() elif _type == : return self._get_object_serializer() raise ValueError(.format(_type))
Gets a serializer for a particular type. For primitives, returns the serializer from the module-level serializers. For arrays and objects, uses the special _get_T_serializer methods to build the encoders and decoders.
20,223
def must_be_same(self, klass): if self.__class__ is not klass: self.__class__ = klass self._morph() self.clear()
Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.
20,224
def from_pandas(cls, index): from pandas import Index as PandasIndex check_type(index, PandasIndex) return Index(index.values, index.dtype, index.name)
Create baloo Index from pandas Index. Parameters ---------- index : pandas.base.Index Returns ------- Index
20,225
def pay(self, transactionAmount, senderTokenId, recipientTokenId=None, callerTokenId=None, chargeFeeTo="Recipient", callerReference=None, senderReference=None, recipientReference=None, senderDescription=None, recipientDescription=None, callerDescription=None, ...
Make a payment transaction. You must specify the amount. This can also perform a Reserve request if 'reserve' is set to True.
20,226
def format_dates(self, data, columns): for column in columns: if column in data.columns: data[column] = pandas.to_datetime(data[column]) return data
This method translates columns values into datetime objects :param data: original Pandas dataframe :param columns: list of columns to cast the date to a datetime object :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with updated 'columns'...
20,227
def qubits(self): return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
Return a list of qubits as (QuantumRegister, index) pairs.
20,228
def path_valid(self): valid = [i is not None for i in self.polygons_closed] valid = np.array(valid, dtype=np.bool) return valid
Returns ---------- path_valid: (n,) bool, indexes of self.paths self.polygons_closed which are valid polygons
20,229
def bbox(self): if not hasattr(self, ): data = None for key in (, , ): if key in self.tagged_blocks: data = self.tagged_blocks.get_data(key) assert data is not None rect = data.get(b) self._bbox = ( ...
(left, top, right, bottom) tuple.
20,230
def closest_pair(arr, give="indicies"): idxs = [idx for idx in np.ndindex(arr.shape)] outs = [] min_dist = arr.max() - arr.min() for idxa in idxs: for idxb in idxs: if idxa == idxb: continue dist = abs(arr[idxa] - arr[idxb]) if dist == min...
Find the pair of indices corresponding to the closest elements in an array. If multiple pairs are equally close, both pairs of indicies are returned. Optionally returns the closest distance itself. I am sure that this could be written as a cheaper operation. I wrote this as a quick and dirty method be...
20,231
def reflect_table(engine, klass): try: meta = MetaData() meta.reflect(bind=engine) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) table = None for tb in klass.tables(): if tb in meta.tables: table = me...
Inspect and reflect objects
20,232
def read_rows(self, rows, **keys): if rows is None: return self._read_all() if self._info[] == ASCII_TBL: keys[] = rows return self.read(**keys) rows = self._extract_rows(rows) dtype, offsets, isvar = self.get_rec_dtype(**keys) ...
Read the specified rows. parameters ---------- rows: list,array A list or array of row indices. vstorage: string, optional Over-ride the default method to store variable length columns. Can be 'fixed' or 'object'. See docs on fitsio.FITS for details...
20,233
def create_logger(): global logger formatter = logging.Formatter() handler = TimedRotatingFileHandler(log_file, when="midnight", interval=1) handler.setFormatter(formatter) handler.setLevel(log_level) handler.suffix = "%Y-%m-%d" logger = logging.getLogger("sacplus") logger.setLevel...
Initial the global logger variable
20,234
def _parse_message(self, data): match = self._regex.match(str(data)) if match is None: raise InvalidMessageError(.format(data)) header, self.bitfield, self.numeric_code, self.panel_data, alpha = match.group(1, 2, 3, 4, 5) is_bit_set = lambda bit: not self.bitfield...
Parse the message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
20,235
def editor_interfaces(self): return ContentTypeEditorInterfacesProxy(self._client, self.space.id, self._environment_id, self.id)
Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_inter...
20,236
def settimeout(self, timeout): self.sock_opt.timeout = timeout if self.sock: self.sock.settimeout(timeout)
Set the timeout to the websocket. timeout: timeout time(second).
20,237
def is_equal_to_ignoring_case(self, other): if not isinstance(self.val, str_types): raise TypeError() if not isinstance(other, str_types): raise TypeError() if self.val.lower() != other.lower(): self._err( % (self.val, other)) return self
Asserts that val is case-insensitive equal to other.
20,238
def find_step_impl(self, step): result = None for si in self.steps[step.step_type]: matches = si.match(step.match) if matches: if result: raise AmbiguousStepImpl(step, result[0], si) args = [self._apply_transforms(arg,...
Find the implementation of the step for the given match string. Returns the StepImpl object corresponding to the implementation, and the arguments to the step implementation. If no implementation is found, raises UndefinedStepImpl. If more than one implementation is found, raises AmbiguousStepIm...
20,239
def padDigitalData(self, dig_data, n): n = int(n) l0 = len(dig_data) if l0 % n == 0: return dig_data else: ladd = n - (l0 % n) dig_data_add = np.zeros(ladd, dtype="uint32") dig_data_add.fill(dig_data[-1]) return np.co...
Pad dig_data with its last element so that the new array is a multiple of n.
20,240
def delete_namespaced_pod_preset(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_namespaced_pod_preset_with_http_info(name, namespace, **kwargs) else: (data) = self.delete_namespaced_pod_preset_with_http_info(name, namesp...
delete_namespaced_pod_preset # noqa: E501 delete a PodPreset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_pod_preset(name, namespace, async_req=True) >>...
20,241
def get_output_metadata(self, path, filename): checksums = get_checksums(path, []) metadata = {: filename, : os.path.getsize(path), : checksums[], : } if self.metadata_only: metadata[] = True return metad...
Describe a file by its metadata. :return: dict
20,242
def built(name, runas, dest_dir, spec, sources, tgt, template=None, deps=None, env=None, results=None, force=False, saltenv=, log_dir=): nocheck ret = {: name, : {}, : , ...
Ensure that the named package is built and exists in the named directory name The name to track the build, the name value is otherwise unused runas The user to run the build process as dest_dir The directory on the minion to place the built package(s) spec The locatio...
20,243
async def create( cls, interface: Interface, mode: LinkMode, subnet: Union[Subnet, int] = None, ip_address: str = None, force: bool = False, default_gateway: bool = False): if not isinstance(interface, Interface): raise TypeError( "interfa...
Create a link on `Interface` in MAAS. :param interface: Interface to create the link on. :type interface: `Interface` :param mode: Mode of the link. :type mode: `LinkMode` :param subnet: The subnet to create the link on (optional). :type subnet: `Subnet` or `int` ...
20,244
def _build(self, x, prev_state): x.get_shape().with_rank(2) self._batch_size = x.get_shape().as_list()[0] self._dtype = x.dtype x_zeros = tf.concat( [x, tf.zeros( shape=(self._batch_size, 1), dtype=self._dtype)], 1) x_ones = tf.concat( [x, tf.ones( shape...
Connects the core to the graph. Args: x: Input `Tensor` of shape `(batch_size, input_size)`. prev_state: Previous state. This could be a `Tensor`, or a tuple of `Tensor`s. Returns: The tuple `(output, state)` for this core. Raises: ValueError: if the `Tensor` `x` does no...
20,245
def get_full_xml_representation(entity, private_key): from federation.entities.diaspora.mappers import get_outbound_entity diaspora_entity = get_outbound_entity(entity, private_key) xml = diaspora_entity.to_xml() return "<XML><post>%s</post></XML>" % etree.tostring(xml).decode("utf-8")
Get full XML representation of an entity. This contains the <XML><post>..</post></XML> wrapper. Accepts either a Base entity or a Diaspora entity. Author `private_key` must be given so that certain entities can be signed.
20,246
def glob(patterns, parent=None, excludes=None, include_dotfiles=False, ignore_false_excludes=False): if not glob2: raise glob2_ext if isinstance(patterns, str): patterns = [patterns] if not parent: parent = os.getcwd() result = [] for pattern in patterns: if not os.path.isabs(p...
Wrapper for #glob2.glob() that accepts an arbitrary number of patterns and matches them. The paths are normalized with #norm(). Relative patterns are automaticlly joined with *parent*. If the parameter is omitted, it defaults to the current working directory. If *excludes* is specified, it must be a string or...
20,247
def convertnumbers(table, strict=False, **kwargs): return convertall(table, numparser(strict), **kwargs)
Convenience function to convert all field values to numbers where possible. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar', 'baz', 'quux'], ... ['1', '3.0', '9+3j', 'aaa'], ... ['2', '1.3', '7+2j', None]] >>> table2 = etl.convertnumbers(table1)...
20,248
def create_image_lists(image_dir, testing_percentage, validation_percentage): if not tf.gfile.Exists(image_dir): tf.logging.error("Image directory not found.") return None result = collections.OrderedDict() sub_dirs = sorted(x[0] for x in tf.gfile.Walk(image_dir)) is_root_dir = True for sub_dir...
Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images for each label and their paths. Args: image_dir: String path to a folder conta...
20,249
def textFileStream(self, directory): return DStream(self._jssc.textFileStream(directory), self, UTF8Deserializer())
Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as text files. Files must be wrriten to the monitored directory by "moving" them from another location within the same file system. File names starting with . are ignored. The text files mus...
20,250
def coord(self, offset=(0,0)): (tilex, tiley) = self.tile (offsetx, offsety) = offset world_tiles = 1<<self.zoom x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1 y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1 lon = x * 180.0 y = math.exp(-y*2*math.pi) e = (y-1)/(y+1) l...
return lat,lon within a tile given (offsetx,offsety)
20,251
def dict(self): json_list = [] for step in self.steps: json_list.append(step.dict) return json_list
the python object for rendering json. It is called dict to be coherent with the other modules but it actually returns a list :return: the python object for rendering json :rtype: list
20,252
def visit_set(self, node): return "{%s}" % ", ".join(child.accept(self) for child in node.elts)
return an astroid.Set node as string
20,253
def get_institute_graph_url(start, end): filename = get_institute_graph_filename(start, end) urls = { : urlparse.urljoin(GRAPH_URL, filename + ".png"), : urlparse.urljoin(GRAPH_URL, filename + ".csv"), } return urls
Pie chart comparing institutes usage.
20,254
def ppo_original_world_model(): hparams = ppo_original_params() hparams.policy_network = "next_frame_basic_deterministic" hparams_keys = hparams.values().keys() video_hparams = basic_deterministic_params.next_frame_basic_deterministic() for (name, value) in six.iteritems(video_hparams.values()): if nam...
Atari parameters with world model as policy.
20,255
def ConfigureViewTypeChoices( self, event=None ): self.viewTypeTool.SetItems( getattr( self.loader, , [] )) if self.loader and self.viewType in self.loader.ROOTS: self.viewTypeTool.SetSelection( self.loader.ROOTS.index( self.viewType )) def chooser( typ...
Configure the set of View types in the toolbar (and menus)
20,256
def _log(self, s): r sys.stderr.write(s) sys.stderr.flush()
r"""Log a string. It flushes but doesn't append \n, so do that yourself.
20,257
def show(parent=None, targets=[], modal=None, auto_publish=False, auto_validate=False): if modal is None: modal = bool(os.environ.get("PYBLISH_QML_MODAL", False)) install(modal) show_settings = settings.to_dict() show_settings[] = auto_publish show_settings[] = auto_validat...
Attempt to show GUI Requires install() to have been run first, and a live instance of Pyblish QML in the background. Arguments: parent (None, optional): Deprecated targets (list, optional): Publishing targets modal (bool, optional): Block interactions to parent
20,258
def storage_set(self, key, value): if not self._module: return self._storage_init() module_name = self._module.module_full_name return self._storage.storage_set(module_name, key, value)
Store a value for the module.
20,259
def set_iscsi_volume(self, port_id, initiator_iqn, initiator_dhcp=False, initiator_ip=None, initiator_netmask=None, target_dhcp=False, target_iqn=None, target_ip=None, target_port=3260, target_lun=0, boot_prio=1, ...
Set iSCSI volume information to configuration. :param port_id: Physical port ID. :param initiator_iqn: IQN of initiator. :param initiator_dhcp: True if DHCP is used in the iSCSI network. :param initiator_ip: IP address of initiator. None if DHCP is used. :param initiator_netmask...
20,260
def logical_downlinks(self): if not self.__logical_downlinks: self.__logical_downlinks = LogicalDownlinks( self.__connection) return self.__logical_downlinks
Gets the LogicalDownlinks API client. Returns: LogicalDownlinks:
20,261
def mod_repo(repo, saltenv=, **kwargs): t be updated unless another change is made at the same time. Keys should be properly added on initial configuration. CLI Examples: .. code-block:: bash salt pkg.mod_repo uri=http://new/uri salt pkg.mod_repo comps=main,universe refres...
Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the definition is well formed. For Ubuntu the ``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be used to create a new repository. The following options are available to modify a repo...
20,262
def remove(self, key, where=None, start=None, stop=None): where = _ensure_term(where, scope_level=1) try: s = self.get_storer(key) except KeyError: raise except Exception: if where is not None: raise ValueError( ...
Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection st...
20,263
def vtableEqual(a, objectStart, b): N.enforce_number(objectStart, N.UOffsetTFlags) if len(a) * N.VOffsetTFlags.bytewidth != len(b): return False for i, elem in enumerate(a): x = encode.Get(packer.voffset, b, i * N.VOffsetTFlags.bytewidth) if x == 0 and elem == 0: ...
vtableEqual compares an unwritten vtable to a written vtable.
20,264
def convert_units(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation,**kwargs): if numpy.isscalar(values): values = [values] float_values = [float(value) for value in values] values_to_return = convert(float_values, source_measure_or_unit_abbreviation, tar...
Convert a value from one unit to another one. Example:: >>> cli = PluginLib.connect() >>> cli.service.convert_units(20.0, 'm', 'km') 0.02 Parameters: values: single measure or an array of measures source_measure_or_unit_abbreviation: A measur...
20,265
def exists(self): if self.name in ("", "/") and self.parent is None: return True else: return self in self.parent.directories
Check whether the directory exists on the camera.
20,266
def clean(self, list_article_candidates): results = [] for article_candidate in list_article_candidates: article_candidate.title = self.do_cleaning(article_candidate.title) article_candidate.description = self.do_cleaning(article_candidate.description) ...
Iterates over each article_candidate and cleans every extracted data. :param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted :return: A list, the list with the cleaned ArticleCandidate-Objects
20,267
def face_subset(self, face_index): if self.defined: result = ColorVisuals( face_colors=self.face_colors[face_index]) else: result = ColorVisuals() return result
Given a mask of face indices, return a sliced version. Parameters ---------- face_index: (n,) int, mask for faces (n,) bool, mask for faces Returns ---------- visual: ColorVisuals object containing a subset of faces.
20,268
def _register_options(self, api_interface): op_paths = api_interface.op_paths(collate_methods=True) for path, operations in op_paths.items(): if api.Method.OPTIONS not in operations: self._options_operation(api_interface, path, operations.keys())
Register CORS options endpoints.
20,269
def encode_schedule(schedule): interpolation, steps, pmfs = schedule return interpolation + + .join( + str(s) + + .join(map(str, p)) for s, p in zip(steps, pmfs))
Encodes a schedule tuple into a string. Args: schedule: A tuple containing (interpolation, steps, pmfs), where interpolation is a string specifying the interpolation strategy, steps is an int array_like of shape [N] specifying the global steps, and pmfs is an array_like of shape [N, M] where pm...
20,270
def create(cls, name, servers=None, time_range=, all_logs=False, filter_for_delete=None, comment=None, **kwargs): if not servers: servers = [svr.href for svr in ManagementServer.objects.all()] servers.extend([svr.href for svr in LogServer.objects.all()]) e...
Create a new delete log task. Provide True to all_logs to delete all log types. Otherwise provide kwargs to specify each log by type of interest. :param str name: name for this task :param servers: servers to back up. Servers must be instances of management servers o...
20,271
def _fill_cropping(self, image_size, view_size): def aspect_ratio(width, height): return width / height ar_view = aspect_ratio(*view_size) ar_image = aspect_ratio(*image_size) if ar_view < ar_image: crop = (1.0 - (ar_view/ar_image)) / 2.0 ...
Return a (left, top, right, bottom) 4-tuple containing the cropping values required to display an image of *image_size* in *view_size* when stretched proportionately. Each value is a percentage expressed as a fraction of 1.0, e.g. 0.425 represents 42.5%. *image_size* and *view_size* are ...
20,272
def editpermissions_user_view(self, request, user_id, forum_id=None): user_model = get_user_model() user = get_object_or_404(user_model, pk=user_id) forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None context = self.get_forum_perms_base_context(request,...
Allows to edit user permissions for the considered forum. The view displays a form to define which permissions are granted for the given user for the considered forum.
20,273
def article(request, slug): tree = request.current_page.get_public_object() if tree.application_urls != : return page(request, slug) draft = use_draft(request) and request.user.has_perm() preview = in request.GET and request.user.has_perm() site = tree.n...
The main view of the Django-CMS Articles! Takes a request and a slug, renders the article.
20,274
def recall(self, label=None): if label is None: return self.call("recall") else: return self.call("recall", float(label))
Returns recall or recall for a given label (category) if specified.
20,275
def estimate_tx_gas_with_safe(self, safe_address: str, to: str, value: int, data: bytes, operation: int, block_identifier=) -> int: data = data or b def parse_revert_data(result: bytes) -> int: g...
Estimate tx gas using safe `requiredTxGas` method :return: int: Estimated gas :raises: CannotEstimateGas: If gas cannot be estimated :raises: ValueError: Cannot decode received data
20,276
def decode(self, dataset_split=None, decode_from_file=False, checkpoint_path=None): if decode_from_file: decoding.decode_from_file(self._estimator, self._decode_hparams.decode_from_file, self._hparams, ...
Decodes from dataset or file.
20,277
def dispose(json_str): result_str = list(json_str) escaped = False normal = True sl_comment = False ml_comment = False quoted = False a_step_from_comment = False a_step_from_comment_away = False former_index = None for index, char in enumerate(json_str): if escap...
Clear all comments in json_str. Clear JS-style comments like // and /**/ in json_str. Accept a str or unicode as input. Args: json_str: A json string of str or unicode to clean up comment Returns: str: The str without comments (or unicode if you pass in unicode)
20,278
def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor: if span_start_logits.dim() != 2 or span_end_logits.dim() != 2: raise ValueError("Input shapes must be (batch_size, passage_length)") batch_size, passage_length = span_start_logits.size() device = ...
This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()`` in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can directly import this function without the class. We call the inputs "logits" - they could either be unnormalized logits or normaliz...
20,279
def validateElement(self, ctxt, elem): if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlValidateElement(ctxt__o, self._o, elem__o) return ret
Try to validate the subtree under an element
20,280
async def create(gc: GroupControl, name, slaves): click.echo("Creating group %s with slaves: %s" % (name, slaves)) click.echo(await gc.create(name, slaves))
Create new group
20,281
def main(argv=sys.argv, stream=sys.stderr): args = parse_args(argv) suite = build_suite(args) runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream) result = runner.run(suite) return get_status(result)
Entry point for ``tappy`` command.
20,282
def find_next_candidate(self): try: return self.candidates.pop() except IndexError: pass try: node = self.top_targets_left.pop() except IndexError: return None self.current_top = node alt, message = node.alter_targe...
Returns the next candidate Node for (potential) evaluation. The candidate list (really a stack) initially consists of all of the top-level (command line) targets provided when the Taskmaster was initialized. While we walk the DAG, visiting Nodes, all the children that haven't finished ...
20,283
def reflect_filter(sources, model, cache=None): targets = [reflect(source, model, cache=cache) for source in sources] return [target for target in targets if target is not None]
Returns the list of reflections of objects in the `source` list to other class. Objects that are not found in target table are silently discarded.
20,284
def upload_headimg(self, account, media_file): return self._post( , params={ : account }, files={ : media_file } )
上传客服账号头像 详情请参考 http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html :param account: 完整客服账号 :param media_file: 要上传的头像文件,一个 File-Object :return: 返回的 JSON 数据包
20,285
def replicate_global_dbs(cloud_url=None, local_url=None): local_url = local_url or config["local_server"]["url"] cloud_url = cloud_url or config["cloud_server"]["url"] server = Server(local_url) for db_name in global_dbs: server.replicate( db_name, urljoin(cloud_url, db_name), d...
Set up replication of the global databases from the cloud server to the local server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing the cloud server :param str local_url: Used to override the local u...
20,286
def frozen_stats_from_tree(tree): if not tree: raise ValueError() stats_index = [] for parent_offset, members in tree: stats = FrozenStatistics(*members) stats_index.append(stats) if parent_offset is not None: stats_index[parent_offset].children.append(stats)...
Restores a statistics from the given flat members tree. :func:`make_frozen_stats_tree` makes a tree for this function.
20,287
def lock(self, session, lock_type, timeout, requested_key=None): try: sess = self.sessions[session] except KeyError: return StatusCode.error_invalid_object return sess.lock(lock_type, timeout, requested_key)
Establishes an access mode to the specified resources. Corresponds to viLock function of the VISA library. :param session: Unique logical identifier to a session. :param lock_type: Specifies the type of lock requested, either Constants.EXCLUSIVE_LOCK or Constants.SHARED_LOCK. :param ti...
20,288
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0): phalf = np.zeros((arr.shape[0] + 1, arr.shape[1], arr.shape[2])) phalf[0] = val_toa phalf[-1] = val_sfc phalf[1:-1] = 0.5*(arr[:-1] + arr[1:]) return phalf
Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere.
20,289
def list_running_zones(self): self.update_controller_info() if self.running is None or not self.running: return None return int(self.running[0][])
Returns the currently active relay. :returns: Returns the running relay number or None if no relays are active. :rtype: string
20,290
def editors(self, value): warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE), DeprecationWarning, ) self[EDITOR_ROLE] = value
Update editors. DEPRECATED: use ``policy["roles/editors"] = value`` instead.
20,291
def unnest(c, elem, ignore_whitespace=False): parent = elem.getparent() gparent = parent.getparent() index = parent.index(elem) preparent = etree.Element(parent.tag) preparent.text, parent.text = (parent.text or ), for k in parent.attrib.keys(): ...
unnest the element from its parent within doc. MUTABLE CHANGES
20,292
def create_venv_with_package(packages): with tempfile.TemporaryDirectory() as tempdir: myenv = create(tempdir, with_pip=True) pip_call = [ myenv.env_exe, "-m", "pip", "install", ] subprocess.check_call(pip_call + [, ]) if p...
Create a venv with these packages in a temp dir and yielf the env. packages should be an iterable of pip version instructio (e.g. package~=1.2.3)
20,293
def _get_parent(root): elem = root while True: elem = elem.getparent() if elem.tag in [, ]: return elem
Returns root element for a list. :Args: root (Element): lxml element of current location :Returns: lxml element representing list
20,294
def _encrypt(self, dec, password=None): if AES is None: raise ImportError("PyCrypto required") if password is None: password = self.password if password is None: raise ValueError( "Password need to be provided to create encrypted arc...
Internal encryption function Uses either the password argument for the encryption, or, if not supplied, the password field of the object :param dec: a byte string representing the to be encrypted data :rtype: bytes
20,295
def _rdumpq(q,size,value,encoding=None): write = q.appendleft if value is None: write("0:~") return size + 3 if value is True: write("4:true!") return size + 7 if value is False: write("5:false!") return size + 8 if isinstance(value,(int,long)): ...
Dump value as a tnetstring, to a deque instance, last chunks first. This function generates the tnetstring representation of the given value, pushing chunks of the output onto the given deque instance. It pushes the last chunk first, then recursively generates more chunks. When passed in the current ...
20,296
def get_channel_groups(self, channel_ids): groups = [] for channel_id in channel_ids: group = self.get_channel_property(channel_id, ) groups.append(group) return groups
This function returns the group of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be returned Returns ---------- groups: array_like Returns a list of cor...
20,297
def has_descriptor(self, descriptor): for p in self.descriptors: if p in descriptor: return True return False
Return ``True`` if the character has the given descriptor. :param IPADescriptor descriptor: the descriptor to be checked against :rtype: bool
20,298
def makeFrequencyPanel(allFreqs, patientName): titles = sorted( iter(allFreqs.keys()), key=lambda title: (allFreqs[title][], title)) origMaxY = 0 cols = 6 rows = len(allFreqs) figure, ax = plt.subplots(rows, cols, squeeze=False) substitutions = [, , , , , ] colors = [, ...
For a title, make a graph showing the frequencies. @param allFreqs: result from getCompleteFreqs @param patientName: A C{str}, title for the panel
20,299
def find_service_by_type(self, service_type): for service in self._services: if service_type == service.type: return service return None
Get service for a given service type. :param service_type: Service type, ServiceType :return: Service