text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def slice(self, key): """Slice Scene by dataset index. .. note:: DataArrays that do not have an ``area`` attribute will not be sliced. """ if not self.all_same_area: raise RuntimeError("'Scene' has different areas and cannot " ...
[ "def", "slice", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "all_same_area", ":", "raise", "RuntimeError", "(", "\"'Scene' has different areas and cannot \"", "\"be usefully sliced.\"", ")", "# slice", "new_scn", "=", "self", ".", "copy", "(", "...
35.12
18.92
def get_slowest_files(cls, num=10): """Returns the slowest num files. :param num: The maximum number of results to be returned :type num: int """ cur = cls.get_cursor() q = ( "SELECT file, SUM(elapsed) as sum_elapsed FROM {} GROUP BY file" ...
[ "def", "get_slowest_files", "(", "cls", ",", "num", "=", "10", ")", ":", "cur", "=", "cls", ".", "get_cursor", "(", ")", "q", "=", "(", "\"SELECT file, SUM(elapsed) as sum_elapsed FROM {} GROUP BY file\"", "\" ORDER BY sum_elapsed DESC LIMIT {}\"", ")", "cur", ".", ...
34.166667
18.166667
def fill_labeled_holes(labels, mask=None, size_fn = None): '''Fill all background pixels that are holes inside the foreground A pixel is a hole inside a foreground object if * there is no path from the pixel to the edge AND * there is no path from the pixel to any other non-hole pixel ...
[ "def", "fill_labeled_holes", "(", "labels", ",", "mask", "=", "None", ",", "size_fn", "=", "None", ")", ":", "#", "# The algorithm:", "#", "# Label the background to get distinct background objects", "# Construct a graph of both foreground and background objects.", "# Walk the ...
36.965812
21.153846
def minimum_spanning_tree_prim(self, source, display = None, q = PriorityQueue()): ''' API: minimum_spanning_tree_prim(self, source, display = None, q = PriorityQueue()) Description: Determines a minimum spanning ...
[ "def", "minimum_spanning_tree_prim", "(", "self", ",", "source", ",", "display", "=", "None", ",", "q", "=", "PriorityQueue", "(", ")", ")", ":", "if", "display", "==", "None", ":", "display", "=", "self", ".", "attr", "[", "'display'", "]", "else", ":...
41.773585
16.830189
def output(self): """Simulated model output""" if self._timeseries is None: self.compute() output = self._timeseries[:, self.system.output_vars] if isinstance(self.system, NetworkModel): return self.system._reshape_output(output) else: return o...
[ "def", "output", "(", "self", ")", ":", "if", "self", ".", "_timeseries", "is", "None", ":", "self", ".", "compute", "(", ")", "output", "=", "self", ".", "_timeseries", "[", ":", ",", "self", ".", "system", ".", "output_vars", "]", "if", "isinstance...
35.222222
14.111111
def read_transforms_from_config(cp, section="transforms"): """Returns a list of PyCBC transform instances for a section in the given configuration file. If the transforms are nested (i.e., the output of one transform is the input of another), the returned list will be sorted by the order of the nes...
[ "def", "read_transforms_from_config", "(", "cp", ",", "section", "=", "\"transforms\"", ")", ":", "trans", "=", "[", "]", "for", "subsection", "in", "cp", ".", "get_subsections", "(", "section", ")", ":", "name", "=", "cp", ".", "get_opt_tag", "(", "sectio...
32.153846
20.846154
def writeGif( filename, images, duration=0.1, repeat=True, dither=False, nq=0, subRectangles=True, dispose=None): """ writeGif(filename, images, duration=0.1, repeat=True, dither=False, nq=0, subRectangles=True, dispose=None) Write an animated gif from the specified images. ...
[ "def", "writeGif", "(", "filename", ",", "images", ",", "duration", "=", "0.1", ",", "repeat", "=", "True", ",", "dither", "=", "False", ",", "nq", "=", "0", ",", "subRectangles", "=", "True", ",", "dispose", "=", "None", ")", ":", "# Check PIL", "if...
35.877551
22.530612
def ssh( self, machine, *, username=None, command=None, boot_only=False, discovered=False, wait=300): """SSH into `machine`.""" start_time = time.monotonic() with utils.Spinner() as context: context.msg = colorized( "{autoblue}Deter...
[ "def", "ssh", "(", "self", ",", "machine", ",", "*", ",", "username", "=", "None", ",", "command", "=", "None", ",", "boot_only", "=", "False", ",", "discovered", "=", "False", ",", "wait", "=", "300", ")", ":", "start_time", "=", "time", ".", "mon...
41.477612
15.671642
def _proportions(self): """ndarray representing slice proportions along correct axis.""" return self._slice.proportions( axis=self._axis, include_mr_cat=self._include_mr_cat )
[ "def", "_proportions", "(", "self", ")", ":", "return", "self", ".", "_slice", ".", "proportions", "(", "axis", "=", "self", ".", "_axis", ",", "include_mr_cat", "=", "self", ".", "_include_mr_cat", ")" ]
41.4
14.6
def read(self, *args): """Handles raw client requests and distributes them to the appropriate components""" self.log("Beginning new transaction: ", args, lvl=network) try: sock, msg = args[0], args[1] user = password = client = clientuuid = useruuid = requestdata...
[ "def", "read", "(", "self", ",", "*", "args", ")", ":", "self", ".", "log", "(", "\"Beginning new transaction: \"", ",", "args", ",", "lvl", "=", "network", ")", "try", ":", "sock", ",", "msg", "=", "args", "[", "0", "]", ",", "args", "[", "1", "...
39.353535
22.636364
def pipe_util(func): """ Decorator that handles X objects and partial application for pipe-utils. """ @wraps(func) def pipe_util_wrapper(function, *args, **kwargs): if isinstance(function, XObject): function = ~function original_function = function if args or kw...
[ "def", "pipe_util", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "pipe_util_wrapper", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "function", ",", "XObject", ")", ":", "function", "=...
27.933333
20.933333
def _interpolate_stream_track_kick_aA(self): """Build interpolations of the stream track near the impact in action-angle coordinates""" if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover return None #Already did this #Calculate 1D meanOmega on a fine grid in angle and...
[ "def", "_interpolate_stream_track_kick_aA", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_kick_interpolatedObsTrackAA'", ")", ":", "#pragma: no cover", "return", "None", "#Already did this", "#Calculate 1D meanOmega on a fine grid in angle and interpolate", "dmOs...
58.214286
19.071429
def loadZone(self, zone, callback=None, errback=None): """ Load an existing zone into a high level Zone object. :param str zone: zone name, like 'example.com' :rtype: :py:class:`ns1.zones.Zone` """ import ns1.zones zone = ns1.zones.Zone(self.config, zone) ...
[ "def", "loadZone", "(", "self", ",", "zone", ",", "callback", "=", "None", ",", "errback", "=", "None", ")", ":", "import", "ns1", ".", "zones", "zone", "=", "ns1", ".", "zones", ".", "Zone", "(", "self", ".", "config", ",", "zone", ")", "return", ...
36.4
13.4
def widgets(self): """ Get the Ext JS specific customization from the activity. :return: The Ext JS specific customization in `list(dict)` form """ customization = self.activity._json_data.get('customization') if customization and "ext" in customization.keys(): ...
[ "def", "widgets", "(", "self", ")", ":", "customization", "=", "self", ".", "activity", ".", "_json_data", ".", "get", "(", "'customization'", ")", "if", "customization", "and", "\"ext\"", "in", "customization", ".", "keys", "(", ")", ":", "return", "custo...
32.25
21.75
def load_roi(self, infile, reload_sources=False, params=None, mask=None): """This function reloads the analysis state from a previously saved instance generated with `~fermipy.gtanalysis.GTAnalysis.write_roi`. Parameters ---------- infile : str reload_sources :...
[ "def", "load_roi", "(", "self", ",", "infile", ",", "reload_sources", "=", "False", ",", "params", "=", "None", ",", "mask", "=", "None", ")", ":", "infile", "=", "utils", ".", "resolve_path", "(", "infile", ",", "workdir", "=", "self", ".", "workdir",...
36.880435
18.206522
def load_uri(self, uri): """ Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://...
[ "def", "load_uri", "(", "self", ",", "uri", ")", ":", "# if self.verbose: printDebug(\"----------\")", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"Reading: <%s>\"", "%", "uri", ",", "fg", "=", "\"green\"", ")", "success", "=", "False", "sorted_fmt_o...
46.155556
28.288889
def render(self, tmpl_name, request_env): """ Render the specified template and return the output. Args: tmpl_name (str): file name of the template request_env (dict): request environment Returns: str - the rendered template """ retu...
[ "def", "render", "(", "self", ",", "tmpl_name", ",", "request_env", ")", ":", "return", "super", "(", "WebApplication", ",", "self", ")", ".", "render", "(", "tmpl_name", ",", "request_env", ")" ]
28.384615
19.307692
def warning(self, msg, *args, **kwargs): """Log 'msg % args' with the warning severity level""" self._log("WARNING", msg, args, kwargs)
[ "def", "warning", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_log", "(", "\"WARNING\"", ",", "msg", ",", "args", ",", "kwargs", ")" ]
49.666667
2.333333
def Items(cls): """non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ...
[ "def", "Items", "(", "cls", ")", ":", "l", "=", "list", "(", ")", "for", "attr", ",", "value", "in", "get_all_attributes", "(", "cls", ")", ":", "# if it's not a class(Constant)", "if", "not", "inspect", ".", "isclass", "(", "value", ")", ":", "l", "."...
27.148148
15.703704
def add_host_to_segment(ipaddress, name, description, network_address, auth, url): ''' Function to abstract existing add_scope_ip_function. Allows for use of network address rather than forcing human to learn the scope_id :param ipaddress: :param name: name of the owner of this host :param descrip...
[ "def", "add_host_to_segment", "(", "ipaddress", ",", "name", ",", "description", ",", "network_address", ",", "auth", ",", "url", ")", ":", "scope_id", "=", "get_scope_id", "(", "network_address", ",", "auth", ",", "url", ")", "add_scope_ip", "(", "ipaddress",...
35.692308
37.615385
def connect(self, host=None, port=None, connect=False, **kwargs): """ Explicitly creates the MongoClient; this method must be used in order to specify a non-default host or port to the MongoClient. Takes arguments identical to MongoClient.__init__""" try: self.__conne...
[ "def", "connect", "(", "self", ",", "host", "=", "None", ",", "port", "=", "None", ",", "connect", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "__connection", "=", "MongoClient", "(", "host", "=", "host", ",", "port", ...
66.5
26.5
def status(self): """Check power status""" vm = self.get_vm_failfast(self.config['name']) extra = self.config['extra'] parserFriendly = self.config['parserFriendly'] status_to_print = [] if extra: status_to_print = \ [["vmname", "powerstate", ...
[ "def", "status", "(", "self", ")", ":", "vm", "=", "self", ".", "get_vm_failfast", "(", "self", ".", "config", "[", "'name'", "]", ")", "extra", "=", "self", ".", "config", "[", "'extra'", "]", "parserFriendly", "=", "self", ".", "config", "[", "'par...
40.16
18
def bootstrap_trajectories(trajs, correlation_length): """ Generates a randomly resampled count matrix given the input coordinates. See API function for full documentation. """ from scipy.stats import rv_discrete # if we have just one trajectory, put it into a one-element list: if (isinstan...
[ "def", "bootstrap_trajectories", "(", "trajs", ",", "correlation_length", ")", ":", "from", "scipy", ".", "stats", "import", "rv_discrete", "# if we have just one trajectory, put it into a one-element list:", "if", "(", "isinstance", "(", "trajs", "[", "0", "]", ",", ...
32.071429
16.357143
def choose_spot_zone(zones, bid, spot_history): """ Returns the zone to put the spot request based on, in order of priority: 1) zones with prices currently under the bid 2) zones with the most stable price :param list[boto.ec2.zone.Zone] zones: :param float bid: :param list[boto.ec2...
[ "def", "choose_spot_zone", "(", "zones", ",", "bid", ",", "spot_history", ")", ":", "# Create two lists of tuples of form: [(zone.name, std_deviation), ...] one for zones", "# over the bid price and one for zones under bid price. Each are sorted by increasing", "# standard deviation values."...
43.745455
23.236364
def authenticate(self): """Aquire authorization token for using thetvdb apis.""" if self.__token: try: resp = self._refresh_token() except exceptions.TVDBRequestException as err: # if a 401 is the cause try to login if getattr(err.r...
[ "def", "authenticate", "(", "self", ")", ":", "if", "self", ".", "__token", ":", "try", ":", "resp", "=", "self", ".", "_refresh_token", "(", ")", "except", "exceptions", ".", "TVDBRequestException", "as", "err", ":", "# if a 401 is the cause try to login", "i...
35.1875
14.4375
def make_request(self, session, url, **kwargs): """Make a HTTP GET request. :param url: The URL to get. :returns: The response to the request. :rtype: requests.Response """ log.debug('Making request: GET %s %s' % (url, kwargs)) return session.get(url, **kwargs)
[ "def", "make_request", "(", "self", ",", "session", ",", "url", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'Making request: GET %s %s'", "%", "(", "url", ",", "kwargs", ")", ")", "return", "session", ".", "get", "(", "url", ",", "*...
34.444444
9.777778
def fetch_package_version(dist_name): """ >>> fetch_package_version('sentry') """ try: # Importing pkg_resources can be slow, so only import it # if we need it. import pkg_resources except ImportError: # pkg_resource is not available on Google App Engine raise...
[ "def", "fetch_package_version", "(", "dist_name", ")", ":", "try", ":", "# Importing pkg_resources can be slow, so only import it", "# if we need it.", "import", "pkg_resources", "except", "ImportError", ":", "# pkg_resource is not available on Google App Engine", "raise", "NotImpl...
35.571429
14.285714
def ad_unif_inf(statistic): """ Approximates the limiting distribution to about 5 decimal digits. """ z = statistic if z < 2: return (exp(-1.2337141 / z) / sqrt(z) * (2.00012 + (.247105 - (.0649821 - (.0347962 - (.011672 - .0016...
[ "def", "ad_unif_inf", "(", "statistic", ")", ":", "z", "=", "statistic", "if", "z", "<", "2", ":", "return", "(", "exp", "(", "-", "1.2337141", "/", "z", ")", "/", "sqrt", "(", "z", ")", "*", "(", "2.00012", "+", "(", ".247105", "-", "(", ".064...
41
22.166667
def unregister_signals(self): """Unregister signals.""" from .models import Collection from .percolator import collection_inserted_percolator, \ collection_removed_percolator, collection_updated_percolator # Unregister Record signals if hasattr(self, 'update_function'...
[ "def", "unregister_signals", "(", "self", ")", ":", "from", ".", "models", "import", "Collection", "from", ".", "percolator", "import", "collection_inserted_percolator", ",", "collection_removed_percolator", ",", "collection_updated_percolator", "# Unregister Record signals",...
55.466667
18.466667
def GetUsernameForPath(self, path): """Retrieves a username for a specific path. This is determining if a specific path is within a user's directory and returning the username of the user if so. Args: path (str): path. Returns: str: username or None if the path does not appear to be w...
[ "def", "GetUsernameForPath", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "lower", "(", ")", "user_accounts", "=", "self", ".", "_user_accounts", ".", "get", "(", "self", ".", "CURRENT_SESSION", ",", "{", "}", ")", "for", "user_account",...
28.12
22
def _make_split(self): """ This method makes the split """ self.bbox_list = [] self.info_list = [] for grid_idx, grid_bbox in enumerate(self.bbox_grid): if self._intersects_area(grid_bbox): bbox_splitter = BBoxSplitter([grid_bbox.geometry], grid_bbox...
[ "def", "_make_split", "(", "self", ")", ":", "self", ".", "bbox_list", "=", "[", "]", "self", ".", "info_list", "=", "[", "]", "for", "grid_idx", ",", "grid_bbox", "in", "enumerate", "(", "self", ".", "bbox_grid", ")", ":", "if", "self", ".", "_inter...
38.944444
23.277778
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
[ "def", "_find_adapter", "(", "registry", ",", "ob", ")", ":", "types", "=", "_always_object", "(", "inspect", ".", "getmro", "(", "getattr", "(", "ob", ",", "'__class__'", ",", "type", "(", "ob", ")", ")", ")", ")", "for", "t", "in", "types", ":", ...
40.666667
15.333333
def _mod_repo_in_file(repo, repostr, filepath): ''' Replace a repo entry in filepath with repostr ''' with salt.utils.files.fopen(filepath) as fhandle: output = [] for line in fhandle: cols = salt.utils.args.shlex_split( salt.utils.stringutils.to_unicode(line)...
[ "def", "_mod_repo_in_file", "(", "repo", ",", "repostr", ",", "filepath", ")", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "filepath", ")", "as", "fhandle", ":", "output", "=", "[", "]", "for", "line", "in", "fhandle", ":", "c...
36.5625
17.5625
def restore_renamed_serializable_attributes(self): """Hook for the future if attributes have been renamed. The old attribute names will have been restored in the __dict__.update in __setstate__, so this routine should move attribute values to their new names. """ if hasat...
[ "def", "restore_renamed_serializable_attributes", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'start_addr'", ")", ":", "self", ".", "origin", "=", "self", ".", "start_addr", "log", ".", "debug", "(", "f\"moving start_addr to origin: {self.start_addr}\...
48.9
14.3
def basic_logging(self) -> None: """ Call this on the client object to create log handlers to output request and response messages. """ # Request handler if len(request_log.handlers) == 0: request_handler = logging.StreamHandler() request_handler.s...
[ "def", "basic_logging", "(", "self", ")", "->", "None", ":", "# Request handler", "if", "len", "(", "request_log", ".", "handlers", ")", "==", "0", ":", "request_handler", "=", "logging", ".", "StreamHandler", "(", ")", "request_handler", ".", "setFormatter", ...
40.619048
13.380952
def get_sesames(email, password, device_ids=None, nicknames=None, timeout=5): """Return list of available Sesame objects.""" sesames = [] account = CandyHouseAccount(email, password, timeout=timeout) for sesame in account.sesames: if device_ids is not None and sesame['device_id'] not in device_...
[ "def", "get_sesames", "(", "email", ",", "password", ",", "device_ids", "=", "None", ",", "nicknames", "=", "None", ",", "timeout", "=", "5", ")", ":", "sesames", "=", "[", "]", "account", "=", "CandyHouseAccount", "(", "email", ",", "password", ",", "...
38.153846
23.846154
def getObjectWorkflowStates(self): """ This method is used as a metacolumn. Returns a dictionary with the workflow id as key and workflow state as value. :returns: {'review_state':'active',...} """ workflow = getToolByName(self, 'portal_workflow') states =...
[ "def", "getObjectWorkflowStates", "(", "self", ")", ":", "workflow", "=", "getToolByName", "(", "self", ",", "'portal_workflow'", ")", "states", "=", "{", "}", "for", "w", "in", "workflow", ".", "getWorkflowsFor", "(", "self", ")", ":", "state", "=", "w", ...
36.384615
12.076923
def write_sample_sheet(path, accessions, names, celfile_urls, sel=None): """Write the sample sheet.""" with open(path, 'wb') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) # write he...
[ "def", "write_sample_sheet", "(", "path", ",", "accessions", ",", "names", ",", "celfile_urls", ",", "sel", "=", "None", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "ofh", ":", "writer", "=", "csv", ".", "writer", "(", "ofh", ",", ...
44.8
17.666667
def _fromfile(self, fh): """Initialize instance from open file.""" fh.seek(0) data = fh.read(4096) if (len(data) < 7) or not (b'0' < data[1:2] < b'8'): raise ValueError("Not a Netpbm file:\n%s" % data[:32]) try: self._read_pam_header(data) except E...
[ "def", "_fromfile", "(", "self", ",", "fh", ")", ":", "fh", ".", "seek", "(", "0", ")", "data", "=", "fh", ".", "read", "(", "4096", ")", "if", "(", "len", "(", "data", ")", "<", "7", ")", "or", "not", "(", "b'0'", "<", "data", "[", "1", ...
36.846154
16
def init_app(self, app, entry_point_group='invenio_assets.bundles', **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. :param entry_point_group: A name of entry point group used to load ``webassets`` bundles. .. v...
[ "def", "init_app", "(", "self", ",", "app", ",", "entry_point_group", "=", "'invenio_assets.bundles'", ",", "*", "*", "kwargs", ")", ":", "self", ".", "init_config", "(", "app", ")", "self", ".", "env", ".", "init_app", "(", "app", ")", "self", ".", "c...
33.4
17.6
def _get_notifier(config): ''' Check the context for the notifier and construct it if not present ''' if 'inotify.notifier' not in __context__: __context__['inotify.queue'] = collections.deque() wm = pyinotify.WatchManager() __context__['inotify.notifier'] = pyinotify.Notifier(wm...
[ "def", "_get_notifier", "(", "config", ")", ":", "if", "'inotify.notifier'", "not", "in", "__context__", ":", "__context__", "[", "'inotify.queue'", "]", "=", "collections", ".", "deque", "(", ")", "wm", "=", "pyinotify", ".", "WatchManager", "(", ")", "__co...
42.692308
16.692308
def resample(sig, old=1, new=1, order=3, zero=0.): """ Generic resampler based on Waring-Lagrange interpolators. Parameters ---------- sig : Input signal (any iterable). old : Time duration reference (defaults to 1, allowing percentages to the ``new`` keyword argument). This can be float number...
[ "def", "resample", "(", "sig", ",", "old", "=", "1", ",", "new", "=", "1", ",", "order", "=", "3", ",", "zero", "=", "0.", ")", ":", "sig", "=", "Stream", "(", "sig", ")", "threshold", "=", ".5", "*", "(", "order", "+", "1", ")", "step", "=...
32.661538
24.076923
def summary_df_from_multi(multi_in, inds_to_keep=None, **kwargs): """Apply summary_df to a multiindex while preserving some levels. Parameters ---------- multi_in: multiindex pandas DataFrame inds_to_keep: None or list of strs, optional Index levels to preserve. kwargs: dict, optional ...
[ "def", "summary_df_from_multi", "(", "multi_in", ",", "inds_to_keep", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Need to pop include true values and add separately at the end as", "# otherwise we get multiple true values added", "include_true_values", "=", "kwargs", "."...
45.836364
17.836364
def decode_token(token): """ Top-level method to decode a JWT. Takes either a compact-encoded JWT with a single signature, or a multi-sig JWT in the JSON-serialized format. Returns the deserialized token, as a dict. The signatures will still be base64-encoded """ if isinstance(token, (u...
[ "def", "decode_token", "(", "token", ")", ":", "if", "isinstance", "(", "token", ",", "(", "unicode", ",", "str", ")", ")", ":", "return", "_decode_token_compact", "(", "token", ")", "else", ":", "return", "_decode_token_json", "(", "token", ")" ]
29.714286
13
def reduce(self): """Removes results rows whose n-grams are contained in larger n-grams.""" self._logger.info('Reducing the n-grams') # This does not make use of any pandas functionality; it # probably could, and if so ought to. data = {} labels = {} # Der...
[ "def", "reduce", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Reducing the n-grams'", ")", "# This does not make use of any pandas functionality; it", "# probably could, and if so ought to.", "data", "=", "{", "}", "labels", "=", "{", "}", "# Der...
48.820513
14.923077
def sd_mount_status(self): """Request for SD Mount status if available. """ request = { "command": "sd_mount_status" } responses = self.complex_request(request) result = None if len(responses) > 0: result = responses[0].get('status') ...
[ "def", "sd_mount_status", "(", "self", ")", ":", "request", "=", "{", "\"command\"", ":", "\"sd_mount_status\"", "}", "responses", "=", "self", ".", "complex_request", "(", "request", ")", "result", "=", "None", "if", "len", "(", "responses", ")", ">", "0"...
29.545455
11.818182
def verify_rsa_signature(signature, signature_scheme, public_key, data): """ <Purpose> Determine whether the corresponding private key of 'public_key' produced 'signature'. verify_signature() will use the public key, signature scheme, and 'data' to complete the verification. >>> public, private = ...
[ "def", "verify_rsa_signature", "(", "signature", ",", "signature_scheme", ",", "public_key", ",", "data", ")", ":", "# Does 'public_key' have the correct format?", "# This check will ensure 'public_key' conforms to", "# 'securesystemslib.formats.PEMRSA_SCHEMA'. Raise", "# 'securesyste...
37.408602
25.688172
def sample_lonlat(self, n): """ Sample 2D distribution of points in lon, lat """ # From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form # However, Martin et al. (2009) use PA theta "from North to East" # Definition of phi (position angle) is offset by pi/4 ...
[ "def", "sample_lonlat", "(", "self", ",", "n", ")", ":", "# From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form", "# However, Martin et al. (2009) use PA theta \"from North to East\"", "# Definition of phi (position angle) is offset by pi/4", "# Definition of t (eccentric anamoly...
40.481481
15.888889
def get_dos(self): '''Find the total DOS shifted by the Fermi energy''' # find the dos file fildos = '' for f in self._files: with open(f, 'r') as fp: first_line = next(fp) if "E (eV)" in first_line and "Int dos(E)" in first_line: ...
[ "def", "get_dos", "(", "self", ")", ":", "# find the dos file", "fildos", "=", "''", "for", "f", "in", "self", ".", "_files", ":", "with", "open", "(", "f", ",", "'r'", ")", "as", "fp", ":", "first_line", "=", "next", "(", "fp", ")", "if", "\"E (eV...
39.413793
20.517241
def get_scheduler_info(): """Gets the scheduler info.""" scheduler = current_app.apscheduler d = OrderedDict([ ('current_host', scheduler.host_name), ('allowed_hosts', scheduler.allowed_hosts), ('running', scheduler.running) ]) return jsonify(d)
[ "def", "get_scheduler_info", "(", ")", ":", "scheduler", "=", "current_app", ".", "apscheduler", "d", "=", "OrderedDict", "(", "[", "(", "'current_host'", ",", "scheduler", ".", "host_name", ")", ",", "(", "'allowed_hosts'", ",", "scheduler", ".", "allowed_hos...
23.416667
18.916667
def delete_volume(self, volume_name: str): """Removes/stops a docker volume. Only the manager nodes can delete a volume Args: volume_name (string): Name of the volume """ # Raise an exception if we are not a manager if not self._manager: raise Ru...
[ "def", "delete_volume", "(", "self", ",", "volume_name", ":", "str", ")", ":", "# Raise an exception if we are not a manager", "if", "not", "self", ".", "_manager", ":", "raise", "RuntimeError", "(", "'Volumes can only be deleted '", "'on swarm manager nodes'", ")", "# ...
32.066667
17.266667
def integrate(self, mass_min, mass_max, log_mode=True, weight=False, steps=1e4): """ Numerical Riemannn integral of the IMF (stupid simple). Parameters: ----------- mass_min: minimum mass bound for integration (solar masses) mass_max: maximum mass bound for integration (solar ma...
[ "def", "integrate", "(", "self", ",", "mass_min", ",", "mass_max", ",", "log_mode", "=", "True", ",", "weight", "=", "False", ",", "steps", "=", "1e4", ")", ":", "if", "log_mode", ":", "d_log_mass", "=", "(", "np", ".", "log10", "(", "mass_max", ")",...
40.8125
25.9375
def check_sync(self): """Check if sync is required based on last sync date.""" # If refresh interval is not specified, we should refresh every time. expiration = utcnow() refresh_td = current_app.config.get('GITHUB_REFRESH_TIMEDELTA') if refresh_td: expiration -= refr...
[ "def", "check_sync", "(", "self", ")", ":", "# If refresh interval is not specified, we should refresh every time.", "expiration", "=", "utcnow", "(", ")", "refresh_td", "=", "current_app", ".", "config", ".", "get", "(", "'GITHUB_REFRESH_TIMEDELTA'", ")", "if", "refres...
47.777778
17.333333
def insert(self, stim, position): """Inserts a new stimulus into the list at the given position :param stim: stimulus to insert into protocol :type stim: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>` :param position: index (row) of location to insert to :type...
[ "def", "insert", "(", "self", ",", "stim", ",", "position", ")", ":", "if", "position", "==", "-", "1", ":", "position", "=", "self", ".", "rowCount", "(", ")", "stim", ".", "setReferenceVoltage", "(", "self", ".", "caldb", ",", "self", ".", "calv", ...
46.461538
18.153846
def tai_timestamp(): """Return current TAI timestamp.""" timestamp = time.time() date = datetime.utcfromtimestamp(timestamp) if date.year < 1972: return timestamp offset = 10 + timestamp leap_seconds = [ (1972, 1, 1), (1972, 7, 1), (1973, 1, 1), (1974, 1, ...
[ "def", "tai_timestamp", "(", ")", ":", "timestamp", "=", "time", ".", "time", "(", ")", "date", "=", "datetime", ".", "utcfromtimestamp", "(", "timestamp", ")", "if", "date", ".", "year", "<", "1972", ":", "return", "timestamp", "offset", "=", "10", "+...
24.512195
17.219512
def demographics(self): """ Get the demographic breakdown for an input targeting criteria """ body = { "audience_definition": self.audience_definition, "targeting_inputs": self.targeting_inputs } resource = self.RESOURCE_DEMOGRAPHICS.format(account...
[ "def", "demographics", "(", "self", ")", ":", "body", "=", "{", "\"audience_definition\"", ":", "self", ".", "audience_definition", ",", "\"targeting_inputs\"", ":", "self", ".", "targeting_inputs", "}", "resource", "=", "self", ".", "RESOURCE_DEMOGRAPHICS", ".", ...
39.692308
17.846154
def get_objective_bank_ids_by_activity(self, activity_id): """Gets the list of ``ObjectiveBank Ids`` mapped to a ``Activity``. arg: activity_id (osid.id.Id): ``Id`` of a ``Activity`` return: (osid.id.IdList) - list of objective bank ``Ids`` raise: NotFound - ``activity_id`` is not f...
[ "def", "get_objective_bank_ids_by_activity", "(", "self", ",", "activity_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bin_ids_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'LEARNING'", ",", "local", "=", "Tr...
49.318182
19.409091
def show_service_certificate(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Return information about a service certificate CLI Example: .. code-block:: bash salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\ thumbalgorithm=sha1 ...
[ "def", "show_service_certificate", "(", "kwargs", "=", "None", ",", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The get_service_certificate function must be called with -f or --...
28.102564
26.25641
def format_adjustments(self, dates, assets): """ Build a dict of Adjustment objects in the format expected by AdjustedArray. Returns a dict of the form: { # Integer index into `dates` for the date on which we should # apply the list of adjustments. ...
[ "def", "format_adjustments", "(", "self", ",", "dates", ",", "assets", ")", ":", "make_adjustment", "=", "partial", "(", "make_adjustment_from_labels", ",", "dates", ",", "assets", ")", "min_date", ",", "max_date", "=", "dates", "[", "[", "0", ",", "-", "1...
39.923077
22.353846
def tuplewrap(value): """ INTENDED TO TURN lists INTO tuples FOR USE AS KEYS """ if is_many(value): return tuple(tuplewrap(v) if is_sequence(v) else v for v in value) return unwrap(value),
[ "def", "tuplewrap", "(", "value", ")", ":", "if", "is_many", "(", "value", ")", ":", "return", "tuple", "(", "tuplewrap", "(", "v", ")", "if", "is_sequence", "(", "v", ")", "else", "v", "for", "v", "in", "value", ")", "return", "unwrap", "(", "valu...
30
14.285714
def get_scoped_variable_from_name(self, name): """ Get the scoped variable for a unique name :param name: the unique name of the scoped variable :return: the scoped variable specified by the name :raises exceptions.AttributeError: if the name is not in the the scoped_variables dictionar...
[ "def", "get_scoped_variable_from_name", "(", "self", ",", "name", ")", ":", "for", "scoped_variable_id", ",", "scoped_variable", "in", "self", ".", "scoped_variables", ".", "items", "(", ")", ":", "if", "scoped_variable", ".", "name", "==", "name", ":", "retur...
52.363636
21.090909
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1): """Creates an API command object. :Parameters: Command : unicode Command string. Reply : unicode Expected reply. By default any reply is accepted (except errors which raise an ...
[ "def", "Command", "(", "self", ",", "Command", ",", "Reply", "=", "u''", ",", "Block", "=", "False", ",", "Timeout", "=", "30000", ",", "Id", "=", "-", "1", ")", ":", "from", "api", "import", "Command", "as", "CommandClass", "return", "CommandClass", ...
40.038462
23.5
def file_crc32(filename, chunksize=_CHUNKSIZE): """ calculate the CRC32 of the contents of filename """ check = 0 with open(filename, 'rb') as fd: for data in iter(lambda: fd.read(chunksize), ""): check = crc32(data, check) return check
[ "def", "file_crc32", "(", "filename", ",", "chunksize", "=", "_CHUNKSIZE", ")", ":", "check", "=", "0", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fd", ":", "for", "data", "in", "iter", "(", "lambda", ":", "fd", ".", "read", "(", "ch...
27.2
13.2
def check_game_end(self): '''Checks for the game's win/lose conditions and 'alters' the game state to reflect the condition found. If the game has not been won or lost then it just returns the game state unaltered.''' if self.player in self.crashes.union(self.robots): ...
[ "def", "check_game_end", "(", "self", ")", ":", "if", "self", ".", "player", "in", "self", ".", "crashes", ".", "union", "(", "self", ".", "robots", ")", ":", "return", "self", ".", "end_game", "(", "'You Died!'", ")", "elif", "not", "self", ".", "ro...
38.083333
19.583333
def __do_case_6_work(d_w, d_u, case_1, case_2, case_3, dfs_data): """Encapsulates the work that will be done for case 6 of __embed_frond, since it gets used in more than one place.""" # --We should only ever see u-cases 1 and 3 if case_2: # --We should never get here return False co...
[ "def", "__do_case_6_work", "(", "d_w", ",", "d_u", ",", "case_1", ",", "case_2", ",", "case_3", ",", "dfs_data", ")", ":", "# --We should only ever see u-cases 1 and 3", "if", "case_2", ":", "# --We should never get here", "return", "False", "comp_d_w", "=", "abs", ...
26.363636
17.151515
def print_help(self, short=False): """ Print help message and exit. :param short: print short help only :type short: bool """ header = [ u"", u"NAME", u" %s - %s" % (self.NAME, self.HELP["description"]), u"", ] ...
[ "def", "print_help", "(", "self", ",", "short", "=", "False", ")", ":", "header", "=", "[", "u\"\"", ",", "u\"NAME\"", ",", "u\" %s - %s\"", "%", "(", "self", ".", "NAME", ",", "self", ".", "HELP", "[", "\"description\"", "]", ")", ",", "u\"\"", ","...
37.034884
20.988372
def render_er(input, output, mode='auto', include_tables=None, include_columns=None, exclude_tables=None, exclude_columns=None, schema=None): """ Transform the metadata into a representation. :param input: Possible inputs are instances of: MetaData: SQLAlchemy Metadata Declarat...
[ "def", "render_er", "(", "input", ",", "output", ",", "mode", "=", "'auto'", ",", "include_tables", "=", "None", ",", "include_columns", "=", "None", ",", "exclude_tables", "=", "None", ",", "exclude_columns", "=", "None", ",", "schema", "=", "None", ")", ...
57.382353
23.617647
def tear_down_plugs(self): """Call tearDown() on all instantiated plugs. Note that initialize_plugs must have been called before calling this method, and initialize_plugs must be called again after calling this method if you want to access the plugs attribute again. Any exceptions in tearDown() me...
[ "def", "tear_down_plugs", "(", "self", ")", ":", "_LOG", ".", "debug", "(", "'Tearing down all plugs.'", ")", "for", "plug_type", ",", "plug_instance", "in", "six", ".", "iteritems", "(", "self", ".", "_plugs_by_type", ")", ":", "if", "plug_instance", ".", "...
39.857143
18
def get_group_model(): """ Get the group model from the ``JOYOUS_GROUP_MODEL`` setting. Useful for developers that need the group model. Defaults to the standard :class:`ls.joyous.models.GroupPage` model if no custom model is defined. """ from django.apps import apps model_string = get_g...
[ "def", "get_group_model", "(", ")", ":", "from", "django", ".", "apps", "import", "apps", "model_string", "=", "get_group_model_string", "(", ")", "try", ":", "return", "apps", ".", "get_model", "(", "model_string", ")", "except", "ValueError", ":", "raise", ...
39.176471
18.941176
def _BuildResponse(self, status, rendered_data, method_name=None, headers=None, content_length=None, token=None, no_audit_log=False): """Builds HTTPResponse object from ...
[ "def", "_BuildResponse", "(", "self", ",", "status", ",", "rendered_data", ",", "method_name", "=", "None", ",", "headers", "=", "None", ",", "content_length", "=", "None", ",", "token", "=", "None", ",", "no_audit_log", "=", "False", ")", ":", "# To avoid...
37.55814
18.674419
def install_versioning(self, conn): """ Create the version table into an already populated database and insert the base script. :param conn: a DB API 2 connection """ logging.info('Creating the versioning table %s', self.version_table) conn.executescript(CREATE_V...
[ "def", "install_versioning", "(", "self", ",", "conn", ")", ":", "logging", ".", "info", "(", "'Creating the versioning table %s'", ",", "self", ".", "version_table", ")", "conn", ".", "executescript", "(", "CREATE_VERSIONING", "%", "self", ".", "version_table", ...
40
15.8
def _model_abilities_one_components(self,beta): """ Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array ...
[ "def", "_model_abilities_one_components", "(", "self", ",", "beta", ")", ":", "parm", "=", "np", ".", "array", "(", "[", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "transform", "(", "beta", "[", "k", "]", ")", "...
53.228571
41.085714
def install(self, ref, table_name=None, index_columns=None,logger=None): """ Finds partition by reference and installs it to warehouse db. Args: ref (str): id, vid (versioned id), name or vname (versioned name) of the partition. """ try: obj_number = ObjectNum...
[ "def", "install", "(", "self", ",", "ref", ",", "table_name", "=", "None", ",", "index_columns", "=", "None", ",", "logger", "=", "None", ")", ":", "try", ":", "obj_number", "=", "ObjectNumber", ".", "parse", "(", "ref", ")", "if", "isinstance", "(", ...
36.888889
22.444444
def do_session_info(self, params): """ \x1b[1mNAME\x1b[0m session_info - Shows information about the current session \x1b[1mSYNOPSIS\x1b[0m session_info [match] \x1b[1mOPTIONS\x1b[0m * match: only include lines that match (default: '') \x1b[1mEXAMPLES\x1b[0m > session_info ...
[ "def", "do_session_info", "(", "self", ",", "params", ")", ":", "fmt_str", "=", "\"\"\"state=%s\nsessionid=%s\nauth_info=%s\nprotocol_version=%d\nxid=%d\nlast_zxid=0x%.16x\ntimeout=%d\nclient=%s\nserver=%s\ndata_watches=%s\nchild_watches=%s\"\"\"", "content", "=", "fmt_str", "%", "(", ...
23.520833
17.354167
def get(self, addr, count): """ Read list of ``count`` values at ``addr`` memory location in DataBank. :param addr: Address to read from :param count: Number of entries to retrieve :return: list of entry values :except IndexError: Raised if address range falls outside va...
[ "def", "get", "(", "self", ",", "addr", ",", "count", ")", ":", "addr", "-=", "self", ".", "_start_addr", "data", "=", "self", ".", "_data", "[", "addr", ":", "addr", "+", "count", "]", "if", "len", "(", "data", ")", "!=", "count", ":", "addr", ...
38.9375
14.9375
def _at_raw(self, calculator, rule, scope, block): """ Implements @raw """ value = calculator.calculate(block.argument) sys.stderr.write("%s\n" % repr(value))
[ "def", "_at_raw", "(", "self", ",", "calculator", ",", "rule", ",", "scope", ",", "block", ")", ":", "value", "=", "calculator", ".", "calculate", "(", "block", ".", "argument", ")", "sys", ".", "stderr", ".", "write", "(", "\"%s\\n\"", "%", "repr", ...
32.166667
7.5
def _rpc(self, method, *args): """Sends an rpc to the app. Args: method: str, The name of the method to execute. args: any, The args of the method. Returns: The result of the rpc. Raises: ProtocolError: Something went wrong with the prot...
[ "def", "_rpc", "(", "self", ",", "method", ",", "*", "args", ")", ":", "with", "self", ".", "_lock", ":", "apiid", "=", "next", "(", "self", ".", "_counter", ")", "data", "=", "{", "'id'", ":", "apiid", ",", "'method'", ":", "method", ",", "'para...
38.526316
14.947368
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): """Handle an AgentJobSSHDebug message. Send the data back to the client""" await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, ...
[ "async", "def", "handle_agent_job_ssh_debug", "(", "self", ",", "_", ",", "message", ":", "AgentJobSSHDebug", ")", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "message", ".", "job_id", "[", "0", "]", ",", "Backen...
103.25
52.75
def merge(self, other): """Merges object with other NameVariants object, not set values of self.variants are replace by values from other object. """ if not isinstance(other, NameVariants): raise TypeError("NameVariants isinstance can be merge with" ...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "NameVariants", ")", ":", "raise", "TypeError", "(", "\"NameVariants isinstance can be merge with\"", "\"other isinstance of the same class\"", ")", "for", "key", "in"...
43.545455
18.818182
def list(per_page=None, page=None): """ List of payments. You have to handle pagination manually :param page: the page number :type page: int|None :param per_page: number of payment per page. It's a good practice to increase this number if you know that you will need a l...
[ "def", "list", "(", "per_page", "=", "None", ",", "page", "=", "None", ")", ":", "# Comprehension dict are not supported in Python 2.6-. You can use this commented line instead of the current", "# line when you drop support for Python 2.6.", "# pagination = {key: value for (key, value) i...
49.857143
27.857143
def get_node_by_path(self, path): """Get a node from a node path. Warning: use of this method assumes that sibling nodes have unique names, if this is not assured the `get_node_by_coord` method can be used instead. | Example with absolute node path: | `node.get_node_by_path...
[ "def", "get_node_by_path", "(", "self", ",", "path", ")", ":", "if", "path", "==", "\".\"", ":", "return", "self", "elif", "path", ".", "lstrip", "(", ")", ".", "startswith", "(", "(", "\".\"", ",", "\"./\"", ")", ")", "or", "not", "isinstance", "(",...
43.911765
23.411765
def plotMulti(self, atrix, atriy, cyclist, title, path='/', legend=None, labelx=None, labely=None, logx=False, logy=False, base=10, sparse=1, pdf=False, limits=None): ''' Method for plotting multiple plots and saving it to multiple pngs or PD...
[ "def", "plotMulti", "(", "self", ",", "atrix", ",", "atriy", ",", "cyclist", ",", "title", ",", "path", "=", "'/'", ",", "legend", "=", "None", ",", "labelx", "=", "None", ",", "labely", "=", "None", ",", "logx", "=", "False", ",", "logy", "=", "...
43.233766
21.051948
def diff(self, items): """ Diff the collections with the given items :param items: The items to diff with :type items: mixed :return: A Collection instance :rtype: Collection """ return self.__class__([i for i in self.items if i not in items])
[ "def", "diff", "(", "self", ",", "items", ")", ":", "return", "self", ".", "__class__", "(", "[", "i", "for", "i", "in", "self", ".", "items", "if", "i", "not", "in", "items", "]", ")" ]
27.181818
15.727273
def visit(d, op): """Recursively call op(d) for all list subelements and dictionary 'values' that d may have.""" op(d) if isinstance(d, list): for i in d: visit(i, op) elif isinstance(d, dict): for i in itervalues(d): visit(i, op)
[ "def", "visit", "(", "d", ",", "op", ")", ":", "op", "(", "d", ")", "if", "isinstance", "(", "d", ",", "list", ")", ":", "for", "i", "in", "d", ":", "visit", "(", "i", ",", "op", ")", "elif", "isinstance", "(", "d", ",", "dict", ")", ":", ...
30.888889
15.555556
def _edit_tags(self, tag, items, locked=True, remove=False): """ Helper to edit and refresh a tags. Parameters: tag (str): tag name items (list): list of tags to add locked (bool): lock this field. remove (bool): If this is active remo...
[ "def", "_edit_tags", "(", "self", ",", "tag", ",", "items", ",", "locked", "=", "True", ",", "remove", "=", "False", ")", ":", "if", "not", "isinstance", "(", "items", ",", "list", ")", ":", "items", "=", "[", "items", "]", "value", "=", "getattr",...
39.5
14.9375
def _create_PmtInf_node(self): """ Method to create the blank payment information nodes as a dict. """ ED = dict() # ED is element dict ED['PmtInfNode'] = ET.Element("PmtInf") ED['PmtInfIdNode'] = ET.Element("PmtInfId") ED['PmtMtdNode'] = ET.Element("PmtMtd") ...
[ "def", "_create_PmtInf_node", "(", "self", ")", ":", "ED", "=", "dict", "(", ")", "# ED is element dict", "ED", "[", "'PmtInfNode'", "]", "=", "ET", ".", "Element", "(", "\"PmtInf\"", ")", "ED", "[", "'PmtInfIdNode'", "]", "=", "ET", ".", "Element", "(",...
43.222222
11.296296
def assertCategoricalLevelsNotEqual(self, levels1, levels2, msg=None): '''Fail if ``levels1`` and ``levels2`` have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or ...
[ "def", "assertCategoricalLevelsNotEqual", "(", "self", ",", "levels1", ",", "levels2", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "levels1", ",", "collections", ".", "Iterable", ")", ":", "raise", "TypeError", "(", "'First argument is n...
34.03125
23.34375
def length_hint(obj, default=0): """ Return an estimate of the number of items in obj. This is useful for presizing containers when building from an iterable. If the object supports len(), the result will be exact. Otherwise, it may over- or under-estimate by an arbitrary amount. The result will be ...
[ "def", "length_hint", "(", "obj", ",", "default", "=", "0", ")", ":", "if", "not", "isinstance", "(", "default", ",", "int", ")", ":", "msg", "=", "(", "\"'%s' object cannot be interpreted as an integer\"", "%", "type", "(", "default", ")", ".", "__name__", ...
28.540541
19.081081
def generate_contentinfo_from_folder(self, csvwriter, rel_path, filenames): """ Create a topic node row in Content.csv for the folder at `rel_path` and add content node rows for all the files in the `rel_path` folder. """ LOGGER.debug('IN process_folder ' + str(rel_path) + ' ...
[ "def", "generate_contentinfo_from_folder", "(", "self", ",", "csvwriter", ",", "rel_path", ",", "filenames", ")", ":", "LOGGER", ".", "debug", "(", "'IN process_folder '", "+", "str", "(", "rel_path", ")", "+", "' '", "+", "str", "(", "filenames", ")", "...
50.619048
23.666667
def lru_cache(maxsize=128, key_fn=None): """Decorator that adds an LRU cache of size maxsize to the decorated function. maxsize is the number of different keys cache can accomodate. key_fn is the function that builds key from args. The default key function creates a tuple out of args and kwargs. If you...
[ "def", "lru_cache", "(", "maxsize", "=", "128", ",", "key_fn", "=", "None", ")", ":", "def", "decorator", "(", "fn", ")", ":", "cache", "=", "LRUCache", "(", "maxsize", ")", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fn", ")", "arg_names"...
32.804878
21.170732
def next_doc_with_tag(self, doc_tag): """ Returns the next document with the specified tag. Empty string is no doc is found. """ while True: try: doc = next(self) if doc.tag == doc_tag: return doc except StopIte...
[ "def", "next_doc_with_tag", "(", "self", ",", "doc_tag", ")", ":", "while", "True", ":", "try", ":", "doc", "=", "next", "(", "self", ")", "if", "doc", ".", "tag", "==", "doc_tag", ":", "return", "doc", "except", "StopIteration", ":", "raise" ]
28.166667
15.333333
def find_version(*paths): '''reads a file and returns the defined __version__ value''' version_match = re.search(r"^__version__ ?= ?['\"]([^'\"]*)['\"]", read(*paths), re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version s...
[ "def", "find_version", "(", "*", "paths", ")", ":", "version_match", "=", "re", ".", "search", "(", "r\"^__version__ ?= ?['\\\"]([^'\\\"]*)['\\\"]\"", ",", "read", "(", "*", "paths", ")", ",", "re", ".", "M", ")", "if", "version_match", ":", "return", "versi...
46
16.571429
def overlap_cplx(vec1, vec2, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, normalized=True): """Return the complex overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a wavefor...
[ "def", "overlap_cplx", "(", "vec1", ",", "vec2", ",", "psd", "=", "None", ",", "low_frequency_cutoff", "=", "None", ",", "high_frequency_cutoff", "=", "None", ",", "normalized", "=", "True", ")", ":", "htilde", "=", "make_frequency_series", "(", "vec1", ")",...
36.659091
20.636364
def create_return_url(base, query, **kwargs): """ Add a query string plus extra parameters to a base URL which may contain a query part already. :param base: redirect_uri may contain a query part, no fragment allowed. :param query: Old query part as a string :param kwargs: extra query parameter...
[ "def", "create_return_url", "(", "base", ",", "query", ",", "*", "*", "kwargs", ")", ":", "part", "=", "urlsplit", "(", "base", ")", "if", "part", ".", "fragment", ":", "raise", "ValueError", "(", "\"Base URL contained parts it shouldn't\"", ")", "for", "key...
30.5
17.973684
def deal(self, num=1, rebuild=False, shuffle=False, end=TOP): """ Returns a list of cards, which are removed from the deck. :arg int num: The number of cards to deal. :arg bool rebuild: Whether or not to rebuild the deck when cards run out. :arg bool shuf...
[ "def", "deal", "(", "self", ",", "num", "=", "1", ",", "rebuild", "=", "False", ",", "shuffle", "=", "False", ",", "end", "=", "TOP", ")", ":", "_num", "=", "num", "rebuild", "=", "rebuild", "or", "self", ".", "rebuild", "re_shuffle", "=", "shuffle...
29.489362
16.638298
def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: str """ return "{}{}_{}{:02d}".format(self.target.prefix, self, self.target.version, ...
[ "def", "tag", "(", "self", ")", ":", "return", "\"{}{}_{}{:02d}\"", ".", "format", "(", "self", ".", "target", ".", "prefix", ",", "self", ",", "self", ".", "target", ".", "version", ",", "self", ".", "target", ".", "ccd", ")" ]
39.555556
16.222222
def search(self, read_cache=True, **kwparams): """ Returns records corresponding to the given search query. See docstring of invenio.legacy.search_engine.perform_request_search() for an overview of available parameters. @raise InvenioConnectorAuthError: if authentication fails ...
[ "def", "search", "(", "self", ",", "read_cache", "=", "True", ",", "*", "*", "kwparams", ")", ":", "parse_results", "=", "False", "of", "=", "kwparams", ".", "get", "(", "'of'", ",", "\"\"", ")", "if", "of", "==", "\"\"", ":", "parse_results", "=", ...
43.173333
20.106667
def channels_rename(self, room_id, name, **kwargs): """Changes the name of the channel.""" return self.__call_api_post('channels.rename', roomId=room_id, name=name, kwargs=kwargs)
[ "def", "channels_rename", "(", "self", ",", "room_id", ",", "name", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'channels.rename'", ",", "roomId", "=", "room_id", ",", "name", "=", "name", ",", "kwargs", "=", "kwarg...
64.333333
22.333333
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
[ "def", "stream_replicate", "(", ")", ":", "stream", "=", "primary", ".", "stream", "(", "SomeDataBlob", ",", "\"trim_horizon\"", ")", "next_heartbeat", "=", "pendulum", ".", "now", "(", ")", "while", "True", ":", "now", "=", "pendulum", ".", "now", "(", ...
32.058824
12.823529
def _parse_args(func, variables, annotations=None): """Return a list of arguments with the variable it reads. NOTE: Multiple arguments may read the same variable. """ arg_read_var = [] for arg_name, anno in (annotations or func.__annotations__).items(): if arg_name == 'return': ...
[ "def", "_parse_args", "(", "func", ",", "variables", ",", "annotations", "=", "None", ")", ":", "arg_read_var", "=", "[", "]", "for", "arg_name", ",", "anno", "in", "(", "annotations", "or", "func", ".", "__annotations__", ")", ".", "items", "(", ")", ...
37.923077
15