text
stringlengths
78
104k
score
float64
0
0.18
def median(items): """Note: modifies the input list!""" items.sort() k = len(items)//2 if len(items) % 2 == 0: return (items[k] + items[k - 1]) / 2 else: return items[k]
0.004878
def check_base_suggested_attributes(self, dataset): ''' Check the global suggested attributes for 2.0 templates. These go an extra step besides just checking that they exist. :param netCDF4.Dataset dataset: An open netCDF dataset :creator_type = "" ; //............................
0.005034
def crypto_sign_ed25519_sk_to_curve25519(secret_key_bytes): """ Converts a secret Ed25519 key (encoded as bytes ``secret_key_bytes``) to a secret Curve25519 key as bytes. Raises a ValueError if ``secret_key_bytes``is not of length ``crypto_sign_SECRETKEYBYTES`` :param secret_key_bytes: bytes ...
0.001125
def with_header(self, key, value): """Sets a header on the request and returns the request itself. The header key will be canonicalized before use. (see also: canonicalize_header) Keyword arguments: key -- the header's name value -- the string value for the header """ ...
0.007673
def __get_reserve_details(self, account_id, **kwargs): """Call documentation: `/account/get_reserve_details <https://www.wepay.com/developer/reference/account#reserve>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``ac...
0.00565
def _convert_hexstr_base(hexstr, base): r""" Packs a long hexstr into a shorter length string with a larger base. Args: hexstr (str): string of hexidecimal symbols to convert base (list): symbols of the conversion base Example: >>> print(_convert_hexstr_base('ffffffff', _ALPHAB...
0.001018
def check_blas_config(): """ checks to see if using OpenBlas/Intel MKL. If so, warn if the number of threads isn't set to 1 (causes severe perf issues when training - can be 10x slower) """ # don't warn repeatedly global _checked_blas_config if _checked_blas_config: return _checked_blas_...
0.008448
def startprocessmonitor(self, process_name, interval=2): """ Start memory and CPU monitoring, with the time interval between each process scan @param process_name: Process name, ex: firefox-bin. @type process_name: string @param interval: Time interval between each proce...
0.003236
def get_first_model_with_resource_name(cls, resource_name): """ Get the first model corresponding to a resource_name Args: resource_name: the resource name """ models = cls.get_models_with_resource_name(resource_name) if len(models) > 0: return ...
0.005714
def erase_line(method=EraseMethod.ALL, file=sys.stdout): """ Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: ...
0.001445
def main(in_base, out_base, compiled_files, source_files, outfile=None, showasm=None, showast=False, do_verify=False, showgrammar=False, raise_on_error=False, do_linemaps=False, do_fragments=False): """ in_base base directory for input files out_base base directory for output file...
0.001722
def create_section(self, name, overwrite=True): """ create and return a new sub-section of this manifest, with the given Name attribute. If a sub-section already exists with that name, it will be lost unless overwrite is False in which case the existing sub-section will be return...
0.003067
def challenge_hash(peer_challenge, authenticator_challenge, username): """ChallengeHash""" sha_hash = hashlib.sha1() sha_hash.update(peer_challenge) sha_hash.update(authenticator_challenge) sha_hash.update(username) return sha_hash.digest()[:8]
0.003731
def make_full_qualified_url(self, path: str) -> str: """ append application url to path""" return self.application_uri.rstrip('/') + '/' + path.lstrip('/')
0.011696
def prepare_fixed_decimal(data, schema): """Converts decimal.Decimal to fixed length bytes array""" if not isinstance(data, decimal.Decimal): return data scale = schema.get('scale', 0) size = schema['size'] # based on https://github.com/apache/avro/pull/82/ sign, digits, exp = data.as_...
0.000634
def rotateAboutVectorMatrix(vec, theta_deg): """Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should...
0.010453
def readdatacommlst(idfname): """read the idf file""" # iddfile = sys.path[0] + '/EplusCode/Energy+.idd' iddfile = 'Energy+.idd' # iddfile = './EPlusInterfaceFunctions/E1.idd' # TODO : can the path name be not hard coded iddtxt = open(iddfile, 'r').read() block, commlst, commdct = parse_idd.extr...
0.004444
def upload_resumable(self, fd, filesize, filehash, unit_hash, unit_id, unit_size, quick_key=None, action_on_duplicate=None, mtime=None, version_control=None, folder_key=None, filedrop_key=None, path=None, previous_hash=None): """upload/r...
0.003934
def appkit_mouse_process(pipe): """Single subprocess for reading mouse events on Mac using older AppKit.""" # pylint: disable=import-error,too-many-locals # Note Objective C does not support a Unix style fork. # So these imports have to be inside the child subprocess since # otherwise the child pro...
0.000327
def lsfiles(root=".", **kwargs): """ Return only files from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of file paths. Raises: O...
0.001946
def _getEventsByDay(self, request, firstDay, lastDay): """ Return the events in this site for the dates given, grouped by day. """ home = request.site.root_page return getAllEventsByDay(request, firstDay, lastDay, home=home)
0.007576
def bootstrap_ts(y, func, B=1000, b=3): """ Bootstrap a timeseries using a window size:b. """ beta_star = np.empty(B) z = y z_star = np.empty(len(z)) for boot_i in range(B): for block_i, start in enumerate(np.random.randint(len(z) - b + 1, size=len(z) / b)): z_star[block_i * b:(b...
0.004728
def create_header_from_telpars(telpars): """ Create a list of fits header items from GTC telescope pars. The GTC telescope server gives a list of string describing FITS header items such as RA, DEC, etc. Arguments --------- telpars : list list returned by server call to getTelescop...
0.001047
def gross_lev(positions): """ Calculates the gross leverage of a strategy. Parameters ---------- positions : pd.DataFrame Daily net position values. - See full explanation in tears.create_full_tear_sheet. Returns ------- pd.Series Gross leverage. """ e...
0.00237
def _depth_first_search(self, target_id, layer_id_list, node_list): """Search for all the layers and nodes down the path. A recursive function to search all the layers and nodes between the node in the node_list and the node with target_id.""" assert len(node_list) <= self.n_nodes ...
0.004267
def send_result(self, additional_dict): ''' Send a result to the RPC client :param additional_dict: the dictionary with the response ''' self.send_response(200) self.send_header("Content-type", "application/json") response = { 'jsonrpc': self.req_rpc_...
0.003436
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs): """Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data...
0.002169
def import_schema(self, definitions, d): """Import schema as <types/> content.""" if not definitions.types: root = Element("types", ns=wsdlns) definitions.root.insert(root) types = Types(root, definitions) definitions.types.append(types) else: ...
0.004545
def overall_CEN_calc(classes, TP, TOP, P, CEN_dict, modified=False): """ Calculate Overall_CEN (Overall confusion entropy). :param classes: classes :type classes : list :param TP: true positive dict for all classes :type TP : dict :param TOP: test outcome positive :type TOP : dict :...
0.001263
def _defragment_mountpoint(mountpoint): ''' Defragment only one BTRFS mountpoint. ''' out = __salt__['cmd.run_all']("btrfs filesystem defragment -f {0}".format(mountpoint)) return { 'mount_point': mountpoint, 'passed': not out['stderr'], 'log': out['stderr'] or False, ...
0.005848
def hmset_dict(self, key, *args, **kwargs): """Set multiple hash fields to multiple values. dict can be passed as first positional argument: >>> await redis.hmset_dict( ... 'key', {'field1': 'value1', 'field2': 'value2'}) or keyword arguments can be used: >>> awai...
0.001308
def init_app(self, app, entry_point_group='invenio_oauth2server.scopes', **kwargs): """Flask application initialization. :param app: An instance of :class:`flask.Flask`. :param entry_point_group: The entrypoint group name to load plugins. (Default: ``'invenio_oauth2...
0.005618
def make_random_histogram(center=0.0, stdev=default_stdev, length=default_feature_dim, num_bins=default_num_bins): "Returns a sequence of histogram density values that sum to 1.0" hist, bin_edges = np.histogram(get_distr(center, stdev, length), range=edge_range, bins=num_bins...
0.006098
def ls(self, path, offset=None, amount=None): """ Return list of files/directories. Each item is a dict. Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'. """ def parseContent(content): result = [] root = ET.fromstri...
0.008466
def populated_column_map(self): '''Return the _column_map without unused optional fields''' column_map = [] cls = self.model for csv_name, field_pattern in cls._column_map: # Separate the local field name from foreign columns if '__' in field_pattern: ...
0.001867
def _from_wkt(string, wkttype=None, strict=False): """ Internal method for parsing wkt, with minor differences depending on ogc or esri style. Arguments: - *string*: The OGC or ESRI WKT representation as a string. - *wkttype* (optional): How to parse the WKT string, as either 'ogc', 'esri', or Non...
0.006887
def load(kls, url, getter=None, parser=None, url_load_hook=None, sep=consts.private.SCOPE_SEPARATOR, prim=None, mime_codec=None, resolver=None): """ load json as a raw App :param str url: url of path of Swagger API definition :param getter: customized Getter :type getter: sub class/inst...
0.004737
def write(self, proto): """ :param proto: capnp TwoGramModelProto message builder """ super(TwoGramModel, self).writeBaseToProto(proto.modelBase) proto.reset = self._reset proto.learningEnabled = self._learningEnabled proto.prevValues = self._prevValues self._encoder.write(proto.encoder...
0.005747
def _del_subscription(self, a_filter, session): """ Delete a session subscription on a given topic :param a_filter: :param session: :return: """ deleted = 0 try: subscriptions = self._subscriptions[a_filter] for index, (sub_session,...
0.004651
def plot_vs(fignum, Xs, c, ls): """ plots vertical lines at Xs values Parameters _________ fignum : matplotlib figure number Xs : list of X values for lines c : color for lines ls : linestyle for lines """ fig = plt.figure(num=fignum) for xv in Xs: bounds = plt.axis...
0.004662
def get(self, remotepath, localpath, callback=None): """ Copy a remote file (C{remotepath}) from the SFTP server to the local host as C{localpath}. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. @param remotepath:...
0.002058
def _update_collection(self, ctx): """ Bulk update """ assert isinstance(ctx, ResourceQueryContext) models = [] for row in ctx.data: models.append(self._update_one_simple(row.pop('id'), row, ctx)) return models
0.007143
def _load_client_secrets(self, filename): """Loads client secrets from the given filename.""" client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError( 'The flow specified in {0} is not supported.'.format( ...
0.004329
def to_json(self): """ Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_json(), outfile) """ ...
0.004027
def _get_required_param(self, param_name): """Get a required request parameter. Args: param_name: name of request parameter to fetch. Returns: parameter value Raises: errors.NotEnoughArgumentsError: if parameter is not specified. """ value = self.request.get(param_name) ...
0.004717
def all(self, predicate=bool): '''Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: predicate (callable): An optional single argument function used to ...
0.002904
def a_urls(html): ''' return normalized urls found in the 'a' tag ''' soup = BeautifulSoup(html, 'lxml') for node in soup.find_all('a'): try: href = node['href'] except KeyError: continue yield norm_url(href)
0.003623
def find( self, flags = 0 ): """ Looks throught the text document based on the current criteria. The \ inputed flags will be merged with the generated search flags. :param flags | <QTextDocument.FindFlag> :return <bool> | success """ ...
0.020251
def list_tables(source): # pylint: disable=line-too-long """List the names of all tables in this file(s) Parameters ---------- source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list` one or more open files, file paths, or LIGO_LW `Document`s Examples -------- >>> from...
0.000855
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
0.003322
def from_base58_seed(cls, base58_seed): """Generate a :class:`Keypair` object via Base58 encoded seed. .. deprecated:: 0.1.7 Base58 address encoding is DEPRECATED! Use this method only for transition to strkey encoding. :param str base58_seed: A base58 encoded encoded sec...
0.002963
def _add_right(self, d): ''' Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self._left = d.first self._right =...
0.002845
def _compute_forearc_backarc_term(self, C, sites, dists): """ Computes the forearc/backarc scaling term given by equation (4). """ f_faba = np.zeros_like(dists.rhypo) # Term only applies to backarc sites (F_FABA = 0. for forearc) max_dist = dists.rhypo[sites.backarc] ...
0.004193
def dbsafe_encode(value, compress_object=False): """ We use deepcopy() here to avoid a problem with cPickle, where dumps can generate different character streams for same lookup value if they are referenced differently. The reason this is important is because we do all of our lookups as simple ...
0.001563
def delete_service_definition(self, service_type, identifier): """DeleteServiceDefinition. [Preview API] :param str service_type: :param str identifier: """ route_values = {} if service_type is not None: route_values['serviceType'] = self._serialize.ur...
0.005806
def validate_votes(self, validators_H): "set of validators may change between heights" assert self.sender if not self.round_lockset.num_eligible_votes == len(validators_H): raise InvalidProposalError('round_lockset num_eligible_votes mismatch') for v in self.round_lockset: ...
0.007092
def to(self, space): """ Convert color to a different color space. :param str space: Name of the color space. :rtype: Color :returns: A new spectra.Color in the given color space. """ if space == self.space: return self new_color = convert_color(self.col...
0.007177
def sharp_round(data, density, kskip, xc, yc, s2m, s4m, nxk, nyk, datamin, datamax): """ sharp_round -- Compute first estimate of the roundness and sharpness of the detected objects. A Python translation of the AP_SHARP_ROUND IRAF/DAOFIND function. """ # Compute the first estim...
0.002039
def as_tuple(obj): " Given obj return a tuple " if not obj: return tuple() if isinstance(obj, (tuple, set, list)): return tuple(obj) if hasattr(obj, '__iter__') and not isinstance(obj, dict): return obj return obj,
0.003817
def dca(adata, mode='denoise', ae_type='zinb-conddisp', normalize_per_cell=True, scale=True, log1p=True, # network args hidden_size=(64, 32, 64), hidden_dropout=0., batchnorm=True, activation='relu', init='glorot_uniform', n...
0.005559
def plugins(): """Returns a tuple of the plugin classes registered with the python style checker. :rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes """ return ( ClassFactoring, ConstantLogic, ExceptStatements, FutureCompatibility, ImportOrder, ...
0.009747
def current_portfolio_weights(self): """ Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price time...
0.002821
def get_spam_checker(backend_path): """ Return the selected spam checker backend. """ try: backend_module = import_module(backend_path) backend = getattr(backend_module, 'backend') except (ImportError, AttributeError): warnings.warn('%s backend cannot be imported' % backend_p...
0.001953
def ColorWithHue(self, hue): '''Create a new instance based on this one with a new hue. Parameters: :hue: The hue of the new color [0...360]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60) (1.0, 1.0, 0.0, 1.0) >>> Color.NewFromHsl(3...
0.004329
def pattern(self): """ Return the pattern used to check if a field name can be accepted by this dynamic field. Use a default one ('^fieldname_(.+)$') if not set when the field was initialized """ if self.dynamic_version_of is not None: return self.dynamic_vers...
0.00655
def get_magnitude_scaling(self, C, mag): """ Returns the magnitude scaling term """ d_m = mag - self.CONSTANTS["Mh"] if mag < self.CONSTANTS["Mh"]: return C["e1"] + C["b1"] * d_m + C["b2"] * (d_m ** 2.0) else: return C["e1"] + C["b3"] * d_m
0.00641
def poisson_ll_2(p1, p2): """ Calculates Poisson LL(p1|p2). """ p1_1 = p1 + eps p2_1 = p2 + eps return np.sum(-p2_1 + p1_1*np.log(p2_1))
0.00625
def slice_hidden(x, hidden_size, num_blocks): """Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size...
0.010256
def sample_stats_to_xarray(self): """Extract sample_stats from posterior.""" posterior = self.posterior posterior_model = self.posterior_model # copy dims and coords dims = deepcopy(self.dims) if self.dims is not None else {} coords = deepcopy(self.coords) if self.c...
0.003672
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self...
0.003817
def to_dict(self): """ Converts object into a dictionary. """ data = { 'id': self.id, 'referenceId': self.reference_id, 'type': self.type, 'displayName': self.display_name, 'remoteUrl': self.remote_url} for key in data.k...
0.007317
def getmethattr(obj, meth): """ Returns either the variable value or method invocation """ if hasmethod(obj, meth): return getattr(obj, meth)() elif hasvar(obj, meth): return getattr(obj, meth) return None
0.022026
def set_split_extents_by_tile_max_bytes(self): """ Sets split extents (:attr:`split_begs` and :attr:`split_ends`) calculated using from :attr:`max_tile_bytes` (and :attr:`max_tile_shape`, :attr:`sub_tile_shape`, :attr:`halo`). """ self.tile_shape = \ ...
0.002853
def debug_print_tree( self, spacing='' ): ''' *Debug only* method for outputting the tree. ''' print (spacing+" "+str(self.word_id)+" "+str(self.text)) if (self.children): spacing=spacing+" " for child in self.children: child.debug_print_tree(spacing)
0.018987
def panic(self, *args): """ Creates a fatal error and exit """ self._err("fatal", *args) if self.test_errs_mode is False: # pragma: no cover sys.exit(1)
0.009756
def set_scrollbar_position(self, position): """Set scrollbar positions""" # Scrollbars will be restored after the expanded state self._scrollbar_positions = position if self._to_be_loaded is not None and len(self._to_be_loaded) == 0: self.restore_scrollbar_positions()
0.006309
def physical(self): """ get the physical samples values Returns ------- phys : Signal new *Signal* with physical values """ if not self.raw or self.conversion is None: samples = self.samples.copy() else: samples = sel...
0.00232
def list_wegobjecten_by_straat(self, straat): ''' List all `wegobjecten` in a :class:`Straat` :param straat: The :class:`Straat` for which the `wegobjecten` \ are wanted. :rtype: A :class:`list` of :class:`Wegobject` ''' try: id = straat.id ...
0.001776
def _MultiNotifyQueue(self, queue, notifications, mutation_pool=None): """Does the actual queuing.""" notification_list = [] now = rdfvalue.RDFDatetime.Now() for notification in notifications: if not notification.first_queued: notification.first_queued = ( self.frozen_timestamp...
0.008997
def get_frac_coords_from_lll(self, lll_frac_coords: Vector3Like) -> np.ndarray: """ Given fractional coordinates in the lll basis, returns corresponding fractional coordinates in the lattice basis. """ return dot(lll_frac_coords, self.lll_mapping)
0.006969
def plot(self): """ Plot """ self.before_plot() self.do_plot_and_bestfit() self.after_plot() self.do_label() self.after_label() self.save() self.close() return self.outputdict
0.007605
def _wiggle_interval(value, wiggle=0.5 ** 44): r"""Check if ``value`` is in :math:`\left[0, 1\right]`. Allows a little bit of wiggle room outside the interval. Any value within ``wiggle`` of ``0.0` will be converted to ``0.0` and similar for ``1.0``. .. note:: There is also a Fortran imple...
0.000879
def visible_object_layers(self): """ This must return layer objects This is not required for custom data formats. :return: Sequence of pytmx object layers/groups """ return (layer for layer in self.tmx.visible_layers if isinstance(layer, pytmx.TiledObjectGroup))
0.00625
def initialize(address='127.0.0.1:27017', database_name='hfos', instance_name="default", reload=False): """Initializes the database connectivity, schemata and finally object models""" global schemastore global l10n_schemastore global objectmodels global collections global dbhost global dbpo...
0.002749
def get_success_url(self): """ By default we use the referer that was stuffed in our form when it was created """ if self.success_url: # if our smart url references an object, pass that in if self.success_url.find('@') > 0: return smart_url...
0.004695
def init_app_context(): """Initialize app context for Invenio 2.x.""" try: from invenio.base.factory import create_app app = create_app() app.test_request_context('/').push() app.preprocess_request() except ImportError: pass
0.003623
def _coerceSingleRepetition(self, dataSet): """ Make a new liveform with our parameters, and get it to coerce our data for us. """ # make a liveform because there is some logic in _coerced form = LiveForm(lambda **k: None, self.parameters, self.name) return form.f...
0.005917
def FoldByteStream(self, mapped_value, **unused_kwargs): # pylint: disable=redundant-returns-doc """Folds the data type into a byte stream. Args: mapped_value (object): mapped value. Returns: bytes: byte stream. Raises: FoldingError: if the data type definition cannot be folded int...
0.003929
def one_to_many(clsname, **kw): """Use an event to build a one-to-many relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship from the remote table. """ @declared_attr def o2m(cls): cls._references((clsname...
0.002538
def finish_directory_parse(self): # type: () -> None ''' A method to finish up the parsing of this UDF File Entry directory. In particular, this method checks to see if it is in sorted order for future use. Parameters: None. Returns: Nothing. ...
0.008403
def align_chunk_with_ner(tmp_ner_path, i_chunk, tmp_done_path): ''' iterate through the i_chunk and tmp_ner_path to generate a new Chunk with body.ner ''' o_chunk = Chunk() input_iter = i_chunk.__iter__() ner = '' stream_id = None all_ner = xml.dom.minidom.parse(open(tmp_ner_path)) ...
0.004743
def QueryInfoKey(key): """This calls the Windows RegQueryInfoKey function in a Unicode safe way.""" regqueryinfokey = advapi32["RegQueryInfoKeyW"] regqueryinfokey.restype = ctypes.c_long regqueryinfokey.argtypes = [ ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDW...
0.014127
def completerTree( self ): """ Returns the completion tree for this instance. :return <QTreeWidget> """ if not self._completerTree: self._completerTree = QTreeWidget(self) self._completerTree.setWindowFlags(Qt.Popup) self....
0.015152
def get_admin(): ''' Return the actual admin from token file ''' if os.path.isfile(LOGIN_FILENAME): with open(LOGIN_FILENAME, 'r') as token_file: old_login, old_password = token_file.read().splitlines()[:2] return old_login, old_password else: return None,...
0.003077
def update_exif_GEXIV2(oldfile,newfile): """Transfers oldfile's exif to newfile's exif and updates the width/height EXIF fields""" # Requires gexiv2 and pygobject package in gentoo # (USE=introspection) try: from gi.repository import GExiv2 except: print("Couldn't import GExiv...
0.007621
def useful_mimetype(text): """Check to see if the given mime type is a MIME type which is useful in terms of how to treat this file. """ if text is None: return False mimetype = normalize_mimetype(text) return mimetype not in [DEFAULT, PLAIN, None]
0.003571
def scroll_to(self, selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): ''' Fast scroll to destination ''' if self.demo_mode: self.slow_scroll_to(selector, by=by, timeout=timeout) return if self.timeout_multiplier and timeout == settings.SMALL...
0.003623
def memory_write(self, start_position: int, size: int, value: bytes) -> None: """ Write ``value`` to memory at ``start_position``. Require that ``len(value) == size``. """ return self._memory.write(start_position, size, value)
0.011628
def _setBatchSystemEnvVars(self): """ Sets the environment variables required by the job store and those passed on command line. """ for envDict in (self._jobStore.getEnv(), self.config.environment): for k, v in iteritems(envDict): self._batchSystem.setEnv(k, ...
0.009317
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'role') and self.role is not None: _dict['role'] = self.role return _dict
0.00627