text
stringlengths
78
104k
score
float64
0
0.18
def qps(self, callback=None, errback=None): """ Return the current QPS for this record :rtype: dict :return: QPS information """ if not self.data: raise RecordException('record not loaded') stats = Stats(self.parentZone.config) return stats.qp...
0.003846
def calls(ctx, obj, limit): """ List call/short positions of an account or an asset """ if obj.upper() == obj: # Asset from bitshares.asset import Asset asset = Asset(obj, full=True) calls = asset.get_call_orders(limit) t = [["acount", "debt", "collateral", "call pri...
0.000801
def fill(self, postf_un_ops: str): """ Insert: * math styles * other styles * unary prefix operators without brackets * defaults """ for op, dic in self.ops.items(): if 'postf' not in dic: dic['postf'] = self.postf ...
0.002933
def getThesaurus(self, word): """response = requests.get("http://words.bighugelabs.com/api/2/%s/%s/json" % (self.tkey, word)).json() return response""" response = requests.get( "http://api.wordnik.com:80/v4/word.json/%s/relatedWords?" "useCanon...
0.005758
def delete(self, symbol): """ Deletes a Symbol. Parameters ---------- symbol : str or Symbol """ if isinstance(symbol, (str, unicode)): sym = self.get(symbol) elif isinstance(symbol, Symbol): sym = symbol ...
0.004825
def forward(self, X): """Forward function. :param X: The input (batch) of the model contains word sequences for lstm and features. :type X: For word sequences: a list of torch.Tensor pair (word sequence and word mask) of shape (batch_size, sequence_length). F...
0.002899
def addfile(project, filename, user, postdata, inputsource=None,returntype='xml'): #pylint: disable=too-many-return-statements """Add a new input file, this invokes the actual uploader""" def errorresponse(msg, code=403): if returntype == 'json': return withheaders(flask.make_response("{su...
0.01043
def draw_shapes_svg_layer(df_shapes, shape_i_columns, layer_name, layer_number=1, use_svg_path=True): ''' Draw shapes as a layer in a SVG file. Args: df_shapes (pandas.DataFrame): Table of shape vertices (one row per vertex). shape_i_columns (str or li...
0.000304
def vatm(model, x, logits, eps, num_iterations=1, xi=1e-6, clip_min=None, clip_max=None, scope=None): """ Tensorflow implementation of the perturbation method used for virtual adversarial training: https://arxiv.org/abs/1507.00677 :param mo...
0.005646
def polygon(surf, points, color): """Draw an antialiased filled polygon on a surface""" gfxdraw.aapolygon(surf, points, color) gfxdraw.filled_polygon(surf, points, color) x = min([x for (x, y) in points]) y = min([y for (x, y) in points]) xm = max([x for (x, y) in points]) ym = max([y for ...
0.002604
def validate_protocol(protocol): '''Validate a protocol, a string, and return it.''' if not re.match(PROTOCOL_REGEX, protocol): raise ValueError(f'invalid protocol: {protocol}') return protocol.lower()
0.004525
def to_polygon(self): """ Return a 4-cornered polygon equivalent to this rectangle """ x,y = self.corners.T vertices = PixCoord(x=x, y=y) return PolygonPixelRegion(vertices=vertices, meta=self.meta, visual=self.visual)
0.01
async def start_polling(self, timeout=20, relax=0.1, limit=None, reset_webhook=None, fast: typing.Optional[bool] = True, error_sleep: int = 5): ...
0.005706
def complex_request(self, request, wait_for_first_response=True): """Send a compound command request to the interface over the normal data channel. request - A dict storing the request to send to the VI. It will be serialized to the currently selected output format. wait_for...
0.004587
def _warning(code): """ Return a warning message of code 'code'. If code = (cd, str) it returns the warning message of code 'cd' and appends str at the end """ if isinstance(code, str): return code message = '' if isinstance(code, tuple): if isinstance(code[0], str): ...
0.002294
def asRemoteException(ErrorType): '''return the remote exception version of the error above you can catch errors as usally: >>> try: raise asRemoteException(ValueError) except ValueError: pass or you can catch the remote Exception >>> try: raise asRemoteException(ReferenceError)(ReferenceError(),'') except asRemote...
0.001377
def getExtentAddress(self, zoom, extent=None, contained=False): """ Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom...
0.001019
def run(self, kpop, nreps, ipyclient=None, seed=12345, force=False, quiet=False, ): """ submits a job to run on the cluster and returns an asynchronous result object. K is the number of populations, randomseed if not set will be ...
0.009385
def target_types_by_alias(self): """Returns a mapping from target alias to the target types produced for that alias. Normally there is 1 target type per alias, but macros can expand a single alias to several target types. :API: public :rtype: dict """ target_types_by_alias = defaultdict(s...
0.008013
def grant(args): """ Given an IAM role or instance name, attach an IAM policy granting appropriate permissions to subscribe to deployments. Given a GitHub repo URL, create and record deployment keys for the repo and any of its private submodules, making the keys accessible to the IAM role. "...
0.002817
def delete_topics(self, topics, **kwargs): """ Delete topics. The future result() value is None. :param list(str) topics: Topics to mark for deletion. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the DeleteTop...
0.003155
def driver(self, sim): """Push data to interface""" r = sim.read if self.actualData is NOP and self.data: self.actualData = self.data.popleft() do = self.actualData is not NOP if do: self.doWrite(sim, self.actualData) else: self.doWri...
0.001786
def run_simulations(self, parameter_list, data_folder): """ This function runs multiple simulations in parallel. """ # Open up a session s = drmaa.Session() s.initialize() # Create a job template for each parameter combination jobs = {} for param...
0.000566
def differential(poly, diffvar): """ Polynomial differential operator. Args: poly (Poly) : Polynomial to be differentiated. diffvar (Poly) : Polynomial to differentiate by. Must be decomposed. If polynomial array, the output is the Jacobian matrix. Examples: >>>...
0.000693
def run(self): """The thread's main activity. Call start() instead.""" self.socket = self.context.socket(zmq.DEALER) self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) self.socket.connect('tcp://%s:%i' % self.address) self.stream = zmqstream.ZMQStream(self.socket, self....
0.006289
def run_application( application, patch_stdout=False, return_asyncio_coroutine=False, true_color=False, refresh_interval=0, eventloop=None): """ Run a prompt toolkit application. :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that print statements from other...
0.00144
def _compute_handshake(self): """Compute the authentication handshake value. :return: the computed hash value. :returntype: `str`""" return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest()
0.012346
def _desc_has_data(desc): """Returns true if there is any data set for a particular PhoneNumberDesc.""" if desc is None: return False # Checking most properties since we don't know what's present, since a custom build may have # stripped just one of them (e.g. liteBuild strips exampleNumber). We...
0.008759
def update(self, other, join='left', overwrite=True, filter_func=None, errors='ignore'): """ Modify in place using non-NA values from another DataFrame. Aligns on indices. There is no return value. Parameters ---------- other : DataFrame, or object coerci...
0.000579
def add_router_interface(self, context, router_id, interface_info): """Add a subnet of a network to an existing router.""" new_router = super(AristaL3ServicePlugin, self).add_router_interface( context, router_id, interface_info) core = directory.get_plugin() # Get network ...
0.000965
def partition_read( self, session, table, key_set, transaction=None, index=None, columns=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ...
0.004136
def api_backoff(func): """ Decorator, Handles HTTP 429 "Too Many Requests" messages from the Discord API If blocking=True is specified, this function will block and retry the function up to max_retries=n times, or 3 if retries is not specified. If the API call still recieves a backoff timer this fun...
0.004166
def set_level(self, level): """ Set the log level of the g8os Note: this level is for messages that ends up on screen or on log file :param level: the level to be set can be one of ("CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG") """ args = { 'leve...
0.006881
def read_rows( self, table_name, app_profile_id=None, rows=None, filter_=None, rows_limit=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams back t...
0.002941
def get_config(self, key="Entrypoint", delim=None): '''get_config returns a particular key (default is Entrypoint) from a VERSION 1 manifest obtained with get_manifest. Parameters ========== key: the key to return from the manifest config delim: Given a list, the delim to us...
0.001847
def to_dict(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> dict: """From instance to dict :param ignore_none: Properties which is None are excluded if True :param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inheri...
0.007848
def parse_with_retrieved(self, retrieved): """ Parse output data folder, store results in database. :param retrieved: a dictionary of retrieved nodes, where the key is the link name :returns: a tuple with two values ``(bool, node_list)``, where: * ``bool`...
0.003755
def containerIsRunning(container_name): """ Checks whether the container is running or not. :param container_name: Name of the container being checked. :returns: True if status is 'running', False if status is anything else, and None if the container does not exist. """ client = docker.from_...
0.00237
def bvlpdu_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" foreign_device_table = [] for fdte in self.bvlciFDT: foreign_device_table.append(fdte.dict_contents(as_class=as_class)) return key_value_contents(use_dict=use_dict, as_...
0.006024
def clear(self): """Helper for clearing all the keys in a database. Use with caution!""" for key in self.conn.keys(): self.conn.delete(key)
0.011429
def launch_app(self, timeout=10): """ Launch Spotify application. Will raise a LaunchError exception if there is no response from the Spotify app within timeout seconds. """ def callback(): """Callback function""" self.send_message({"type": TYPE_...
0.002448
def transform_subject(self, X): """Transform a new subject using the existing model Parameters ---------- X : 2D array, shape=[voxels, timepoints] The fMRI data of the new subject. Returns ------- w : 2D array, shape=[voxels, features] ...
0.001887
def is_dimension(self): """Return true if the colum is a dimension""" from ambry.valuetype.core import ROLE return self.role == ROLE.DIMENSION
0.012048
def make_input_from_dict(sentence_id: SentenceId, input_dict: Dict, translator: 'Translator') -> TranslatorInput: """ Returns a TranslatorInput object from a JSON object, serialized as a string. :param sentence_id: Sentence id. :param input_dict: A dict...
0.004821
def camel_to_under(name): """ Converts camel-case string to lowercase string separated by underscores. Written by epost (http://stackoverflow.com/questions/1175208). :param name: String to be converted :return: new String with camel-case converted to lowercase, underscored """ s1 = re.sub(...
0.002404
def frommatrix(cls, apart, dpart, det_radius, init_matrix, **kwargs): """Create a `ParallelHoleCollimatorGeometry` using a matrix. This alternative constructor uses a matrix to rotate and translate the default configuration. It is most useful when the transformation to be applied is alr...
0.000723
def dump(d, fmt='json', stream=None): """Serialize structured data into a stream in JSON, YAML, or LHA format. If stream is None, return the produced string instead. Parameters: - fmt: should be 'json' (default), 'yaml', or 'lha' - stream: if None, return string """ if fmt == 'json': ...
0.001779
def get(cls, group, admin): """Get specific GroupAdmin object.""" try: ga = cls.query.filter_by( group=group, admin_id=admin.get_id(), admin_type=resolve_admin_type(admin)).one() return ga except Exception: return None
0.006452
def commit(self): ''' Writes the current provenance stack to storage if it wasn't already there and returns it Returns (Tuple[bool, str, List[]]): Whether the stack was not cached, the iden of the prov stack, and the provstack ''' providen, provstack = get() ...
0.007921
def logx(supress_args=[], supress_all_args=False, supress_result=False, receiver=None): """ logs parameters and result takes arguments supress_args - list of parameter names to supress supress_all_args - boolean to supress all arguments supress_result - boolean to supress result ...
0.003415
def get_splits(self, n_splits=1): """Return splits of this dataset ready for Cross Validation. If n_splits is 1, a tuple containing the X for train and test and the y for train and test is returned. Otherwise, if n_splits is bigger than 1, a list of such tuples is returned, one ...
0.001251
def get_access_key(self): """ Gets the application secret key. The value can be stored in parameters "access_key", "client_key" or "secret_key". :return: the application secret key. """ access_key = self.get_as_nullable_string("access_key") access_key = access_ke...
0.012019
def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug'], explicit=True) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely ...
0.00699
def __get_securities(self, currency: str, agent: str, symbol: str, namespace: str) -> List[dal.Security]: """ Fetches the securities that match the given filters """ repo = self.get_security_repository() query = repo.query if currency is not None: qu...
0.003641
def jdnDate(jdn): """ Converts Julian Day Number to Gregorian date. """ a = jdn + 32044 b = (4*a + 3) // 146097 c = a - (146097*b) // 4 d = (4*c + 3) // 1461 e = c - (1461*d) // 4 m = (5*e + 2) // 153 day = e + 1 - (153*m + 2) // 5 month = m + 3 - 12*(m//10) year = 100*b + d - 48...
0.002778
def risearch(self): "Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials" if self._risearch is None: self._risearch = ResourceIndex(self.api.base_url, self.api.username, self.api.password) return self._risearch
0.014134
def purge_run(self, event): """Run purge for the object with ``location_id`` specified in ``event`` argument.""" location_id = event['location_id'] verbosity = event['verbosity'] try: logger.info(__("Running purge for location id {}.", location_id)) location_purg...
0.009328
def _infer_interval_breaks(coord, axis=0, check_monotonic=False): """ >>> _infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) >>> _infer_interval_breaks([[0, 1], [3, 4]], axis=1) array([[-0.5, 0.5, 1.5], [ 2.5, 3.5, 4.5]]) """ coord = np.asarray(co...
0.000764
def get_package_id(self, name): """ Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large". @return: The package id that depends on the Data center and the size choosen. """ j...
0.008018
def search(self, **kwargs): """ Method to search ipv4's based on extends search. :param search: Dict containing QuerySets to find ipv4's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :para...
0.005865
def addLocation(self, locationUri, weight): """ add relevant location to the topic page @param locationUri: uri of the location to add @param weight: importance of the provided location (typically in range 1 - 50) """ assert isinstance(weight, (float, int)), "weight value...
0.00905
def theta2_purities_chart (self): """ Make the plot showing alignment rates """ # Specify the order of the different possible categories keys = OrderedDict() keys['proportion_germline'] = { 'name': 'Germline' } keys['proportion_tumour_1'] = { 'name': 'Tumour Subclone 1' } ...
0.022094
def _raw_write(self, data, debug_str = None): """ Write data to YubiKey. """ if self.debug: if not debug_str: debug_str = '' hexdump = yubico_util.hexdump(data, colorize=True)[:-1] # strip LF self._debug("WRITE : %s %s\n" % (hexdump, de...
0.014995
def list( self, bucket: str, prefix: str=None, delimiter: str=None, ) -> typing.Iterator[str]: """ Returns an iterator of all blob entries in a bucket that match a given prefix. Do not return any keys that contain the delimiter past the prefix...
0.02168
def format_configchoicefield_nodes(field_name, field, field_id, state, lineno): """Create a section node that documents a ConfigChoiceField config field. Parameters ---------- field_name : `str` Name of the configuration field (the attribute name of on the config class). field : ``l...
0.000354
def _get_component_from_result(self, result, lookup): """ Helper function to get a particular address component from a Google result. Since the address components in results are an array of objects containing a types array, we have to search for a particular component rather than being ...
0.008318
def _negotiateHandler(self, request): """ Negotiate a handler based on the content types acceptable to the client. :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes` :return: Pair of a resource and the content type. """ accept = _parseAccept(request.re...
0.002825
def _listen(self, protocols, From, description): """ Implementation of L{Listen}. """ # The peer is coming from a client-side representation of the user # described by 'From', and talking *to* a server-side representation of # the user described by 'From'. self.ve...
0.002125
def inverse_transform(self, X_in): """ Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue warnings when some of those cases occur. ...
0.006696
def _registered_kl(type_a, type_b): """Get the KL function registered for classes a and b.""" hierarchy_a = tf_inspect.getmro(type_a) hierarchy_b = tf_inspect.getmro(type_b) dist_to_children = None kl_fn = None for mro_to_a, parent_a in enumerate(hierarchy_a): for mro_to_b, parent_b in enumerate(hierarc...
0.018152
def get_next_line(self): """ Gets next line of random_file and starts over when reaching end of file""" try: line = next(self.random_file).strip() #keep track of which document we are currently looking at to later avoid having the same doc as t1 if line == "": ...
0.009146
async def peers(client: Client, leaves: bool = False, leaf: str = "") -> dict: """ GET peering entries of every node inside the currency network :param client: Client to connect to the api :param leaves: True if leaves should be requested :param leaf: True if leaf should be requested :return: ...
0.005405
def free_symbolic(self): """Free symbolic data""" if self._symbolic is not None: self.funs.free_symbolic(self._symbolic) self._symbolic = None self.mtx = None
0.009524
def set_options_from_file(self, filename, file_format='yaml'): """Load options from file. This is a wrapper over :func:`.set_options_from_JSON` and :func:`.set_options_from_YAML`. :param str filename: File from which to load the options. :param str file_format: File format (``y...
0.002797
def charges(self, num, charge_id=None, **kwargs): """Search for charges against a company by company number. Args: num (str): Company number to search on. transaction (Optional[str]): Filing record number. kwargs (dict): additional keywords passed into requests.s...
0.002882
def post_event_unpublish(self, id, **data): """ POST /events/:id/unpublish/ Unpublishes an event. In order for a free event to be unpublished, it must not have any pending or completed orders, even if the event is in the past. In order for a paid event to be unpublished, it must not have...
0.010363
def _as_reference_point(self) -> np.ndarray: """ Return classification information as reference point """ ref_val = [] for fn, f in self._classification.items(): if f[0] == "<": ref_val.append(self._method.problem.ideal[fn]) elif f[0] == "<>": ...
0.004283
def makevAndvPfuncs(self,policyFunc): ''' Constructs the marginal value function for this period. Parameters ---------- policyFunc : function Consumption and medical care function for this period, defined over market resources, permanent income level, and...
0.026085
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'hits') and self.hits is no...
0.004878
def handle_registered(self, server): """\ When the connection to the server is registered, send all pending data. """ if not self._registered: self.logger.info('Registered') self._registered = True for data in self._out_buffer: ...
0.00542
def _join_strings(x): """Joins adjacent Str elements found in the element list 'x'.""" for i in range(len(x)-1): # Process successive pairs of elements if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str': x[i]['c'] += x[i+1]['c'] del x[i+1] # In-place deletion of element from list ...
0.002571
def return_file_objects(connection, container, prefix='database'): """Given connecton and container find database dumps """ options = [] meta_data = objectstore.get_full_container_list( connection, container, prefix='database') env = ENV.upper() for o_info in meta_data: expec...
0.001466
def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: """ Returns True if you have vision on a grid point. """ # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3...
0.007246
def validate_word_size(word_size, BLAST_SETS): """Validate word size in blast/tblastn form. """ blast_min_int_word_size = BLAST_SETS.min_word_size blast_max_int_word_size = BLAST_SETS.max_word_size blast_word_size_error = BLAST_SETS.get_word_size_error() try: if len(word_size) <= 0: ...
0.002674
def share(self, email, message=None): """Share the project with another Todoist user. :param email: The other user's email address. :type email: str :param message: Optional message to send with the invitation. :type message: str >>> from pytodoist import todoist ...
0.002972
def find_field(browser, field_type, value): """ Locate an input field. :param browser: ``world.browser`` :param string field_type: a field type (i.e. `button`) :param string value: an id, name or label This first looks for `value` as the id of the element, else the name of the element, els...
0.001742
def format_request_email_templ(increq, template, **ctx): """Format the email message element for inclusion request notification. Formats the message according to the provided template file, using some default fields from 'increq' object as default context. Arbitrary context can be provided as keywords ...
0.000751
def normalizeX(value): """ Normalizes x coordinate. * **value** must be an :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("X coordinates must be instances of " ":ref:`type-i...
0.002475
def _write(self, destination: TextIO) -> None: """ Writes the converted output to a destination. """ for line in self.dest_lines: destination.write(line + NL)
0.009901
def id_match_check(self, data_df, meta_df, dim): """ Verifies that id values match between: - row case: index of data_df & index of row metadata - col case: columns of data_df & index of column metadata """ if dim == "row": if len(data_df.index) == len...
0.007849
def relabel(self, xlabel=None, ylabel=None, y2label=None, title=None, delay_draw=False): " re draw labels (title, x, y labels)" n = self.labelfont.get_size() self.titlefont.set_size(n+1) # print(" plot relabel ", delay_draw) rcParams['xtick.labelsize'] = rcParam...
0.004507
def action_set(method_name): """ Creates a setter that will call the action method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the action. @type method_name: str """ def action_set(value, context, **_para...
0.00216
def _try_reduce(self) -> Tuple[bool, List[HdlStatement]]: """ Doc on parent class :meth:`HdlStatement._try_reduce` """ # flag if IO of statement has changed io_change = False self.ifTrue, rank_decrease, _io_change = self._try_reduce_list( self.ifTrue) ...
0.002102
def write(self, data): 'Put, possibly replace, file contents with (new) data' if not hasattr(data, 'read'): data = six.BytesIO(data)#StringIO(data) self.jfs.up(self.path, data)
0.018868
def plot_element_profile(self, element, comp, show_label_index=None, xlim=5): """ Draw the element profile plot for a composition varying different chemical potential of an element. X value is the negative value of the chemical potential reference to ...
0.001677
def instance(self): """ Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'. See :func:`Part.instances()` method for documentation. :return: :class:`Part` with category `INSTANCE` :raises NotFoundError: if the instance does not exist ...
0.007194
def delete_saved_search(self, keys): """ Delete one or more saved searches by passing a list of one or more unique search keys """ headers = {"Zotero-Write-Token": token()} headers.update(self.default_headers()) req = requests.delete( url=self.endpoint ...
0.004505
def volumes(self): """ Returns a `list` of all the `Volume` known to the cluster. Updates every time - no caching. :return: a `list` of all the `Volume` known to the cluster. :rtype: list """ self.connection._check_login() response = self.connection._do_get("{}/{...
0.007092
def query_dns(cls, domains, records): """ Query DNS records for host. :param domains: Iterable of domains to get DNS Records for :param records: Iterable of DNS records to get from domain. """ results = {k: set() for k in records} for record in records: ...
0.003619
def get_order(self, order_id): '''Get an order''' resp = self.get('/orders/{}'.format(order_id)) return Order(resp)
0.014388