text
stringlengths
78
104k
score
float64
0
0.18
def update(self, collection_id, title=None, description=None, private=False): """ Update an existing collection belonging to the logged-in user. This requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param title [string]: The ...
0.00346
def add_config(): """ Prompts user for API keys, adds them in an .ini file stored in the same location as that of the script """ genius_key = input('Enter Genius key : ') bing_key = input('Enter Bing key : ') CONFIG['keys']['bing_key'] = bing_key CONFIG['keys']['genius_key'] = genius_k...
0.002481
def feed(self, data): """ Main method for purifying HTML (overrided) """ self.reset_purified() HTMLParser.feed(self, data) return self.html()
0.010582
def default_value_setter(field): """ When setting to the name of the field itself, the value in the current language will be set. """ def default_value_func_setter(self, value): localized_field = utils.build_localized_field_name( field, self._linguist.active_language ) ...
0.002481
def get_copy_token( self, bucket: str, key: str, cloud_checksum: str, ) -> typing.Any: """ Given a bucket, key, and the expected cloud-provided checksum, retrieve a token that can be passed into :func:`~cloud_blobstore.BlobStore.copy` that guar...
0.008535
def get_all_terms(self): """ Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index """ if not self._canvas_account_id: raise MissingAccountID() params = {"workflow_state": 'all', 'per_page'...
0.003175
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows ...
0.007235
def extract_attribute(module_name, attribute_name): """Extract metatdata property from a module""" with open('%s/__init__.py' % module_name) as input_file: for line in input_file: if line.startswith(attribute_name): return ast.literal_eval(line.split('=')[1].strip())
0.003215
def normalize(text, mode='NFKC', ignore=''): """Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana, Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII and DIGIT. Additionally, Full-width wave dash (〜) etc. are normalized Parameters ---------- text : str ...
0.004205
def get_proxy(self, input_): """Gets a proxy. :param input: a proxy condition :type input: ``osid.proxy.ProxyCondition`` :return: a proxy :rtype: ``osid.proxy.Proxy`` :raise: ``NullArgument`` -- ``input`` is ``null`` :raise: ``OperationFailed`` -- unable to compl...
0.002138
def values_export(self, **params): """ Method for `Export Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Export-Values-from-all-Data-Streams-of-a-Device>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listi...
0.007553
def GET_save_conditionvalues(self) -> None: """Save the |StateSequence| and |LogSequence| object values of the current |HydPy| instance for the current simulation endpoint.""" state.conditions[self._id] = state.conditions.get(self._id, {}) state.conditions[self._id][state.idx2] = state.h...
0.006024
def search_image(name=None, path=['.']): """ look for the image real path, if name is None, then return all images under path. @return system encoded path string FIXME(ssx): this code is just looking wired. """ name = strutils.decode(name) for image_dir in path: if not os.path.isdir...
0.002725
def get_MAD(tau): """ input: eigenvalues of PCA matrix output: Maximum Angular Deviation """ # tau is ordered so that tau[0] > tau[1] > tau[2] for t in tau: if isinstance(t, complex): return -999 MAD = math.degrees(numpy.arctan(numpy.sqrt(old_div((tau[1] + tau[2]), tau[0]...
0.008824
def disconnect(self, message=""): """Hang up the connection. Arguments: message -- Quit message. """ try: del self.connected except AttributeError: return self.quit(message) self.transport.close() self._handle_event(...
0.005435
def replaceAll(self): """ Replace all matches after the current cursor position. This method calls ``replaceSelectedText`` until it returns **False**, and then closes the mini buffer. """ while self.replaceSelected(): pass self.qteWidget.SCISetStylin...
0.005181
def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name...
0.001445
def basic_ack(self, delivery_tag, multiple=False): """Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific m...
0.001053
def get_plot_data(self): """ Generates the JSON report to plot the gene boxes Following the convention of the reports platform, this method returns a list of JSON/dict objects with the information about each entry in the abricate file. The information contained in this JSON is:: ...
0.000864
def _mp_run_check(tasks, results, options): """ a helper function for multiprocessing with DistReport. """ try: for index, change in iter(tasks.get, None): # this is the part that takes up all of our time and # produces side-effects like writing out files for all of ...
0.001119
def add_layer(self, depth, soil): """ Adds a soil to the SoilProfile at a set depth. Note, the soils are automatically reordered based on depth from surface. :param depth: depth from surface to top of soil layer :param soil: Soil object """ self._layers[depth] ...
0.003215
def combine_dfs(dfs, names, method): """Combine dataframes. Combination is either done simple by just concatenating the DataFrames or performs tracking by adding the name of the dataset as a column.""" if method == "track": res = list() for df, identifier in zip(dfs, names): ...
0.001996
def mod_hostname(hostname): ''' Modify hostname .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) CLI Example: .. code-block:: bash salt '*' network.mod_hostname master.saltstack.com ''' # # SunOS tested on SmartOS and OmniOS (Solaris...
0.001277
def to_flat_graph(self): """Convert the parsed manifest to the 'flat graph' that the compiler expects. Kind of hacky note: everything in the code is happy to deal with macros as ParsedMacro objects (in fact, it's been changed to require that), so those can just be returned witho...
0.003257
def get_device_model(): """ Returns the Device model that is active in this project. """ try: return apps.get_model(settings.GCM_DEVICE_MODEL) except ValueError: raise ImproperlyConfigured("GCM_DEVICE_MODEL must be of the form 'app_label.model_name'") except LookupError: ...
0.006452
def flatten(self, max_value: int) -> FrozenSet[int]: """Return a set of all values contained in the sequence set. Args: max_value: The maximum value, in place of any ``*``. """ return frozenset(self.iter(max_value))
0.007663
async def create_task(app: web.Application, coro: Coroutine, *args, **kwargs ) -> asyncio.Task: """ Convenience function for calling `TaskScheduler.create(coro)` This will use the default `TaskScheduler` to create a new background task. ...
0.001045
def load_operator(self, operator): """|coro| Loads the players stats for the operator Parameters ---------- operator : str the name of the operator Returns ------- :class:`Operator` the operator object found""" location =...
0.004709
async def send_upstream(self, message, stream_name=None): """ Send a message upstream to a de-multiplexed application. If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream steams. """ if stream_name is None: ...
0.006015
def as_alias_handler(alias_list): """Returns a list of all the names that will be called.""" list_ = list() for alias in alias_list: if alias.asname: list_.append(alias.asname) else: list_.append(alias.name) return list_
0.003623
def run(self): '''Run listener ''' self.running = True for msg in self.recv(1): if msg is None: if self.running: continue else: break self.logger.debug("New message received: %s", str(msg))...
0.005634
def storage_class(self, value): """Set the storage class for the bucket. See https://cloud.google.com/storage/docs/storage-classes :type value: str :param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABIL...
0.003968
def _create_slack_with_env_var(env_var: EnvVar) -> SlackClient: """ Create a :obj:`SlackClient` with a token from an env var. """ token = os.getenv(env_var) if token: return SlackClient(token=token) raise MissingToken(f"Could not acquire token from {env_var}")
0.003521
def get_field_value(obj, field): """ Gets the value of a given model instance field. :param obj: The model instance. :type obj: Model :param field: The field you want to find the value of. :type field: Any :return: The value of the field as a string. :rtype: str """ if isinstance...
0.003717
def returner(ret): ''' Return data to a mysql server ''' # if a minion is returning a standalone job, get a jobid if ret['jid'] == 'req': ret['jid'] = prep_jid(nocache=ret.get('nocache', False)) save_load(ret['jid'], ret) try: with _get_serv(ret, commit=True) as cur: ...
0.002114
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ trust_ref = None cf_data_ref = None result = None try: trust_ref_pointer = new(Security, 'SecTrustRef *') result ...
0.001856
def reflect(x, y, x0, y0, d=1.0, a=180): """ Returns the reflection of a point through origin (x0,y0). """ return coordinates(x0, y0, d * distance(x0, y0, x, y), a + angle(x0, y0, x, y))
0.004444
def send_message(self, body, to, quiet=False, html_body=None): """Send a message to a single member""" if to.get('MUTED'): to['QUEUED_MESSAGES'].append(body) else: if not quiet: logger.info('message on %s to %s: %s' % (self.name, to['JID'], body)) ...
0.008108
def download_preview(self, image, url_field='url'): """Downlaod the binary data of an image attachment at preview size. :param str url_field: the field of the image with the right URL :return: binary image data :rtype: bytes """ return self.download(image, url_field=url...
0.005797
def destroy(name, call=None): """ This function irreversibly destroys a virtual machine on the cloud provider. Before doing so, it should fire an event on the Salt event bus. The tag for this event is `salt/cloud/<vm name>/destroying`. Once the virtual machine has been destroyed, another event is f...
0.00157
def macro_create(self, args: argparse.Namespace) -> None: """Create or overwrite a macro""" # Validate the macro name valid, errmsg = self.statement_parser.is_valid_command(args.name) if not valid: self.perror("Invalid macro name: {}".format(errmsg), traceback_war=False) ...
0.004512
def health_check(self): """Gets a single item to determine if Dynamo is functioning.""" logger.debug('Health Check on Table: {namespace}'.format( namespace=self.namespace )) try: self.get_all() return True except ClientError as e: ...
0.004515
def path_to_pattern(path, metadata=None): """ Remove source information from path when using chaching Returns None if path is not str Parameters ---------- path : str Path to data optionally containing format_strings metadata : dict, optional Extra arguments to the class, c...
0.002584
def refresh_entitlement(owner, repo, identifier, show_tokens): """Refresh an entitlement in a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_refresh_with_http_info( owner=owner, repo=repo, identifier=identifier, sh...
0.004684
def files_comments_add(self, *, comment: str, file: str, **kwargs) -> SlackResponse: """Add a comment to an existing file. Args: comment (str): The body of the comment. e.g. 'Everyone should take a moment to read this file.' file (str): The file id. e.g. 'F123446...
0.006536
def gif_summary(name, tensor, max_outputs=3, fps=10, collections=None, family=None): """Outputs a `Summary` protocol buffer with gif animations. Args: name: Name of the summary. tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width, channels]` where `channels` is 1...
0.005587
def price_projection(price_data=price_data(), ex_best_offers_overrides=ex_best_offers_overrides(), virtualise=True, rollover_stakes=False): """ Selection criteria of the returning price data. :param list price_data: PriceData filter to specify what market data we wish to receive. :p...
0.006353
def get_instance(self, payload): """ Build an instance of AllTimeInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance...
0.011574
def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None, featuretypes_to_ignore=None): """ Cleans a GFF file by removing features on unwanted chromosomes and of unwanted featuretypes. Optionally adds "chr" to chrom names. """ logger.info("Cleaning GFF") chroms_to_ignore =...
0.001302
def pluralize(singular): """Return plural form of given lowercase singular word (English only). Based on ActiveState recipe http://code.activestate.com/recipes/413172/ >>> pluralize('') '' >>> pluralize('goose') 'geese' >>> pluralize('dolly') 'dollies' >>> pluralize('genius') 'g...
0.001376
def main(): """Start the poor_consumer.""" try: opts, args = getopt.getopt(sys.argv[1:], "h:v", ["help", "nack=", "servers=", "queues="]) except getopt.GetoptError as err: print str(err) usage() sys.exit() # defaults nack = 0.0 ...
0.000704
def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = [ke...
0.003824
def select(sockets, remain=None): """This function is called during sendrecv() routine to select the available sockets. """ if remain is not None: max_timeout = remain / len(sockets) for s in sockets: if s.timeout > max_timeout: ...
0.003968
def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk wi...
0.002885
def to_bytes(self): ''' Returns serialized bytes object representing all headers/ payloads in this packet''' rawlist = [] i = len(self._headers)-1 while i >= 0: self._headers[i].pre_serialize(b''.join(rawlist), self, i) rawlist.insert(0, self._head...
0.004762
def index(self, column): # pylint: disable=C6409 """Fetches the column number (0 indexed). Args: column: A string, column to fetch the index of. Returns: An int, the row index number. Raises: ValueError: The specified column was not found. """ for i, key in enumerat...
0.004454
def load_from_dict(dct=None, **kwargs): """ Load configuration from a dictionary. """ dct = dct or dict() dct.update(kwargs) def _load_from_dict(metadata): return dict(dct) return _load_from_dict
0.004292
def find_comments_by_video(self, video_id, page=1, count=20): """doc: http://open.youku.com/docs/doc?id=35 """ url = 'https://openapi.youku.com/v2/comments/by_video.json' params = { 'client_id': self.client_id, 'video_id': video_id, 'page': page, ...
0.004515
def kill_zombies(self, zombies, session=None): """ Fail given zombie tasks, which are tasks that haven't had a heartbeat for too long, in the current DagBag. :param zombies: zombie task instances to kill. :type zombies: airflow.utils.dag_processing.SimpleTaskInstance :pa...
0.003333
def delete_operation(self, name): """ Deletes the long-running operation. .. seealso:: https://cloud.google.com/datastore/docs/reference/data/rest/v1/projects.operations/delete :param name: the name of the operation resource. :type name: str :return: none if...
0.003401
def calculate_amr(cls, is_extended, from_id, to_id, rtr_only=False, rtr_too=True): """ Calculates AMR using CAN-ID range as parameter. :param bool is_extended: If True parameters from_id and to_id contains 29-bit CAN-ID. :param int from_id: First CAN-ID which should be received. ...
0.009547
def reset(self): """Resets the iterator to the beginning of the data.""" self.curr_idx = 0 #shuffle data in each bucket random.shuffle(self.idx) for i, buck in enumerate(self.sentences): self.indices[i], self.sentences[i], self.characters[i], self.label[i] = shuffle(s...
0.009796
def is_all_field_none(self): """ :rtype: bool """ if self._status is not None: return False if self._balance_preferred is not None: return False if self._balance_threshold_low is not None: return False if self._method_fill i...
0.004545
def get_aside_of_type(self, block, aside_type): """ Return the aside of the given aside_type which might be decorating this `block`. Arguments: block (:class:`.XBlock`): The block to retrieve asides for. aside_type (`str`): the type of the aside """ # TOD...
0.007383
def resolve(self): """ Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows). """ s = self._flavour.resolve(self) if s is None: # No symlink resolution => for cons...
0.002894
def exit(message, code=0): """ output a message to stdout and terminates the process. :param message: Message to be outputed. :type message: String :param code: The termination code. Default is 0 :type code: int :returns: void """ v = VerbosityM...
0.001901
def secure_authorized_channel( credentials, request, target, ssl_credentials=None, **kwargs): """Creates a secure authorized gRPC channel. This creates a channel with SSL and :class:`AuthMetadataPlugin`. This channel can be used to create a stub that can make authorized requests. Example:: ...
0.000429
def add_expansion(self, expansion_node): """ Add a child expansion node to the type node's expansions. If an expansion node with the same name is already present in type node's expansions, the new and existing expansion node's children are merged. :param expansion_node: The exp...
0.003337
def roundplus(number): """ given an number, this fuction rounds the number as the following examples: 87 -> 87, 100 -> 100+, 188 -> 100+, 999 -> 900+, 1001 -> 1000+, ...etc """ num = str(number) if not num.isdigit(): return num num = str(number) digits = len(num) rounded = '...
0.001704
def __getOptimizedMetricLabel(self): """ Get the label for the metric being optimized. This function also caches the label in the instance variable self._optimizedMetricLabel Parameters: ----------------------------------------------------------------------- metricLabels: A sequence of all the la...
0.006809
def decode(self, targets, encoder_outputs, attention_bias): """Generate logits for each value in the target sequence. Args: targets: target values for the output sequence. int tensor with shape [batch_size, target_length] encoder_outputs: continuous representation of input sequence. ...
0.00723
def get_empirical_ar_params(train_datas, params): """ Estimate the parameters of an AR observation model by fitting a single AR model to the entire dataset. """ assert isinstance(train_datas, list) and len(train_datas) > 0 datadimension = train_datas[0].shape[1] assert params["nu_0"] > datad...
0.002045
def can_delete_repositories(self): """Tests if this user can delete ``Repositories``. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting a ``Repository`` will result in a ``PermissionDenied``. This is intended as a...
0.00369
def mac_move_detect_enable(self, **kwargs): """Enable mac move detect enable on vdx switches Args: get (bool): Get config instead of editing config. (True, False) delete (bool): True, delete the mac-move-detect-enable. (True, False) callback...
0.001131
def set_up(self, u, engine): """Special setup for mysql engines""" # add the reconnecting PoolListener that will detect a # disconnected connection and automatically start a new # one. This provides a measure of additional safety over # the pool_recycle parameter, and is useful ...
0.001497
def make_diagonal_povm(pi_basis, confusion_rate_matrix): """ Create a DiagonalPOVM from a ``pi_basis`` and the ``confusion_rate_matrix`` associated with a readout. See also the grove documentation. :param OperatorBasis pi_basis: An operator basis of rank-1 projection operators. :param numpy.nd...
0.005596
def describe_configs(self, config_resources, include_synonyms=False): """Fetch configuration parameters for one or more Kafka resources. :param config_resources: An list of ConfigResource objects. Any keys in ConfigResource.configs dict will be used to filter the result. Setting...
0.004014
async def get_shade(self, shade_id, from_cache=True) -> BaseShade: """Get a shade instance based on shade id.""" if not from_cache: await self.get_shades() for _shade in self.shades: if _shade.id == shade_id: return _shade raise ResourceNotFoundExc...
0.008108
def cidfrm(cent, lenout=_default_len_out): """ Retrieve frame ID code and name to associate with a frame center. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cidfrm_c.html :param cent: An object to associate a frame with. :type cent: int :param lenout: Available space in output stri...
0.00123
def find_embedding(elt, embedding=None): """Try to get elt embedding elements. :param embedding: embedding element. Must have a module. :return: a list of [module [,class]*] embedding elements which define elt. :rtype: list """ result = [] # result is empty in the worst case # start to ...
0.000473
def get_complete_version(version=None): """Returns a tuple of the graphene version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from graphene import VERSION as version else: assert len(version) == 5 assert versi...
0.005249
def setup_geoserver(options): """Prepare a testing instance of GeoServer.""" fast = options.get('fast', False) download_dir = path('downloaded') if not download_dir.exists(): download_dir.makedirs() geoserver_dir = path('geoserver') geoserver_bin = path('geoserver_ext/target/geoserver.w...
0.001661
def convert_multinomial(node, **kwargs): """Map MXNet's multinomial operator attributes to onnx's Multinomial operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get("dtype", 'int32'))] sample_si...
0.004161
def grids(fig=None, value='solid'): """Sets the value of the grid_lines for the axis to the passed value. The default value is `solid`. Parameters ---------- fig: Figure or None(default: None) The figure for which the axes should be edited. If the value is None, the current figure i...
0.001938
def _get_environment_updates(self, display_all_distributions=False): """ Check all pacakges installed in the environment to see if there are any updates availalble. Args: display_all_distributions (bool): Return distribution even if it is up-to-date. Defaults...
0.001157
def select_authors_by_geo(query): """Pass exact name (case insensitive) of geography name, return ordered set of author ids. """ for geo, ids in AUTHOR_GEO.items(): if geo.casefold() == query.casefold(): return set(ids)
0.003922
def select(self, criterion, keepboth=False): """Filter current file collections, create another file collections contains all winfile with criterion=True. How to construct your own criterion function, see :meth:`FileCollection.from_path_by_criterion`. :param criterion...
0.006116
def delete_scheduling_block(block_id): """Delete Scheduling Block with the specified ID""" DB.delete('scheduling_block/{}'.format(block_id)) # Add a event to the scheduling block event list to notify # of a deleting a scheduling block from the db DB.rpush('scheduling_block_events', jso...
0.002755
def _backward_kill_word(text, pos): """" Kill the word behind pos. Word boundaries are the same as those used by _backward_word. """ text, new_pos = _backward_word(text, pos) return text[:new_pos] + text[pos:], new_pos
0.004132
def print(self, rows): """ Write the data to our output stream (stdout). If the table is not rendered yet, we will make a renderer instance which will freeze state. """ if not self.default_renderer: self.default_renderer = self.make_renderer() self.default_renderer.p...
0.006061
def is_sqlatype_text_over_one_char( coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type that's more than one character long? """ coltype = _coltype_to_typeengine(coltype) return is_sqlatype_text_of_length_at_least(coltype, 2)
0.003279
def merge(*dicts, **kwargs): """Merges two or more dictionaries into a single one. Optional keyword arguments allow to control the exact way in which the dictionaries will be merged. :param overwrite: Whether repeated keys should have their values overwritten, retaining the last value...
0.001176
def addition_circuit( addend0: Qubits, addend1: Qubits, carry: Qubits) -> Circuit: """Returns a quantum circuit for ripple-carry addition. [Cuccaro2004]_ Requires two carry qubit (input and output). The result is returned in addend1. .. [Cuccaro2004] A new quantum rippl...
0.000697
def load_pkl(filenames): """ Unpickle file contents. Args: filenames (str): Can be one or a list or tuple of filenames to retrieve. Returns: Times: A single object, or from a collection of filenames, a list of Times objects. Raises: TypeError: If any loaded object is not a...
0.005013
def viewbox(self): """ Return bounding box of the viewport. :return: (left, top, right, bottom) `tuple`. """ return self.left, self.top, self.right, self.bottom
0.00995
def remove_backslash_r(filename, encoding): """ A helpful utility to remove Carriage Return from any file. This will read a file into memory, and overwrite the contents of the original file. TODO: This function may be a liability :param filename: :return: ...
0.004847
def run_command(self, command, shell=True, env=None, execute='/bin/bash', return_code=None): """Run a shell command. The options available: * ``shell`` to be enabled or disabled, which provides the ability to execute arbitrary stings or not. if disabled co...
0.0016
def from_ordered_sequence(cls, iseq): """ Return the root of a balanced binary search tree populated with the values in iterable *iseq*. """ seq = list(iseq) # optimize for usually all fits by making longest first bst = cls(seq.pop()) bst._insert_from_orde...
0.005618
def cut(img, left, above, right, down): """ 从图像中复制出一个矩形选区 box = (100, 100, 400, 400) region = im.crop(box) 矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点, 单位是px,所以上诉代码复制了一个 300x300 pixels 的矩形选区 :param img: 加载到内存的图片 :param left: 左 :param above: 上 :param right: 右 :param down: 下 ...
0.002381
def _missing_imageinfo(self): """ returns list of image filenames that are missing info """ if 'image' not in self.data: return missing = [] for img in self.data['image']: if 'url' not in img: missing.append(img['file']) ret...
0.005848