text
stringlengths
78
104k
score
float64
0
0.18
def wells(self, *args) -> List[Well]: """ Accessor function used to generate a list of wells in top -> down, left -> right order. This is representative of moving down `rows` and across `columns` (e.g. 'A1', 'B1', 'C1'...'A2', 'B2', 'C2') With indexing one can treat it as a typi...
0.001783
def get_strings(self, need_quote=False): """ret: string""" self.skip() if self.buf[0] == ';' or self.buf[0] == '{' or self.buf[0] == '}': error.err_add(self.errors, self.pos, 'EXPECTED_ARGUMENT', self.buf[0]) raise error.Abort if self.bu...
0.001284
def Record(self, value): """Records given value.""" self.sum += value self.count += 1 pos = bisect.bisect(self.bins, value) - 1 if pos < 0: pos = 0 elif pos == len(self.bins): pos = len(self.bins) - 1 self.heights[pos] += 1
0.011321
def dump_stats(self, pattern): """Dumps VM statistics. in pattern of type str The selection pattern. A bit similar to filename globbing. """ if not isinstance(pattern, basestring): raise TypeError("pattern can only be an instance of type basestring") sel...
0.01061
def node_path_to_child(self, node): """Return a list describing the path from this node to a child node If *node* is not a (grand)child of this node, then raise RuntimeError. Parameters ---------- node : instance of Node The child node. Returns ----...
0.002604
def MakeSuiteFromHist(hist, name=None): """Makes a normalized suite from a Hist object. Args: hist: Hist object name: string name Returns: Suite object """ if name is None: name = hist.name # make a copy of the dictionary d = dict(hist.GetDict()) return...
0.002882
def _move_focused_item_into_viewport(self, view, focused_item): """Called when an item is focused, moves the item into the viewport :param view: :param StateView | ConnectionView | PortView focused_item: The focused item """ self.view.editor.handler_block(self.drag_motion_handle...
0.006726
def ADC(cpu, dest, src): """ Adds with carry. Adds the destination operand (first operand), the source operand (second operand), and the carry (CF) flag and stores the result in the destination operand. The state of the CF flag represents a carry from a previous addition. When a...
0.009076
def clean_time(sltime, in_format='%Y-%m-%dT%H:%M:%S%z', out_format='%Y-%m-%d %H:%M'): """Easy way to format time strings :param string sltime: A softlayer formatted time string :param string in_format: Datetime format for strptime :param string out_format: Datetime format for strftime """ try: ...
0.003906
def cmd_land(ip, count, port, iface, verbose): """This command implements the LAND attack, that sends packets forging the source IP address to be the same that the destination IP. Also uses the same source and destination port. The attack is very old, and can be used to make a Denial of Service on ...
0.000843
def applyCommand(self): """ Applies the current line of code as an interactive python command. """ # generate the command information cursor = self.textCursor() cursor.movePosition(cursor.EndOfLine) line = projex.text.nativestring(curs...
0.009542
def to_pandas(self, wrap=False, **kwargs): """ Convert to pandas DataFrame. Execute at once. :param wrap: if True, wrap the pandas DataFrame into a PyODPS DataFrame :return: pandas DataFrame """ try: import pandas as pd except ImportError: ...
0.002959
def find_card_bundles(provider: Provider, deck: Deck) -> Optional[Iterator]: '''each blockchain transaction can contain multiple cards, wrapped in bundles. This method finds and returns those bundles.''' if isinstance(provider, RpcNode): if deck.id is None: raise Exception("deck.id r...
0.000816
def fetch_recent_submissions(self, max_duration): """Fetch recent submissions in subreddit with boundaries. Does not include posts within the last day as their scores may not be representative. :param max_duration: When set, specifies the number of days to include """ ...
0.002853
def get_cell_length(flow_model): """Get flow direction induced cell length dict. Args: flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported. """ assert flow_model.lower() in FlowModelConst.d8_lens return FlowModelConst.d8_lens.get(flow_model.lower()...
0.009346
def gammatone_erb_constants(n): """ Constants for using the real bandwidth in the gammatone filter, given its order. Returns a pair :math:`(x, y) = (1/a_n, c_n)`. Based on equations from: ``Holdsworth, J.; Patterson, R.; Nimmo-Smith, I.; Rice, P. Implementing a GammaTone Filter Bank. In: SVOS Final Re...
0.004682
def getProvince(self, default=None): """Return the Province from the Physical or Postal Address """ physical_address = self.getPhysicalAddress().get("state", default) postal_address = self.getPostalAddress().get("state", default) return physical_address or postal_address
0.006431
def recover(self,runAsync=False): """ If the shared configuration store for a site is unavailable, a site in read-only mode will operate in a degraded capacity that allows access to the ArcGIS Server Administrator Directory. You can recover a site if the shared configuration stor...
0.003922
def JR(self,**kwargs): """ NAME: JR PURPOSE: Calculate the radial action INPUT: +scipy.integrate.quad keywords OUTPUT: J_R(R,vT,vT)/ro/vc + estimate of the error HISTORY: 2010-12-01 - Written - Bovy (NYU) """ ...
0.021157
def meta_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None): """ *Wrapper of* ``SELECT`` Wrapper of the :meth:`~.select` function filtering samples only based on metadata. :param predicate: logical predicate on the values of the rows :param semiJoinDataset: a...
0.00826
def supports_heading_type(self, heading_type): """Tests if the given heading type is supported. arg: heading_type (osid.type.Type): a heading Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``HEADI...
0.002874
def match_files(files, pattern: Pattern): """Yields file name if matches a regular expression pattern.""" for name in files: if re.match(pattern, name): yield name
0.005208
async def pong(self, message: bytes=b'') -> None: """Send pong message.""" if isinstance(message, str): message = message.encode('utf-8') await self._send_frame(message, WSMsgType.PONG)
0.0181
def join(self, join_streamlet, window_config, join_function): """Return a new Streamlet by joining join_streamlet with this streamlet """ from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt join_streamlet_result = JoinStreamlet(JoinBolt.INNER, window_config, ...
0.002008
def handle_options(tool, condition, command, options): """ Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags>...
0.004386
def set_sail(self, angle): ''' Set the angle of the sail to `angle` degrees :param angle: sail angle :type angle: float between -90 and 90 ''' angle = float(angle) request = self.boatd.post({'value': float(angle)}, '/sail') return request.get('result')
0.006309
def set_state(task, execution_date, upstream=False, downstream=False, future=False, past=False, state=State.SUCCESS, commit=False, session=None): """ Set the state of a task instance and if needed its relatives. Can set state for future tasks (calculated from execution_date) and retroactively ...
0.000973
def sign(self, pairs): """ Generate a signature for a sequence of (key, value) pairs @param pairs: The pairs to sign, in order @type pairs: sequence of (str, str) @return: The binary signature of this sequence of pairs @rtype: str """ kv = kvform.seq...
0.003623
def get_jobs_url(self, job_id): # type: (Text) -> Text """ Returns the URL to check job status. :param job_id: The ID of the job to check. """ return compat.urllib_parse.urlunsplit(( self.uri.scheme, self.uri.netloc, self.u...
0.006977
def cli(env, identifier, count): """Get details for a ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
0.003759
def disable(self, clear_cache=True): """ Disable the cache and clear its contents :param clear_cache: clear the cache contents as well as disabling (defaults to True) """ logger.debug('disable(clear_cache={})'.format(clear_cache)) if clear_cache: self.clear()...
0.007595
def fileSave(self, filePath=None, updatePath=False): """Write the internal JSON data dictionary to a JSON data file. If no file path is provided, the stored data file path will be used. Args: filePath (Optional[str]): A relative or absolute path to a '.json' file. D...
0.002676
def pfxdtag(tag): """ Return short-form prefixed tag from fully qualified (Clark notation) tagname. """ uri, tagroot = tag[1:].split('}') prefix = reverse_nsmap[uri] return '%s:%s' % (prefix, tagroot)
0.004386
def new_value(self, key, value): """Create new value in data""" data = self.model.get_data() data[key] = value self.set_data(data)
0.012048
def log(level, message): """ Publish `message` with the `level` the redis `channel`. :param level: the level of the message :param message: the message you want to log """ if redis_instance is None: __connect() if level not in __error_levels: raise InvalidErrorLevel('You ha...
0.001667
def send_left(self, count): """ Sends the given number of left key presses. """ for i in range(count): self.interface.send_key(Key.LEFT)
0.011111
def add_to_archive(self, spec): ''' Add files and commands to archive Use InsightsSpec.get_output() to get data ''' if isinstance(spec, InsightsCommand): archive_path = os.path.join(self.cmd_dir, spec.archive_path.lstrip('/')) if isinstance(spec, InsightsFile)...
0.007797
def read_rows( self, read_position, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Reads rows from the table in the format prescribed by the read session. Each response contains one...
0.000776
def allocate_sync_ensembles(dynamic, tolerance = 0.1, threshold = 1.0, ignore = None): """! @brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster. @param[in] dynamic (dynamic): Dynamic of each oscillato...
0.023489
def lstlec(string, n, lenvals, array): """ Given a character string and an ordered array of character strings, find the index of the largest array element less than or equal to the given string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlec_c.html :param string: Upper bound va...
0.001087
def ip_address(self, container: Container ) -> Union[IPv4Address, IPv6Address]: """ The IP address used by a given container, or None if no IP address has been assigned to that container. """ r = self.__api.get('containers/{}/ip'.format(conta...
0.009112
def cache_return(func): """Cache the return value of a function without arguments""" _cache = [] def wrap(): if not _cache: _cache.append(func()) return _cache[0] return wrap
0.004545
def get_gpu_ids(): """Get the IDs of the GPUs that are available to the worker. If the CUDA_VISIBLE_DEVICES environment variable was set when the worker started up, then the IDs returned by this method will be a subset of the IDs in CUDA_VISIBLE_DEVICES. If not, the IDs will fall in the range [0, N...
0.000899
def list_files(self, prefix, flat=False): """ List the files in the layer with the given prefix. flat means only generate one level of a directory, while non-flat means generate all file paths with that prefix. """ layer_path = self.get_path_to_file("") path = os.path.join(lay...
0.011864
def FindAll(params, ctxt, scope, stream, coord, interp): """ This function converts the argument data into a set of hex bytes and then searches the current file for all occurrences of those bytes. data may be any of the basic types or an array of one of the types. If data is an array of signed bytes...
0.001682
def image(self): """ Returns an image array of current render window """ if not hasattr(self, 'ren_win') and hasattr(self, 'last_image'): return self.last_image ifilter = vtk.vtkWindowToImageFilter() ifilter.SetInput(self.ren_win) ifilter.ReadFrontBufferOff() ...
0.003914
def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None): """ If there exist mutually exclusive parameters checks for them and maps param2 to 1.""" def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if param2_name in kwargs: if param1_...
0.004717
def add_axes_at_origin(self): """ Add axes actor at origin Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor """ self.marker_actor = vtk.vtkAxesActor() # renderer = self.renderers[self.loc_to_index(loc)] self.AddActor...
0.006623
def get_version_rank(version): """ Converts a version string to it's rank. Usage:: >>> get_version_rank("4.2.8") 4002008000000 >>> get_version_rank("4.0") 4000000000000 >>> get_version_rank("4.2.8").__class__ <type 'int'> :param version: Current version...
0.005917
def set_restriction(self, command, user, event_types): """ Adds restriction for given `command`. :param command: command on which the restriction should be set. :type command: str :param user: username for which the restriction applies. :type user: str :param eve...
0.002793
def addPhoto(self, photo): """Add a photo to this set. photo - the photo """ method = 'flickr.photosets.addPhoto' _dopost(method, auth=True, photoset_id=self.id, photo_id=photo.id) self.__count += 1 return True
0.007435
async def disable(self, reason=None): """Enters maintenance mode Parameters: reason (str): Reason of disabling Returns: bool: ``True`` on success """ params = {"enable": True, "reason": reason} response = await self._api.put("/v1/agent/maintenance...
0.005333
def _get_updated_values(before_values, after_values): """ Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_va...
0.001776
def clear(self): """ Clears the field represented by this element @rtype: WebElementWrapper @return: Returns itself """ def clear_element(): """ Wrapper to clear element """ return self.element.clear() self.e...
0.004963
def addReadGroupSet(self): """ Adds a new ReadGroupSet into this repo. """ self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) dataUrl = self._args.dataFile indexFile = self._args.indexFile parsed = urlparse.urlparse(dataUrl) ...
0.001273
def get_satellites_by_type(self, s_type): """Generic function to access one of the satellite attribute ie : self.pollers, self.reactionners ... :param s_type: satellite type wanted :type s_type: str :return: self.*type*s :rtype: list """ if hasattr(self,...
0.006061
def jacobian_augmentation(sess, x, X_sub_prev, Y_sub, grads, lmbda, aug_batch_size=512, feed=None): """ Augment an adversary's substit...
0.008158
def sample(self): '''Returns the stream's rows used as sample. These sample rows are used internally to infer characteristics of the source file (e.g. encoding, headers, ...). ''' sample = [] iterator = iter(self.__sample_extended_rows) iterator = self.__apply_pr...
0.004535
def _regroup(self): """Update the output :math:`g` keeping the map :math:`\pi` fixed. Compute the KL between all input and output components. """ # clean up old maps for j in range(self.nout): self.inv_map[j] = [] # find smallest divergence between input com...
0.005019
def sentence(random=random, *args, **kwargs): """ Return a whole sentence >>> mock_random.seed(0) >>> sentence(random=mock_random) "Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston." >>> mock_random.seed(2) >>> sentence(random=mock_random, slugify=True) 'blist...
0.00744
def _wait_response(self, message): """ Private function to get responses from the server. :param message: the received message """ if message is None or message.code != defines.Codes.CONTINUE.number: self.queue.put(message)
0.007246
def appendData(self, content): """ Add characters to the element's pcdata. """ if self.pcdata is not None: self.pcdata += content else: self.pcdata = content
0.052023
def context_list(zap_helper): """List the available contexts.""" contexts = zap_helper.zap.context.context_list if len(contexts): console.info('Available contexts: {0}'.format(contexts[1:-1])) else: console.info('No contexts available in the current session')
0.003436
def search_host_and_dispatch(self, host_name, command, extcmd): # pylint: disable=too-many-branches """Try to dispatch a command for a specific host (so specific scheduler) because this command is related to a host (change notification interval for example) :param host_name: host name t...
0.004704
def regex_in_package_file(regex, filename, package_name, return_match=False): """ Search for a regex in a file contained within the package directory If return_match is True, return the found object instead of a boolean """ filepath = package_file_path(filename, package_name) return regex_in_file(r...
0.002762
def get_extension(media): """Gets the corresponding extension for any Telegram media.""" # Photos are always compressed as .jpg by Telegram if isinstance(media, (types.UserProfilePhoto, types.ChatPhoto, types.MessageMediaPhoto)): return '.jpg' # Documents will come wi...
0.001311
def cloud_init_interface(name, vm_=None, **kwargs): ''' Interface between salt.cloud.lxc driver and lxc.init ``vm_`` is a mapping of vm opts in the salt.cloud format as documented for the lxc driver. This can be used either: - from the salt cloud driver - because you find the argument to g...
0.000086
def get_asset_contents(self): """Gets the content of this asset. return: (osid.repository.AssetContentList) - the asset contents raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from templ...
0.00578
def pretty_const(value): """Make a constant pretty for printing in GUI""" words = value.split('_') pretty = words[0].capitalize() for word in words[1:]: pretty += ' ' + word.lower() return pretty
0.004484
def handle_event(self, event): """ When we get an 'event' type from the bridge handle it by invoking the handler and if needed sending back the result. """ result_id, ptr, method, args = event[1] obj = None result = None try: obj, hand...
0.002926
def SympyCreate(n): """Creation operator for a Hilbert space of dimension `n`, as an instance of `sympy.Matrix`""" a = sympy.zeros(n) for i in range(1, n): a += sympy.sqrt(i) * basis_state(i, n) * basis_state(i-1, n).H return a
0.003922
def _set_clear_mpls_auto_bandwidth_statistics_all(self, v, load=False): """ Setter method for clear_mpls_auto_bandwidth_statistics_all, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_all (rpc) If this variable is read-only (config: false) in the source YANG file, then _...
0.005831
def _parameterize_obj(obj): """Recursively parameterize all strings contained in an object. Parameterizes all values of a Mapping, all items of a Sequence, an unicode string, or pass other objects through unmodified. Byte strings will be interpreted as UTF-8. Args: obj: data to parameteri...
0.001006
def search_unique_identities_slice(db, term, offset, limit): """Look for unique identities using slicing. This function returns those unique identities which match with the given `term`. The term will be compared with name, email, username and source values of each identity. When an empty term is given...
0.000473
def decouple(fn): """ Inverse operation of couple. Create two functions of one argument and one return from a function that takes two arguments and has two returns Examples -------- >>> h = lambda x: (2*x**3, 6*x**2) >>> f, g = decouple(h) >>> f(5) 250 >>> g(5) 150 ...
0.00207
def build_joblist(jobgraph): """Returns a list of jobs, from a passed jobgraph.""" jobset = set() for job in jobgraph: jobset = populate_jobset(job, jobset, depth=1) return list(jobset)
0.004785
def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs): ''' Draws a string of text according to current font settings. :param txt: Text to output :param x: x-coordinate of the top left corner :param y: y-coordinate of the top left corner ...
0.005931
def _pred(aclass): """ :param aclass :return: boolean """ isaclass = inspect.isclass(aclass) return isaclass and aclass.__module__ == _pred.__module__
0.005747
def is_binary(f): """Return True if binary mode.""" # NOTE: order matters here. We don't bail on Python 2 just yet. Both # codecs.open() and io.open() can open in text mode, both set the encoding # attribute. We must do that check first. # If it has a decoding attribute with a value, it is text mod...
0.000997
def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as...
0.008488
def is_valid_ipv6_prefix(ipv6_prefix): """Returns True if given `ipv6_prefix` is a valid IPv6 prefix.""" # Validate input type if not isinstance(ipv6_prefix, str): return False tokens = ipv6_prefix.split('/') if len(tokens) != 2: return False # Validate address/mask and return...
0.002532
def feeds(ctx, assets, pricethreshold, maxage): """ Price Feed Overview """ import builtins witnesses = Witnesses(bitshares_instance=ctx.bitshares) def test_price(p, ref): if math.fabs(float(p / ref) - 1.0) > pricethreshold / 100.0: return click.style(str(p), fg="red") ...
0.001845
def rank_for_in(self, leaderboard_name, member): ''' Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard. ''' if se...
0.00578
def __read_graph(self, network_filename): """ Read .ncol network file :param network_filename: complete path for the .ncol file :return: an undirected network """ self.g = nx.read_edgelist(network_filename, nodetype=int)
0.007435
def define(self, key, value): """ Defines the value for the inputted key by setting both its default and \ value to the inputted value. :param key | <str> value | <variant> """ skey = nstr(key) self._defaults[skey] = value ...
0.01173
def get_agent(self): """Gets the ``Agent`` identified in this authentication credential. :return: the ``Agent`` :rtype: ``osid.authentication.Agent`` :raise: ``OperationFailed`` -- unable to complete request *compliance: mandatory -- This method must be implemented.* "...
0.003876
def shutdown(self): """ Shutdown the application and exit :returns: No return value """ task = asyncio.ensure_future(self.core.shutdown()) self.loop.run_until_complete(task)
0.009009
def ingest(self): """*Import the IFS catalogue into the sherlock-catalogues database* The method first generates a list of python dictionaries from the IFS datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** S...
0.003322
def create_api_gateway_routes( self, lambda_arn, api_name=None, api_key_required=False, authorization_type='NONE', authorizer=None, ...
0.005158
def AddList(self, listName, description, templateID): """Create a new List Provide: List Name, List Description, and List Template Templates Include: Announcements Contacts Custom List Custom List in Datasheet View ...
0.000818
def do_statement(source, start): """returns none if not found other functions that begin with 'do_' raise also this do_ type function passes white space""" start = pass_white(source, start) # start is the fist position after initial start that is not a white space or \n if not start < len(source): ...
0.00374
def _create_add_petabencana_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-petabencana-layer.svg') self.action_add_petabencana_layer = QAction( QIcon(icon), self.tr('Add PetaBencana Flood Layer'), self...
0.002356
def get_parent_bin_ids(self, bin_id): """Gets the parent ``Ids`` of the given bin. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (osid.id.IdList) - the parent ``Ids`` of the bin raise: NotFound - ``bin_id`` is not found raise: NullArgument - ``bin_id`` is ``null`` ...
0.003695
def canFetchMore(self, index): '''Return if more data available for *index*.''' if not index.isValid(): item = self.root else: item = index.internalPointer() return item.canFetchMore()
0.008299
def bounds(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the bounds property in relative coordinates. Bounds is a tuple ((top, left), (height, width))""" ...
0.013333
def process_incoming_tuples(self): """Should be called when tuple was buffered into in_stream This method is equivalent to ``addBoltTasks()`` but is designed for event-driven single-thread bolt. """ # back-pressure if self.output_helper.is_out_queue_available(): self._read_tuples_and_exec...
0.010707
def import_tags(self, tag_nodes): """ Import all the tags form 'wp:tag' nodes, because tags in 'item' nodes are not necessarily all the tags, then use only the nicename, because it's like a slug and the true tag name may be not valid for url usage. """ self.write_...
0.003125
def delete(self, request, bot_id, hook_id, id, format=None): """ Delete an existing telegram recipient --- responseMessages: - code: 401 message: Not authenticated """ bot = self.get_bot(bot_id, request.user) hook = self.get_hook(hook_...
0.00611
def dirpath_to_list(p): ''' dirpath_to_list(path) yields a list of directories contained in the given path specification. A path may be either a single directory name (==> [path]), a :-separated list of directories (==> path.split(':')), a list of directory names (==> path), or None (==> []). Note that...
0.01087
def get_run_threads(ns_run): """ Get the individual threads from a nested sampling run. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing module docstring for more details). Returns ------- threads: list of numpy array Each thread ...
0.000747