text
stringlengths
78
104k
score
float64
0
0.18
def get_category(self, id, **data): """ GET /categories/:id/ Gets a :format:`category` by ID as ``category``. """ return self.get("/categories/{0}/".format(id), data=data)
0.013636
def subtract_afromb(*inputs, **kwargs): """Subtract stream a from stream b. Returns: list(IOTileReading) """ try: value_a = inputs[0].pop() value_b = inputs[1].pop() return [IOTileReading(0, 0, value_b.value - value_a.value)] except StreamEmptyError: return...
0.003096
def mnist_model(image, labels, mesh): """The model. Args: image: tf.Tensor with shape [batch, 28*28] labels: a tf.Tensor with shape [batch] and dtype tf.int32 mesh: a mtf.Mesh Returns: logits: a mtf.Tensor with shape [batch, 10] loss: a mtf.Tensor with shape [] """ batch_dim = mtf.Dimens...
0.011728
def get_email_templates_per_page(self, per_page=1000, page=1, params=None): """ Get e-mail templates per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list ...
0.006849
def unpack_int(s): """ Reads a packed integer from string <s> """ ret = 0 i = 0 while True: b = ord(s[i]) ret |= (b & 127) << (i * 7) i += 1 if b & 128 == 0: break return ret
0.004202
def _setup_exercise(game_interface: GameInterface, ex: Exercise, seed: int) -> Optional[Result]: """ Set the game state. Only returns a result if there was an error in ex.setup() """ rng = random.Random() rng.seed(seed) try: game_state = ex.setup(rng) except Exception as e: ...
0.006711
def build_includes(cls, include_packages): """ The default include strategy is to add a star (*) wild card after all sub-packages (but not the main package). This strategy is compatible with py2app and bbfreeze. Example (From SaltStack 2014.7): salt salt.fileser...
0.004849
def update_alias(self, addressid, data): """Update alias address""" return self.api_call( ENDPOINTS['aliases']['update'], dict(addressid=addressid), body=data)
0.009479
def do_propget(self, subcmd, opts, *args): """Print value of PROPNAME on files, dirs, or revisions. usage: 1. propget PROPNAME [PATH...] 2. propget PROPNAME --revprop -r REV [URL] 1. Prints versioned prop in working copy. 2. Prints unversioned remote pro...
0.004357
def blog_recent_posts(limit=5, tag=None, username=None, category=None): """ Put a list of recently published blog posts into the template context. A tag title or slug, category title or slug or author's username can also be specified to filter the recent posts returned. Usage:: {% blog_rec...
0.00143
def is_valid_combination(row): """ This is a filtering function. Filtering functions should return True if combination is valid and False otherwise. Test row that is passed here can be incomplete. To prevent search for unnecessary items filtering function is executed with found subset of data t...
0.001295
def log_start_end(f): """ Decorator to log start and end of function Use of decorator module here ensures that argspec will inspect wrapped function, not the decorator itself. http://micheles.googlecode.com/hg/decorator/documentation.html """ def inner(f, *args, **kwargs): logging.i...
0.002028
def search_show_address_unite(self, progammeId, source_site=None, type=None): """doc: http://open.youku.com/docs/doc?id=85 """ url = 'https://openapi.youku.com/v2/searches/show/address_unite.json' params = { 'client_id': self.client_id, ...
0.005338
def read_namespaced_daemon_set(self, name, namespace, **kwargs): """ read the specified DaemonSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set(name, namespace,...
0.005722
def AsPrimitiveProto(self): """Return an old style protocol buffer object.""" if self.protobuf: result = self.protobuf() result.ParseFromString(self.SerializeToString()) return result
0.019139
def import_string(dotted_path: str) -> Any: """ Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import fails. """ try: module_path, class_name = dotted_path.strip(' ').rsplit('.', 1...
0.006033
def build_slabs(self): """ Builds the reconstructed slab by: (1) Obtaining the unreconstructed slab using the specified parameters for the SlabGenerator. (2) Applying the appropriate lattice transformation in the a and b lattice vectors. ...
0.00444
def report_non_responding_hosting_devices(self, context, host, hosting_device_ids): """Report that a hosting device is determined to be dead. :param context: contains user information :param host: originator of callback :param hosting_device...
0.005076
def get_ip(request): """ get the ip address from the request """ if config.BEHIND_REVERSE_PROXY: ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '') ip_address = ip_address.split(",", 1)[0].strip() if ip_address == '': ip_address = get_ip_address_from_request(reque...
0.002421
def predict_class(self, features): """ Model inference base on the given data which returning label :param features: it can be a ndarray or list of ndarray for locally inference or RDD[Sample] for running in distributed fashion :return: ndarray or RDD[Sample] dep...
0.00566
def wait(self, build_id, states): """ :param build_id: wait for build to finish :return: """ logger.info("watching build '%s'", build_id) for changetype, obj in self.watch_resource("builds", build_id): try: obj_name = obj["metadata"]["name"] ...
0.002139
def connect_to_region(cls, region, session=None, access_key=None, secret_key=None, **kwargs): """ Connect to an AWS region. This method has been deprecated in favor of :meth:`~.connect` Parameters ---------- region : str Name of an ...
0.002555
def handle(self, dict): ''' Processes a vaild zookeeper request @param dict: a valid dictionary object ''' # format key key = "zk:{action}:{domain}:{appid}".format( action=dict['action'], appid=dict['appid'], domain=dict['d...
0.003132
def satisfaction_reason_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/satisfaction_reasons#show-reason-for-satisfaction-rating" api_path = "/api/v2/satisfaction_reasons/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
0.009615
def global_maxpooling(attrs, inputs, proto_obj): """Performs max pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
0.01039
def update(self, default_activity_sid=values.unset, event_callback_url=values.unset, events_filter=values.unset, friendly_name=values.unset, multi_task_enabled=values.unset, timeout_activity_sid=values.unset, prioritize_queue_order=values.unset): """ ...
0.00692
def _parse_game_date_and_location(self, boxscore): """ Retrieve the game's date and location. The date and location of the game follow a more complicated parsing scheme and should be handled differently from other tags. Both fields are separated by a newline character ('\n') wit...
0.001309
def run_container(docker_client, backup_data): """Pull the Docker image and creates a container with a '/backup' volume. This volume will be mounted on the temporary workdir previously created. It will then start the container and return the container object. """ docker_client.pull(backup_data[...
0.00149
def load(self, filename=None): ''' Reads a non-XML bcp FORMAT file and parses it into fields list used for creating bulk data file ''' fields = [] with open(filename, 'r') as f: format_data = f.read().strip() lines = format_data.split('\n') self._sql_...
0.004525
def explain_decision_tree(estimator, vec=None, top=_TOP, target_names=None, targets=None, # ignored feature_names=None, feature_re=None, ...
0.001052
def cache(self, name, val, overwrite=True): """Assigns an attribute reference to all subsequent tasks. For example, if a task caches a DataFrame `df` using `self.cache('some_df', df)`, all tasks that follow can access the DataFrame using `self.some_df`. Note that manually assigned attributes tha...
0.007439
def _prefetch_items(self,change): """ When the current_row in the model changes (whether from scrolling) or set by the application. Make sure the results are loaded! """ if self.is_initialized: view = self.item_view upper_limit = view.iterabl...
0.017341
def GetStatus(self): """Requests and waits for status. Returns: status dictionary. """ # status packet format STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH" STATUS_FIELDS = [ "packetType", "firmwareVersion", ...
0.000647
def draw(self): """ Draws the precision-recall curves computed in score on the axes. """ if self.iso_f1_curves: for f1 in self.iso_f1_values: x = np.linspace(0.01, 1) y = f1 * x / (2 * x - f1) self.ax.plot(x[y>=0], y[y>=0], colo...
0.009174
def make_rpc_report(repo_dir, old_commit, new_commit, args): """Create initial RST report header for OpenStack-Ansible.""" # Do we have a valid commit range? # NOTE: # An exception is thrown by osa_differ if these two commits # are the the same, but it is sometimes necessary to ...
0.000766
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasAgg(figure) manager = FigureManagerBase(canvas, num) return manager
0.004367
def downloadThumbnail(self, outPath): """downloads the items's thumbnail""" url = self._url + "/info/thumbnail" params = { } return self._get(url=url, out_folder=outPath, file_name=None, param_di...
0.015717
def installed_plugins(only_conda=False): ''' .. versionadded:: 0.20 Parameters ---------- only_conda : bool, optional Only consider plugins that are installed **as Conda packages**. .. versionadded:: 0.22 Returns ------- list List of properties corresponding to...
0.00147
def find_program (program): """Look for program in environment PATH variable.""" if os.name == 'nt': # Add some well-known archiver programs to the search path path = os.environ['PATH'] path = append_to_path(path, get_nt_7z_dir()) path = append_to_path(path, get_nt_mac_dir()) ...
0.004283
def next(self): """ Sends a "next" command to the player. """ msg = cr.Message() msg.type = cr.NEXT self.send_message(msg)
0.011765
def dropbox_form(request): """ generates a dropbox uid and renders the submission form with a signed version of that id""" from briefkasten import generate_post_token token = generate_post_token(secret=request.registry.settings['post_secret']) return dict( action=request.route_url('dropbox_form_...
0.006696
def element_focus_should_be_set(self, locator): """Verifies the element identified by `locator` has focus. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id |""" self._info("Verifying element '%s' focus is set" % locator) self._check_element_focus(True, locator)
0.022082
def write_maxjobs(self,fh,category): """ Write the DAG entry for this category's maxjobs to the DAG file descriptor. @param fh: descriptor of open DAG file. @param category: tuple containing type of jobs to set a maxjobs limit for and the maximum number of jobs of that type to run at once. "...
0.014963
def _getManagedObjectsInstances(self, varBinds, **context): """Iterate over Managed Objects fulfilling SNMP query. Returns ------- :py:class:`list` - List of Managed Objects Instances to respond with or `None` to indicate that not all objects have been gathered s...
0.001514
def otsu (img, bins=64): r""" Otsu's method to find the optimal threshold separating an image into fore- and background. This rather expensive method iterates over a number of thresholds to separate the images histogram into two parts with a minimal intra-class variance. An increase in the...
0.011622
def feed(self, data_len, feed_time=None): '''Update the bandwidth meter. Args: data_len (int): The number of bytes transfered since the last call to :func:`feed`. feed_time (float): Current time. ''' self._bytes_transferred += data_len sel...
0.002481
def remove_certain_leaves(tr, to_remove=lambda node: False): """ Removes all the branches leading to leaves identified positively by to_remove function. :param tr: the tree of interest (ete3 Tree) :param to_remove: a method to check is a leaf should be removed. :return: void, modifies the initial tr...
0.002081
def generate_sections(self): """Return all hubs, slugs, and upload counts.""" datasets = Dataset.objects.values( 'hub_slug' ).annotate( upload_count=Count( 'hub_slug' ) ).order_by('-upload_count') return [ { ...
0.003738
def overlap(intv1, intv2): """Overlaping of two intervals""" return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
0.007519
def _build_project_tree(path, followsymlinks, file_filter): """ Build a tree of LocalFolder with children or just a LocalFile based on a path. :param path: str path to a directory to walk :param followsymlinks: bool should we follow symlinks when walking :param file_filter: FileFilter: include metho...
0.006289
def iterconsume(self, limit=None): """Cycle between all consumers in consume mode. See :meth:`Consumer.iterconsume`. """ self.consume() return self.backend.consume(limit=limit)
0.009217
def recvProxyData(self, data): """Write data to server""" if self.initialized: self.sendData(data) else: self.queued_data.append(data)
0.010989
def read(self, timeout=None): ''' Read from the transport. If timeout>0, will only block for `timeout` seconds. ''' e = None if not hasattr(self, '_sock'): return None try: # Note that we ignore both None and 0, i.e. we either block with a...
0.001107
def approve_subscription(data): """ Function to approve a SNS subscription with Amazon We don't do a ton of verification here, past making sure that the endpoint we're told to go to to verify the subscription is on the correct host """ url = data['SubscribeURL'] domain = urlparse(url).netl...
0.000933
def get_public_net_id(self): """Returns the public net id""" for id, net_params in self.strategy.iteritems(): if id == CONF.QUARK.public_net_id: return id return None
0.009174
def new(self, *args, **kwargs): ''' Create and return a new instance. ''' inst = self.clazz() self.storage.append(inst) # set all attributes with an initial default value referential_attributes = dict() for name, ty in self.attributes: ...
0.006926
def _offset_setup(self,sigangle,leading,deltaAngleTrack): """The part of the setup related to calculating the stream/progenitor offset""" #From the progenitor orbit, determine the sigmas in J and angle self._sigjr= (self._progenitor.rap()-self._progenitor.rperi())/numpy.pi*self._sigv sel...
0.016442
def initialize(self, symbolic_vm: LaserEVM): """Initializes the mutation pruner Introduces hooks for SSTORE operations :param symbolic_vm: :return: """ @symbolic_vm.pre_hook("SSTORE") def mutator_hook(global_state: GlobalState): global_state.annotate...
0.003024
def pad_zeroes(addr, n_zeroes): """Padds the address with zeroes""" if len(addr) < n_zeroes: return pad_zeroes("0" + addr, n_zeroes) return addr
0.006098
def build_hugo_md(filename, tag, bump): """ Build the markdown release notes for Hugo. Inserts the required TOML header with specific values and adds a break for long release notes. Parameters ---------- filename : str, path The release notes file. tag : str The tag, fo...
0.001106
def _initTable(self, tableName, schemaDef): cursor=_conn.execute(""" SELECT * FROM sqlite_master WHERE name ='{0}' and type='table'; """.format(tableName)) if cursor.fetchone() is None: _conn.execute('''CREATE TABLE {0} ({1});'''.format(tableName, schemaDef)) ...
0.007407
async def state(gc: GroupControl): """Current group state.""" state = await gc.state() click.echo(state) click.echo("Full state info: %s" % repr(state))
0.005952
def add(self, *args, **kwargs): """Add a new record to the section""" if self.start and self.start.state == 'done' and kwargs.get('log_action') != 'done': raise ProgressLoggingError("Can't add -- process section is done") self.augment_args(args, kwargs) kwargs['log_action'...
0.004926
def is_org_admin(self, organisation_id): """Is the user authorized to administrate the organisation""" return (self._has_role(organisation_id, self.roles.administrator) or self.is_admin())
0.009091
def close(self): """ Close the link. """ # Stop the comm thread self._thread.stop() # Close the USB dongle try: if self.cfusb: self.cfusb.set_crtp_to_usb(False) self.cfusb.close() except Exception as e: # If we pull...
0.004338
def AgregarViaje(self, cuit_transportista=None, cuit_conductor=None, fecha_inicio_viaje=None, distancia_km=None, **kwargs): "Agrega la información referente al viaje del remito electrónico cárnico" self.remito['viaje'] = {'cuitTransportista': cuit_transportista, 'cuitCon...
0.012111
def spline_backwards_hankel(ht, htarg, opt): r"""Check opt if deprecated 'spline' is used. Returns corrected htarg, opt. r""" # Ensure ht is all lowercase ht = ht.lower() # Only relevant for 'fht' and 'hqwe', not for 'quad' if ht in ['fht', 'qwe', 'hqwe']: # Get corresponding htar...
0.000728
def node_ignores_exception( node: astroid.node_classes.NodeNG, exception=Exception ) -> bool: """Check if the node is in a TryExcept which handles the given exception. If the exception is not given, the function is going to look for bare excepts. """ managing_handlers = get_exception_handlers(n...
0.002381
def map_async(self, func, iterable, chunksize=None, callback=None): """A variant of the map() method which returns a ApplyResult object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready callback is applied to it...
0.002857
def get_window_at_mouse(self): """ Get the window the mouse is currently over """ window_ret = ctypes.c_ulong(0) _libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret)) return window_ret.value
0.007905
def subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value. """...
0.002105
def block_similarity(self, block_a, block_b): """ :param block_a: The first block address. :param block_b: The second block address. :returns: The similarity of the basic blocks, normalized for the base address of the block and function call addresses. ...
0.004242
def apply_diff(src, dest): """Recursively apply changes from src to dest. Preserves dest type and hidden info in dest structure, like ruamel.yaml leaves when parses files. This includes comments, ordering and line foldings. Used in Stage load/dump cycle to preserve comments and custom formatting. ...
0.00064
def normalizedFluctuationCorrelationFunctionMultiple(A_kn, B_kn=None, N_max=None, norm=True, truncate=False): """Compute the normalized fluctuation (cross) correlation function of (two) timeseries from multiple timeseries samples. C(t) = (<A(t) B(t)> - <A><B>) / (<AB> - <A><B>) This may be useful in diagno...
0.004038
def mousePressEvent(self, event): """Reimplement Qt method""" if event.button() == Qt.LeftButton: self.__drag_start_pos = QPoint(event.pos()) QTabBar.mousePressEvent(self, event)
0.009174
def generate_request_xml(message_identifier_id, operation, lis_result_sourcedid, score): # pylint: disable=too-many-locals """ Generates LTI 1.1 XML for posting result to LTI consumer. :param message_identifier_id: :param operation: :param lis_result_sourcedid: :par...
0.00056
def sonority_from_fts(self, seg): """Given a segment as features, returns the sonority on a scale of 1 to 9. Args: seg (list): collection of (value, feature) pairs representing a segment (vowel or consonant) Returns: int: sonority of `s...
0.002235
def generateUiClasses(srcpath): """ Generates the UI classes using the compilation system for Qt. :param srcpath | <str> """ import_qt(globals()) for root, folders, files in os.walk(srcpath): found = False for file in files: name, ext = os.pa...
0.008621
def connect(self): """ Connect to the tcp gateway Allow for this function to be keypad agnostic If keypad value is omitted, then set it to the hex value of 70 which is the recommended value for an external device controlling the system (top of pg 3 of cav6.6_rnet_protocol_v1.01.00.pdf). ...
0.006281
def _header(self): """ Default html header """ html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Report</title> """ if "bokeh" in self.report_engines: html += self.bokeh_header_() if "altair" in self.report_engines:...
0.029126
def strains(self): """ Create a dictionary of SEQID: OLNID from the supplied """ with open(os.path.join(self.path, 'strains.csv')) as strains: next(strains) for line in strains: oln, seqid = line.split(',') self.straindict[oln] = se...
0.00431
def _percentile(self, values, percent, key=lambda x: x): """Find the percentile of a list of values. Args: values: A list of values for which percentiles are desired percent: A float value from 0 to 100 representing the requested percentile. key: optional key functio...
0.004167
def _set_cspf_group_subnet(self, v, load=False): """ Setter method for cspf_group_subnet, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/cspf_group/cspf_group_subnet (list) If this variable is read-only (config: false) in the source YANG file, then _set_cspf_group_subnet is consider...
0.003839
def custom_prompt(msg, delims="", completer=lambda: None): """Start up a prompt that with particular delims and completer""" try: orig_delims = readline.get_completer_delims() orig_completer = readline.get_completer() readline.set_completer_delims(delims) readline.set_completer(...
0.001779
def compute_pac(self): """Compute phase-amplitude coupling values from data.""" n_segments = sum([len(x['data'].axis['chan'][0]) for x in self.data]) progress = QProgressDialog('Computing PAC', 'Abort', 0, n_segments - 1, self) progress.setWindowModalit...
0.001869
def demote(self, move: chess.Move) -> None: """Moves a variation one down in the list of variations.""" variation = self[move] i = self.variations.index(variation) if i < len(self.variations) - 1: self.variations[i + 1], self.variations[i] = self.variations[i], self.variation...
0.009146
def get_serializer(self, *args, **kwargs): """Get an instance of the child serializer.""" init_args = { k: v for k, v in six.iteritems(self.kwargs) if k in self.SERIALIZER_KWARGS } kwargs = self._inherit_parent_kwargs(kwargs) init_args.update(kwargs) ...
0.004357
def make_sequence(obj): """ Given an object, if it is a sequence return, otherwise add it to a length 1 sequence and return. Useful for wrapping functions which sometimes return single objects and other times return lists of objects. Parameters -------------- obj : object An obje...
0.001835
def handler(self,): """* get request token if OAuth1 * Get user authorization * Get access token """ if self.oauth_version == 'oauth1': request_token, request_token_secret = self.oauth.get_request_token(params={'oauth_callback': self.callback_uri}) ...
0.007024
def timeseries_reactive(self): """ Reactive power time series in kvar. Parameters ------- :pandas:`pandas.Series<series>` Series containing reactive power time series in kvar. Returns ---------- :pandas:`pandas.DataFrame<dataframe>` or None ...
0.001748
def __convert_string(node): """Converts a StringProperty node to JSON format.""" converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue)) return __check_for_flag(converted)
0.004926
def _create(self): """ Create the file if not exists. """ # Create new file with _handle_azure_exception(): self._create_from_size( content_length=self._content_length, **self._client_kwargs)
0.007722
def completeness(args): """ %prog completeness blastfile ref.fasta > outfile Print statistics for each gene, the coverage of the alignment onto the best hit, as an indicator for completeness of the gene model. For example, one might BLAST sugarcane ESTs against sorghum annotations as reference, to ...
0.002882
def response_iterator(request_iterator, thread_pool, max_active_tasks=None, do_first_task_sequentially=True): """ :param request_iterator: An iterator producing inputs for consumption by the worker pool. :type request_iterator: iterator of callable, args, kwargs :param thread_pool: thread pool t...
0.001501
def predict(self, data, unkown=None): """\ Classify data according to previous calibration. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :type data: :class:`scipy.sparse.csr_matrix` :param unkown: the label to attribute if no label is known :returns:...
0.003704
def fetchByExample(self, exampleDict, batchSize, rawResults = False, **queryArgs) : """exampleDict should be something like {'age' : 28}""" return self.simpleQuery('by-example', rawResults, example = exampleDict, batchSize = batchSize, **queryArgs)
0.041667
def handle_extra_source(self, source_df, sim_params): """ Extra sources always have a sid column. We expand the given data (by forward filling) to the full range of the simulation dates, so that lookup is fast during simulation. """ if source_df is None: retu...
0.000628
def _get_principal(self, app: FlaskUnchained) -> Principal: """ Get an initialized instance of Flask Principal's. :class:~flask_principal.Principal`. """ principal = Principal(app, use_sessions=False) principal.identity_loader(self._identity_loader) return princip...
0.006211
def remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_name)
0.004219
def get_best_language(self, accept_lang): """Given an Accept-Language header, return the best-matching language.""" LUM = settings.LANGUAGE_URL_MAP langs = dict(LUM.items() + settings.CANONICAL_LOCALES.items()) # Add missing short locales to the list. This will automatically map ...
0.004621