text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def iter_node(node, name='', unknown=None, # Runtime optimization list=list, getattr=getattr, isinstance=isinstance, enumerate=enumerate, missing=NonExistent): """Iterates over an object: - If the object has a _fields attribute, it gets attributes in the or...
[ "def", "iter_node", "(", "node", ",", "name", "=", "''", ",", "unknown", "=", "None", ",", "# Runtime optimization", "list", "=", "list", ",", "getattr", "=", "getattr", ",", "isinstance", "=", "isinstance", ",", "enumerate", "=", "enumerate", ",", "missin...
36.586207
0.000918
def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' if salt.utils.path.which('timedatectl'): ret = _timedatectl() for line in (x.strip() for x in ret['stdout'].splitlines()): ...
[ "def", "get_hwclock", "(", ")", ":", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "'timedatectl'", ")", ":", "ret", "=", "_timedatectl", "(", ")", "for", "line", "in", "(", "x", ".", "strip", "(", ")", "for", "x", "in", "ret", "[",...
40.288288
0.000218
def sort_genomic_ranges(rngs): """sort multiple ranges""" return sorted(rngs, key=lambda x: (x.chr, x.start, x.end))
[ "def", "sort_genomic_ranges", "(", "rngs", ")", ":", "return", "sorted", "(", "rngs", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "chr", ",", "x", ".", "start", ",", "x", ".", "end", ")", ")" ]
39.333333
0.025
def retrieve_loadbalancer_status(self, loadbalancer, **_params): """Retrieves status for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer), params=_params)
[ "def", "retrieve_loadbalancer_status", "(", "self", ",", "loadbalancer", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "lbaas_loadbalancer_path_status", "%", "(", "loadbalancer", ")", ",", "params", "=", "_params", ")" ]
59.75
0.008264
def scene_to_collision(scene): """ Create collision objects from a trimesh.Scene object. Parameters ------------ scene : trimesh.Scene Scene to create collision objects for Returns ------------ manager : CollisionManager CollisionManager for objects in scene objects: {n...
[ "def", "scene_to_collision", "(", "scene", ")", ":", "manager", "=", "CollisionManager", "(", ")", "objects", "=", "{", "}", "for", "node", "in", "scene", ".", "graph", ".", "nodes_geometry", ":", "T", ",", "geometry", "=", "scene", ".", "graph", "[", ...
30
0.001346
def _init_modules_stub(self, **_): """Initializes the modules stub based off of your current yaml files Implements solution from http://stackoverflow.com/questions/28166558/invalidmoduleerror-when-using-testbed-to-unit-test-google-app-engine """ from google.appengine.api import ...
[ "def", "_init_modules_stub", "(", "self", ",", "*", "*", "_", ")", ":", "from", "google", ".", "appengine", ".", "api", "import", "request_info", "# edit all_versions per modules & versions thereof needing tests", "all_versions", "=", "{", "}", "# {'default': [1], 'ands...
53.291667
0.002304
def rel2abs_x(x, axis=None): r''' Transform relative x-coordinates to absolute x-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **x** (``float``, ``list``) Relative coordinates. :options: **axis...
[ "def", "rel2abs_x", "(", "x", ",", "axis", "=", "None", ")", ":", "# get current axis", "if", "axis", "is", "None", ":", "axis", "=", "plt", ".", "gca", "(", ")", "# get current limits", "xmin", ",", "xmax", "=", "axis", ".", "get_xlim", "(", ")", "#...
25.540541
0.026504
def mean_abs(self): """return the median of absolute values""" # XXX rename this method if len(self.values) > 0: return sorted(map(abs, self.values))[len(self.values) / 2] else: return None
[ "def", "mean_abs", "(", "self", ")", ":", "# XXX rename this method", "if", "len", "(", "self", ".", "values", ")", ">", "0", ":", "return", "sorted", "(", "map", "(", "abs", ",", "self", ".", "values", ")", ")", "[", "len", "(", "self", ".", "valu...
34.142857
0.008163
def returns_section(thing, doc, header_level): """ Generate markdown for Returns section. Parameters ---------- thing : function Function to produce returns for doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns -------...
[ "def", "returns_section", "(", "thing", ",", "doc", ",", "header_level", ")", ":", "lines", "=", "[", "]", "return_type", "=", "None", "try", ":", "return_type", "=", "thing", ".", "__annotations__", "[", "\"return\"", "]", "except", "AttributeError", ":", ...
30.84
0.000838
def chao_shen(q): """ Computes some terms needed for the Chao-Shen KL correction. """ yx = q[q > 0] # remove bins with zero counts n = np.sum(yx) p = yx.astype(float)/n f1 = np.sum(yx == 1) # number of singletons in the sample if f1 == n: # avoid C == 0 f1 -= 1 C = 1 - (f1/n)...
[ "def", "chao_shen", "(", "q", ")", ":", "yx", "=", "q", "[", "q", ">", "0", "]", "# remove bins with zero counts", "n", "=", "np", ".", "sum", "(", "yx", ")", "p", "=", "yx", ".", "astype", "(", "float", ")", "/", "n", "f1", "=", "np", ".", "...
36.266667
0.010753
def keep(self, diff): """ Mark this diff (or volume) to be kept in path. """ (toUUID, fromUUID) = self.toArg.diff(diff) self._client.keep(toUUID, fromUUID) logger.debug("Kept %s", diff)
[ "def", "keep", "(", "self", ",", "diff", ")", ":", "(", "toUUID", ",", "fromUUID", ")", "=", "self", ".", "toArg", ".", "diff", "(", "diff", ")", "self", ".", "_client", ".", "keep", "(", "toUUID", ",", "fromUUID", ")", "logger", ".", "debug", "(...
42.6
0.009217
def ufloatDict_nominal(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values())))
[ "def", "ufloatDict_nominal", "(", "self", ",", "ufloat_dict", ")", ":", "return", "OrderedDict", "(", "izip", "(", "ufloat_dict", ".", "keys", "(", ")", ",", "map", "(", "lambda", "x", ":", "x", ".", "nominal_value", ",", "ufloat_dict", ".", "values", "(...
79
0.016736
def _links(self): """Calculate total energy production. Not Rounded""" total = 0.0 for value in self.link.values(): total += value return total
[ "def", "_links", "(", "self", ")", ":", "total", "=", "0.0", "for", "value", "in", "self", ".", "link", ".", "values", "(", ")", ":", "total", "+=", "value", "return", "total" ]
30.333333
0.010695
def generate_signature(secret, verb, url, nonce, data): """Generate a request signature compatible with BitMEX.""" # Parse the url so we can remove the base and extract just the path. parsedURL = urllib.parse.urlparse(url) path = parsedURL.path if parsedURL.query: path = path + '?' + parsedU...
[ "def", "generate_signature", "(", "secret", ",", "verb", ",", "url", ",", "nonce", ",", "data", ")", ":", "# Parse the url so we can remove the base and extract just the path.", "parsedURL", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "path", "=...
40.8
0.001597
def _compare_lists(list1, list2, custom_cmp): """Compare twolists using given comparing function. :param list1: first list to compare :param list2: second list to compare :param custom_cmp: a function taking two arguments (element of list 1, element of list 2) and :return: True or False dep...
[ "def", "_compare_lists", "(", "list1", ",", "list2", ",", "custom_cmp", ")", ":", "if", "len", "(", "list1", ")", "!=", "len", "(", "list2", ")", ":", "return", "False", "for", "element1", ",", "element2", "in", "zip", "(", "list1", ",", "list2", ")"...
35.866667
0.001812
def find_view_menu(self, name): """ Finds and returns a ViewMenu by name """ return self.get_session.query(self.viewmenu_model).filter_by(name=name).first()
[ "def", "find_view_menu", "(", "self", ",", "name", ")", ":", "return", "self", ".", "get_session", ".", "query", "(", "self", ".", "viewmenu_model", ")", ".", "filter_by", "(", "name", "=", "name", ")", ".", "first", "(", ")" ]
37.6
0.015625
def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ): """ Encrypt a stream of data for a set of keys. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on ...
[ "def", "gpg_encrypt", "(", "fd_in", ",", "path_out", ",", "sender_key_info", ",", "recipient_key_infos", ",", "passphrase", "=", "None", ",", "config_dir", "=", "None", ")", ":", "if", "config_dir", "is", "None", ":", "config_dir", "=", "get_config_dir", "(", ...
36.607843
0.011476
def _aggregate_config_values(config_values: typing.List[ConfigValue]) -> dict: """ Returns a (sorted) :param config_values: :type config_values: :return: :rtype: """ _keys: defaultdict = _nested_default_dict() _sorted_values = sorted(config_values, key=lambda x: x.name) for valu...
[ "def", "_aggregate_config_values", "(", "config_values", ":", "typing", ".", "List", "[", "ConfigValue", "]", ")", "->", "dict", ":", "_keys", ":", "defaultdict", "=", "_nested_default_dict", "(", ")", "_sorted_values", "=", "sorted", "(", "config_values", ",", ...
33.5
0.001613
def create_constraints(self, courses): """Internal use. Creates all constraints in the problem instance for the given courses. """ for i, course1 in enumerate(courses): for j, course2 in enumerate(courses): if i <= j: continue ...
[ "def", "create_constraints", "(", "self", ",", "courses", ")", ":", "for", "i", ",", "course1", "in", "enumerate", "(", "courses", ")", ":", "for", "j", ",", "course2", "in", "enumerate", "(", "courses", ")", ":", "if", "i", "<=", "j", ":", "continue...
44.5
0.008811
def c(self): """Caching client for not repeapting checks""" if self._client is None: self._parse_settings() self._client = Rumetr(**self.settings) return self._client
[ "def", "c", "(", "self", ")", ":", "if", "self", ".", "_client", "is", "None", ":", "self", ".", "_parse_settings", "(", ")", "self", ".", "_client", "=", "Rumetr", "(", "*", "*", "self", ".", "settings", ")", "return", "self", ".", "_client" ]
34.833333
0.009346
def has_saved(self, addr): """Test if device has data from the saved data file.""" saved = False if self._saved_devices.get(addr, None) is not None: saved = True return saved
[ "def", "has_saved", "(", "self", ",", "addr", ")", ":", "saved", "=", "False", "if", "self", ".", "_saved_devices", ".", "get", "(", "addr", ",", "None", ")", "is", "not", "None", ":", "saved", "=", "True", "return", "saved" ]
35.5
0.009174
def pause(self): """Pauses playback""" if self.isPlaying is True: self._execute("pause") self._changePlayingState(False)
[ "def", "pause", "(", "self", ")", ":", "if", "self", ".", "isPlaying", "is", "True", ":", "self", ".", "_execute", "(", "\"pause\"", ")", "self", ".", "_changePlayingState", "(", "False", ")" ]
31.2
0.0125
def update(self, **kwargs): """Updates an instance. Args: **kwargs : Arbitrary keyword arguments. Column names are keywords and their new values are the values. Examples: >>> customer.update(email="newemail@x.com", name="new") """ kwa...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_preprocess_params", "(", "kwargs", ")", "kwargs", "=", "self", ".", "preprocess_kwargs_before_update", "(", "kwargs", ")", "for", "key", ",", "value", "in", "k...
36.818182
0.002406
def _new_from_cdata(cls, cdata: Any) -> "Random": """Return a new instance encapsulating this cdata.""" self = object.__new__(cls) # type: "Random" self.random_c = cdata return self
[ "def", "_new_from_cdata", "(", "cls", ",", "cdata", ":", "Any", ")", "->", "\"Random\"", ":", "self", "=", "object", ".", "__new__", "(", "cls", ")", "# type: \"Random\"", "self", ".", "random_c", "=", "cdata", "return", "self" ]
42
0.009346
def add(self, attendees): """ Add attendees to the parent event :param attendees: list of attendees to add :type attendees: str or tuple(str, str) or Attendee or list[str] or list[tuple(str,str)] or list[Attendee] """ if attendees: if isinstance(attendees, s...
[ "def", "add", "(", "self", ",", "attendees", ")", ":", "if", "attendees", ":", "if", "isinstance", "(", "attendees", ",", "str", ")", ":", "self", ".", "__attendees", ".", "append", "(", "Attendee", "(", "address", "=", "attendees", ",", "event", "=", ...
50.061224
0.001999
def classify_wherex(scope_, fromx, wherex): "helper for wherex_to_rowlist. returns [SingleTableCond,...], [CartesianCond,...]" exprs = [] for exp in fromx: if isinstance(exp, sqparse2.JoinX): # todo: probably just add exp.on_stmt as a CartesianCond. don't write this until tests are ready. # todo: ...
[ "def", "classify_wherex", "(", "scope_", ",", "fromx", ",", "wherex", ")", ":", "exprs", "=", "[", "]", "for", "exp", "in", "fromx", ":", "if", "isinstance", "(", "exp", ",", "sqparse2", ".", "JoinX", ")", ":", "# todo: probably just add exp.on_stmt as a Car...
44.392857
0.022047
def _responsive_sleep(self, seconds, wait_log_interval=0, wait_reason=''): """When there is litte work to do, the queuing thread sleeps a lot. It can't sleep for too long without checking for the quit flag and/or logging about why it is sleeping. parameters: seconds - the nu...
[ "def", "_responsive_sleep", "(", "self", ",", "seconds", ",", "wait_log_interval", "=", "0", ",", "wait_reason", "=", "''", ")", ":", "for", "x", "in", "xrange", "(", "int", "(", "seconds", ")", ")", ":", "self", ".", "quit_check", "(", ")", "if", "w...
49.185185
0.001477
def export_to_dict(session, recursive, back_references, include_defaults): """Exports databases and druid clusters to a dictionary""" logging.info('Starting export') dbs = session.query(Database) databases = [database.export_to_dict(recursive=recu...
[ "def", "export_to_dict", "(", "session", ",", "recursive", ",", "back_references", ",", "include_defaults", ")", ":", "logging", ".", "info", "(", "'Starting export'", ")", "dbs", "=", "session", ".", "query", "(", "Database", ")", "databases", "=", "[", "da...
42.772727
0.00104
def flux_variability(model, reactions, fixed, tfba, solver): """Find the variability of each reaction while fixing certain fluxes. Yields the reaction id, and a tuple of minimum and maximum value for each of the given reactions. The fixed reactions are given in a dictionary as a reaction id to value ma...
[ "def", "flux_variability", "(", "model", ",", "reactions", ",", "fixed", ",", "tfba", ",", "solver", ")", ":", "fba", "=", "_get_fba_problem", "(", "model", ",", "tfba", ",", "solver", ")", "for", "reaction_id", ",", "value", "in", "iteritems", "(", "fix...
36.114286
0.00077
def decode(data): """ Handles decoding of the XML `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data. """ dom = None try: dom = dhtmlparser.parseString(data) except Exception, e: raise MetaParsingException("...
[ "def", "decode", "(", "data", ")", ":", "dom", "=", "None", "try", ":", "dom", "=", "dhtmlparser", ".", "parseString", "(", "data", ")", "except", "Exception", ",", "e", ":", "raise", "MetaParsingException", "(", "\"Can't parse your XML data: %s\"", "%", "e"...
24.702128
0.000829
def download(self, temp_ver, store_metadata=True): """ Retrieve the given template version Args: temp_ver (TemplateVersion): template version to retrieve store_metadata (bool): If set to ``False``, will not refresh the local metadata with the retrieved on...
[ "def", "download", "(", "self", ",", "temp_ver", ",", "store_metadata", "=", "True", ")", ":", "dest", "=", "self", ".", "_prefixed", "(", "temp_ver", ".", "name", ")", "temp_dest", "=", "'%s.tmp'", "%", "dest", "with", "utils", ".", "LockFile", "(", "...
31.423077
0.001187
def init(): ''' Initializes git repo for nbinteract. 1. Checks for requirements.txt or Dockerfile, offering to create a requirements.txt if needed. 2. Sets the Binder spec using the `origin` git remote in .nbinteract.json. 3. Prints a Binder URL so the user can debug their image if needed. ...
[ "def", "init", "(", ")", ":", "log", "(", "'Initializing folder for nbinteract.'", ")", "log", "(", ")", "log", "(", "'Checking to see if this folder is the root folder of a git project.'", ")", "if", "os", ".", "path", ".", "isdir", "(", "'.git'", ")", ":", "log"...
34.952381
0.000265
def next_frame_savp_vae(): """SAVP - VAE only model.""" hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
[ "def", "next_frame_savp_vae", "(", ")", ":", "hparams", "=", "next_frame_savp", "(", ")", "hparams", ".", "use_vae", "=", "True", "hparams", ".", "use_gan", "=", "False", "hparams", ".", "latent_loss_multiplier", "=", "1e-3", "hparams", ".", "latent_loss_multipl...
31
0.031373
def _get_bounds(self, layers): """Return the bounds of all data layers involved in a cartoframes map. Args: layers (list): List of cartoframes layers. See `cartoframes.layers` for all types. Returns: dict: Dictionary of northern, southern, eastern, and w...
[ "def", "_get_bounds", "(", "self", ",", "layers", ")", ":", "extent_query", "=", "(", "'SELECT ST_EXTENT(the_geom) AS the_geom '", "'FROM ({query}) AS t{idx}\\n'", ")", "union_query", "=", "'UNION ALL\\n'", ".", "join", "(", "[", "extent_query", ".", "format", "(", ...
38.647059
0.001485
def linterp(self, setx, sety, x): """ Linear interp of model data values between time steps """ if math.isnan(sety[0]) or math.isnan(setx[0]): return np.nan #if math.isnan(sety[0]): # sety[0] = 0. #if math.isnan(sety[1]): # sety[1] = ...
[ "def", "linterp", "(", "self", ",", "setx", ",", "sety", ",", "x", ")", ":", "if", "math", ".", "isnan", "(", "sety", "[", "0", "]", ")", "or", "math", ".", "isnan", "(", "setx", "[", "0", "]", ")", ":", "return", "np", ".", "nan", "#if math....
35.909091
0.017284
def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.fo...
[ "def", "_log_board_terrain", "(", "self", ",", "terrain", ")", ":", "self", ".", "_logln", "(", "'terrain: {0}'", ".", "format", "(", "' '", ".", "join", "(", "t", ".", "value", "for", "t", "in", "terrain", ")", ")", ")" ]
44.25
0.00831
def main( gpu:Param("GPU to run on", str)=None, woof: Param("Use imagewoof (otherwise imagenette)", int)=0, lr: Param("Learning rate", float)=1e-3, size: Param("Size (px: 128,192,224)", int)=128, alpha: Param("Alpha", float)=0.99, mom: Param("Momentum", float)=0.9, ...
[ "def", "main", "(", "gpu", ":", "Param", "(", "\"GPU to run on\"", ",", "str", ")", "=", "None", ",", "woof", ":", "Param", "(", "\"Use imagewoof (otherwise imagenette)\"", ",", "int", ")", "=", "0", ",", "lr", ":", "Param", "(", "\"Learning rate\"", ",", ...
43.571429
0.030465
def proc_modscag(fn_list, extent=None, t_srs=None): """Process the MODSCAG products for full date range, create composites and reproject """ #Use cubic spline here for improve upsampling ds_list = warplib.memwarp_multi_fn(fn_list, res='min', extent=extent, t_srs=t_srs, r='cubicspline') stack_fn = o...
[ "def", "proc_modscag", "(", "fn_list", ",", "extent", "=", "None", ",", "t_srs", "=", "None", ")", ":", "#Use cubic spline here for improve upsampling ", "ds_list", "=", "warplib", ".", "memwarp_multi_fn", "(", "fn_list", ",", "res", "=", "'min'", ",", "extent",...
48.433333
0.008097
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_d...
[ "def", "gather_command_line_options", "(", "filter_disabled", "=", "None", ")", ":", "if", "filter_disabled", "is", "None", ":", "filter_disabled", "=", "not", "SETTINGS", ".", "COMMAND_LINE", ".", "SHOW_DISABLED_OPTIONS", "options", "=", "[", "opt", "for", "opt",...
56.428571
0.002494
def element_from_neighbourhood(X): """ Randomly move an event: - Either to an empty slot - Swapping with another event """ m, n = X.shape new_X = np.copy(X) event_to_move = np.random.randint(m) current_event_slot = np.where(new_X[event_to_move, :] == 1)[0][0] slot_to_move_to ...
[ "def", "element_from_neighbourhood", "(", "X", ")", ":", "m", ",", "n", "=", "X", ".", "shape", "new_X", "=", "np", ".", "copy", "(", "X", ")", "event_to_move", "=", "np", ".", "random", ".", "randint", "(", "m", ")", "current_event_slot", "=", "np",...
28.857143
0.002395
def genes_with_homology_models(self): """DictList: All genes that have at least one homology model.""" return DictList(x for x in self.genes_with_structures if x.protein.num_structures_homology > 0)
[ "def", "genes_with_homology_models", "(", "self", ")", ":", "return", "DictList", "(", "x", "for", "x", "in", "self", ".", "genes_with_structures", "if", "x", ".", "protein", ".", "num_structures_homology", ">", "0", ")" ]
70.666667
0.014019
def covar(self): """ The covariance matrix for the result :math:`\\beta` """ if self._covar is None: self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X)) return self._covar
[ "def", "covar", "(", "self", ")", ":", "if", "self", ".", "_covar", "is", "None", ":", "self", ".", "_covar", "=", "_np", ".", "linalg", ".", "inv", "(", "_np", ".", "dot", "(", "_np", ".", "transpose", "(", "self", ".", "X", ")", ",", "self", ...
33.428571
0.0125
def download_pip_based_installations(env, pip_invocation, requirements, download_cache_folder): """Download requirements for pip based installation.""" if config.installation_cache_folder() is None: raise EnvironmentSetupError("Local installation cache folder not " "defined but ...
[ "def", "download_pip_based_installations", "(", "env", ",", "pip_invocation", ",", "requirements", ",", "download_cache_folder", ")", ":", "if", "config", ".", "installation_cache_folder", "(", ")", "is", "None", ":", "raise", "EnvironmentSetupError", "(", "\"Local in...
61
0.001467
def get_language(): """ Return an active language code that is guaranteed to be in settings.LANGUAGES (Django does not seem to guarantee this for us). """ lang = _get_language() if lang is None: # Django >= 1.8 return settings.DEFAULT_LANGUAGE if lang not in settings.AVAILABLE_LANGU...
[ "def", "get_language", "(", ")", ":", "lang", "=", "_get_language", "(", ")", "if", "lang", "is", "None", ":", "# Django >= 1.8", "return", "settings", ".", "DEFAULT_LANGUAGE", "if", "lang", "not", "in", "settings", ".", "AVAILABLE_LANGUAGES", "and", "'-'", ...
35.769231
0.002096
def get_lo_hi_from_CI(s, exclude=None): """ Parse the confidence interval from CI. >>> get_lo_hi_from_CI("20-20/40-60") (40, 60) """ a, b = s.split("|") ai, aj = a.split("-") bi, bj = b.split("-") los = [int(ai), int(bi)] his = [int(aj), int(bj)] if exclude and exclude in l...
[ "def", "get_lo_hi_from_CI", "(", "s", ",", "exclude", "=", "None", ")", ":", "a", ",", "b", "=", "s", ".", "split", "(", "\"|\"", ")", "ai", ",", "aj", "=", "a", ".", "split", "(", "\"-\"", ")", "bi", ",", "bj", "=", "b", ".", "split", "(", ...
23.722222
0.002252
def freeze(environ, names, label=None): """Flag the given names to reset to their current value in the next Python. :param dict environ: The environment that will be passed to the next Python. :param names: A list of variable names that should be reset to their current value (as in ``environ``)...
[ "def", "freeze", "(", "environ", ",", "names", ",", "label", "=", "None", ")", ":", "diff", "=", "_get_diff", "(", "environ", ",", "label", ")", "for", "name", "in", "names", ":", "diff", "[", "name", "]", "=", "environ", ".", "get", "(", "name", ...
35.722222
0.009084
def sample(self, n_samples=1, random_state=None): """Generate random samples from the model. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array_like, shape (n_samples, n_features) ...
[ "def", "sample", "(", "self", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "if", "random_state", "is", "None", ":", "random_state", "=", "self", ".", "random_state", "random_s...
36.878049
0.001289
def checkType(self, item_type, projectarea_id): """Check the validity of :class:`rtcclient.workitem.Workitem` type :param item_type: the type of the workitem (e.g. Story/Defect/Epic) :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea` id :retur...
[ "def", "checkType", "(", "self", ",", "item_type", ",", "projectarea_id", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Checking the validity of workitem type: %s\"", ",", "item_type", ")", "try", ":", "project_area", "=", "self", ".", "getProjectAreaByID", ...
36.363636
0.002436
def _parse_orders(self, orders): """ Transform orders from list objects to PHP arrays: [ { 'PNAME': 'CD Player', 'PCODE': 'PROD_04891', 'PINFO': 'Extended Warranty - 5 Years', 'PRICE': '82.3', ...
[ "def", "_parse_orders", "(", "self", ",", "orders", ")", ":", "result", "=", "{", "}", "for", "index", ",", "order", "in", "enumerate", "(", "orders", ")", ":", "for", "detail", ",", "value", "in", "order", ".", "iteritems", "(", ")", ":", "result", ...
33.191176
0.001291
async def hincrbyfloat(self, name, key, amount=1.0): """ Increment the value of ``key`` in hash ``name`` by floating ``amount`` """ return await self.execute_command('HINCRBYFLOAT', name, key, amount)
[ "async", "def", "hincrbyfloat", "(", "self", ",", "name", ",", "key", ",", "amount", "=", "1.0", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'HINCRBYFLOAT'", ",", "name", ",", "key", ",", "amount", ")" ]
45.6
0.008621
def refresh_lock(lock_file): """'Refresh' an existing lock. 'Refresh' an existing lock by re-writing the file containing the owner's unique id, using a new (randomly generated) id, which is also returned. """ unique_id = '%s_%s_%s' % ( os.getpid(), ''.join([str(random.randint(0...
[ "def", "refresh_lock", "(", "lock_file", ")", ":", "unique_id", "=", "'%s_%s_%s'", "%", "(", "os", ".", "getpid", "(", ")", ",", "''", ".", "join", "(", "[", "str", "(", "random", ".", "randint", "(", "0", ",", "9", ")", ")", "for", "i", "in", ...
33.541667
0.001208
def props_value(props): """ Properties value. :param dict props: Properties dictionary. :rtype: str :return: Properties as string. """ sep = "" result_value = "" for prop_key, prop_value in props.items(): result_value = "{}{}{}={}".format( result_value, sep, prop_key, prop_value ...
[ "def", "props_value", "(", "props", ")", ":", "sep", "=", "\"\"", "result_value", "=", "\"\"", "for", "prop_key", ",", "prop_value", "in", "props", ".", "items", "(", ")", ":", "result_value", "=", "\"{}{}{}={}\"", ".", "format", "(", "result_value", ",", ...
13.875
0.078652
def intersecting_ranges(ranges): """Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``rang...
[ "def", "intersecting_ranges", "(", "ranges", ")", ":", "ranges", "=", "sorted", "(", "ranges", ",", "key", "=", "op", ".", "attrgetter", "(", "'start'", ")", ")", "return", "sorted_diff", "(", "ranges", ",", "group_ranges", "(", "ranges", ")", ")" ]
27
0.001233
def get_context(context): """An internal context generator. Accepts a CKAN context. CKAN's internals put various things into the context which makes reusing it for multiple API calls inadvisable. This function adds more fine grain control on the context from our plugin logic side. """ new_c...
[ "def", "get_context", "(", "context", ")", ":", "new_context", "=", "{", "'model'", ":", "context", "[", "'model'", "]", ",", "'session'", ":", "context", "[", "'session'", "]", ",", "'user'", ":", "context", ".", "get", "(", "'user'", ")", ",", "'igno...
32.45
0.001497
def ip_anycast_gateway(self, **kwargs): """ Add anycast gateway under interface ve. Args: int_type: L3 interface type on which the anycast ip needs to be configured. name:L3 interface name on which the anycast ip needs to be configured. ...
[ "def", "ip_anycast_gateway", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "anycast_ip", "=", "kwargs", "....
47.336207
0.000535
def load(self, data): """ Load an image that was previously saved using :py:meth:`~docker.models.images.Image.save` (or ``docker save``). Similar to ``docker load``. Args: data (binary): Image data to be loaded. Returns: (list of :py:class:`Image...
[ "def", "load", "(", "self", ",", "data", ")", ":", "resp", "=", "self", ".", "client", ".", "api", ".", "load_image", "(", "data", ")", "images", "=", "[", "]", "for", "chunk", "in", "resp", ":", "if", "'stream'", "in", "chunk", ":", "match", "="...
31
0.002018
def use(self, *middleware: Middleware): """ Registers middleware plugin(s) with the bot or set. :param middleware : :return: """ for (idx, m) in enumerate(middleware): if hasattr(m, 'on_process_request') and callable(m.on_process_request): self...
[ "def", "use", "(", "self", ",", "*", "middleware", ":", "Middleware", ")", ":", "for", "(", "idx", ",", "m", ")", "in", "enumerate", "(", "middleware", ")", ":", "if", "hasattr", "(", "m", ",", "'on_process_request'", ")", "and", "callable", "(", "m"...
40.416667
0.008065
def draw_net_using_node_coords(net): """ Plot a networkx.Graph by using the lat and lon attributes of nodes. Parameters ---------- net : networkx.Graph Returns ------- fig : matplotlib.figure the figure object where the network is plotted """ import matplotlib.pyplot as p...
[ "def", "draw_net_using_node_coords", "(", "net", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "fig", "=", "plt", ".", "figure", "(", ")", "node_coords", "=", "{", "}", "for", "node", ",", "data", "in", "net", ".", "nodes", "(", "data",...
29.105263
0.001751
def application(self, func): """Parse the function application subgrammar. Function application can, conceptually, be thought of as a mixfix operator, similar to the way array subscripting works. However, it is not clear at this point whether we want to allow it to work as such, ...
[ "def", "application", "(", "self", ",", "func", ")", ":", "start", "=", "self", ".", "tokens", ".", "matched", ".", "start", "if", "self", ".", "tokens", ".", "accept", "(", "common_grammar", ".", "rparen", ")", ":", "# That was easy.", "return", "ast", ...
48.466667
0.001349
def get_flags(self, i, version0, scoped=False): """Get flags.""" index = i.index value = ['('] version = False toggle = False end = ':' if scoped else ')' try: c = next(i) if c != '?': i.rewind(1) return Non...
[ "def", "get_flags", "(", "self", ",", "i", ",", "version0", ",", "scoped", "=", "False", ")", ":", "index", "=", "i", ".", "index", "value", "=", "[", "'('", "]", "version", "=", "False", "toggle", "=", "False", "end", "=", "':'", "if", "scoped", ...
31.526316
0.001619
def register(name, func=None): """ Function or decorator which registers a given function as a recognized control command. """ def decorator(func): # Perform the registration ControlDaemon._register(name, func) return func # If func was given, call the decorator, otherw...
[ "def", "register", "(", "name", ",", "func", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "# Perform the registration", "ControlDaemon", ".", "_register", "(", "name", ",", "func", ")", "return", "func", "# If func was given, call the decora...
24.352941
0.002326
def url(self, var, default=NOTSET, force=True): """Get environment variable, parsed with urlparse/urllib.parse""" return self._get(var, default=default, cast=urlparse.urlparse, force=force)
[ "def", "url", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ",", "force", "=", "True", ")", ":", "return", "self", ".", "_get", "(", "var", ",", "default", "=", "default", ",", "cast", "=", "urlparse", ".", "urlparse", ",", "force", "=", ...
56.75
0.008696
def update(self, callback=int): """Process all pending model modifications.""" # print(self._pending_modifications) add_var = self._pending_modifications.add_var if len(add_var) > 0: self._add_variables(add_var) self._pending_modifications.add_var = [] cal...
[ "def", "update", "(", "self", ",", "callback", "=", "int", ")", ":", "# print(self._pending_modifications)", "add_var", "=", "self", ".", "_pending_modifications", ".", "add_var", "if", "len", "(", "add_var", ")", ">", "0", ":", "self", ".", "_add_variables", ...
39.972222
0.001357
def plot_plane(where="back", texture=None): """Plot a plane at a particular location in the viewbox. :param str where: 'back', 'front', 'left', 'right', 'top', 'bottom' :param texture: {texture} :return: :any:`Mesh` """ fig = gcf() xmin, xmax = fig.xlim ymin, ymax = fig.ylim zmin, z...
[ "def", "plot_plane", "(", "where", "=", "\"back\"", ",", "texture", "=", "None", ")", ":", "fig", "=", "gcf", "(", ")", "xmin", ",", "xmax", "=", "fig", ".", "xlim", "ymin", ",", "ymax", "=", "fig", ".", "ylim", "zmin", ",", "zmax", "=", "fig", ...
32.261905
0.000716
async def get(self, public_key): """Retrieves all users input and output offers Accepts: - public key """ # Sign-verifying functional #super().verify() # Get coinid account = await self.account.getaccountdata(public_key=public_key) if "error" in account.keys(): self.set_status(account["error"]) ...
[ "async", "def", "get", "(", "self", ",", "public_key", ")", ":", "# Sign-verifying functional", "#super().verify()", "# Get coinid", "account", "=", "await", "self", ".", "account", ".", "getaccountdata", "(", "public_key", "=", "public_key", ")", "if", "\"error\"...
23.8
0.041372
def send_request(self, msgid, method, args, kwargs): """Send a request.""" msg = dumps([0, msgid, method, args, kwargs]) self.send(msg)
[ "def", "send_request", "(", "self", ",", "msgid", ",", "method", ",", "args", ",", "kwargs", ")", ":", "msg", "=", "dumps", "(", "[", "0", ",", "msgid", ",", "method", ",", "args", ",", "kwargs", "]", ")", "self", ".", "send", "(", "msg", ")" ]
39
0.012579
def makeadistu_inlets(data, commdct): """make the dict adistu_inlets""" adistus = getadistus(data, commdct) # assume that the inlet node has the words "Air Inlet Node Name" airinletnode = "Air Inlet Node Name" adistu_inlets = {} for adistu in adistus: objkey = adistu.upper() obji...
[ "def", "makeadistu_inlets", "(", "data", ",", "commdct", ")", ":", "adistus", "=", "getadistus", "(", "data", ",", "commdct", ")", "# assume that the inlet node has the words \"Air Inlet Node Name\"", "airinletnode", "=", "\"Air Inlet Node Name\"", "adistu_inlets", "=", "...
36.421053
0.001408
def AsDict(self, dt=True): """ A dict representation of this Shake instance. The return value uses the same key names as the JSON representation. Args: dt (bool): If True, return dates as python datetime objects. If False, return dates as ISO strings. ...
[ "def", "AsDict", "(", "self", ",", "dt", "=", "True", ")", ":", "data", "=", "{", "}", "if", "self", ".", "sharekey", ":", "data", "[", "'sharekey'", "]", "=", "self", ".", "sharekey", "if", "self", ".", "name", ":", "data", "[", "'name'", "]", ...
30.510204
0.001296
async def stop_poll(self, chat_id: typing.Union[base.String, base.Integer], message_id: base.Integer, reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Poll: """ Use this method to stop a poll which was sent by the bot. ...
[ "async", "def", "stop_poll", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "String", ",", "base", ".", "Integer", "]", ",", "message_id", ":", "base", ".", "Integer", ",", "reply_markup", ":", "typing", ".", "Union", "[", ...
55.25
0.008007
def add_consumer(self, consumer): """Add another consumer from a :class:`Consumer` instance.""" consumer.backend = self.backend self.consumers.append(consumer)
[ "def", "add_consumer", "(", "self", ",", "consumer", ")", ":", "consumer", ".", "backend", "=", "self", ".", "backend", "self", ".", "consumers", ".", "append", "(", "consumer", ")" ]
45
0.010929
def store_references(self, references): """Stores references to disk and may collect garbage.""" for trajectory_name in references: self._storage_service.store(pypetconstants.LIST, references[trajectory_name], trajectory_name=trajectory_name) self._check_and_collect_garbage()
[ "def", "store_references", "(", "self", ",", "references", ")", ":", "for", "trajectory_name", "in", "references", ":", "self", ".", "_storage_service", ".", "store", "(", "pypetconstants", ".", "LIST", ",", "references", "[", "trajectory_name", "]", ",", "tra...
61.6
0.009615
def urls_from_file_tree(template_dir): """Generates a list of URL strings that would match each staticflatpage.""" urls = [] # keep a list of of all the files/paths # Should be somethign like: # /path/to/myproject/templates/staticflatpages root_dir = join(template_dir, 'staticflatpages') for ...
[ "def", "urls_from_file_tree", "(", "template_dir", ")", ":", "urls", "=", "[", "]", "# keep a list of of all the files/paths", "# Should be somethign like:", "# /path/to/myproject/templates/staticflatpages", "root_dir", "=", "join", "(", "template_dir", ",", "'staticflatpages'"...
39.235294
0.001464
def parse_runtime_limit(value, now=None): """Parsing CLI option for runtime limit, supplied as VALUE. Value could be something like: Sunday 23:00-05:00, the format being [Wee[kday]] [hh[:mm][-hh[:mm]]]. The function will return two valid time ranges. The first could be in the past, containing the p...
[ "def", "parse_runtime_limit", "(", "value", ",", "now", "=", "None", ")", ":", "def", "extract_time", "(", "value", ")", ":", "value", "=", "_RE_RUNTIMELIMIT_HOUR", ".", "search", "(", "value", ")", ".", "groupdict", "(", ")", "return", "timedelta", "(", ...
34.336842
0.000298
def _find_spherical_axes(self): """ Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point group T molecules have only one unique 3-fold and one unique 2-fold axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules have a unique 5-fold axis. """ ...
[ "def", "_find_spherical_axes", "(", "self", ")", ":", "rot_present", "=", "defaultdict", "(", "bool", ")", "origin_site", ",", "dist_el_sites", "=", "cluster_sites", "(", "self", ".", "centered_mol", ",", "self", ".", "tol", ")", "test_set", "=", "min", "(",...
50.108108
0.001058
def add_annotations(self,annotations,**kwargs): """ Add an annotation to the QuantFigure. Parameters: annotations : dict or list(dict,) Annotations can be on the form form of {'date' : 'text'} and the text will automatically be placed at the right level on the chart or A Plotly...
[ "def", "add_annotations", "(", "self", ",", "annotations", ",", "*", "*", "kwargs", ")", ":", "ann_kwargs", "=", "utils", ".", "check_kwargs", "(", "kwargs", ",", "get_annotation_kwargs", "(", ")", ",", "{", "}", ",", "clean_origin", "=", "True", ")", "i...
28.870968
0.047568
def stub(base_class=None, **attributes): """creates a python class on-the-fly with the given keyword-arguments as class-attributes accessible with .attrname. The new class inherits from Use this to mock rather than stub. """ if base_class is None: base_class = object members = { ...
[ "def", "stub", "(", "base_class", "=", "None", ",", "*", "*", "attributes", ")", ":", "if", "base_class", "is", "None", ":", "base_class", "=", "object", "members", "=", "{", "\"__init__\"", ":", "lambda", "self", ":", "None", ",", "\"__new__\"", ":", ...
33.35
0.001458
def rsa_pss_sign(private_key, data, hash_algorithm): """ Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xB...
[ "def", "rsa_pss_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n private_key must be an instance of ...
29.768116
0.000943
def to_json(self, *attributes, **options): """ Returns the selected field *attributes* for each :class:`Field` *nested* in the `Container` as a JSON formatted string. The *attributes* of each :class:`Field` for containers *nested* in the `Container` are viewed as well (chained method ca...
[ "def", "to_json", "(", "self", ",", "*", "attributes", ",", "*", "*", "options", ")", ":", "nested", "=", "options", ".", "pop", "(", "'nested'", ",", "False", ")", "fieldnames", "=", "options", ".", "pop", "(", "'fieldnames'", ",", "attributes", ")", ...
51
0.001991
def error_response(response): """ Raises errors matching the response code """ if response.status_code >= 500: raise exceptions.GeocodioServerError elif response.status_code == 403: raise exceptions.GeocodioAuthError elif response.status_code == 422: raise exceptions.Ge...
[ "def", "error_response", "(", "response", ")", ":", "if", "response", ".", "status_code", ">=", "500", ":", "raise", "exceptions", ".", "GeocodioServerError", "elif", "response", ".", "status_code", "==", "403", ":", "raise", "exceptions", ".", "GeocodioAuthErro...
28.352941
0.002008
def set_config(config_file='/etc/dnsmasq.conf', follow=True, **kwargs): ''' Sets a value or a set of values in the specified file. By default, if conf-dir is configured in this file, salt will attempt to set the option in any file inside the conf-dir where it has already been enabled. If it does not...
[ "def", "set_config", "(", "config_file", "=", "'/etc/dnsmasq.conf'", ",", "follow", "=", "True", ",", "*", "*", "kwargs", ")", ":", "dnsopts", "=", "get_config", "(", "config_file", ")", "includes", "=", "[", "config_file", "]", "if", "follow", "is", "True...
44
0.001793
def line_model(freq, data, tref, amp=1, phi=0): """ Simple time-domain model for a frequency line. Parameters ---------- freq: float Frequency of the line. data: pycbc.types.TimeSeries Reference data, to get delta_t, start_time, duration and sample_times. tref: float Ref...
[ "def", "line_model", "(", "freq", ",", "data", ",", "tref", ",", "amp", "=", "1", ",", "phi", "=", "0", ")", ":", "freq_line", "=", "TimeSeries", "(", "zeros", "(", "len", "(", "data", ")", ")", ",", "delta_t", "=", "data", ".", "delta_t", ",", ...
33.96875
0.000894
def encode(binary_data): ''' Encode binary data using Bell-202 AFSK Expects a bitarray.bitarray() object of binary data as its argument. Returns a generator of sound samples suitable for use with the audiogen module. ''' framed_data = frame(binary_data) # set volume to 1/2, preceed packet with 1/20 s silenc...
[ "def", "encode", "(", "binary_data", ")", ":", "framed_data", "=", "frame", "(", "binary_data", ")", "# set volume to 1/2, preceed packet with 1/20 s silence to allow for startup glitches", "for", "sample", "in", "itertools", ".", "chain", "(", "audiogen", ".", "silence",...
28.882353
0.043393
def get_monitored_hosting_devices_info(self, hd_state_filter=None): """ This function returns a list of all hosting devices monitored by this agent """ wait_time = datetime.timedelta( seconds=cfg.CONF.cfg_agent.hosting_device_dead_timeout) resp = [] fo...
[ "def", "get_monitored_hosting_devices_info", "(", "self", ",", "hd_state_filter", "=", "None", ")", ":", "wait_time", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "cfg", ".", "CONF", ".", "cfg_agent", ".", "hosting_device_dead_timeout", ")", "resp", "...
39.970588
0.001437
def new(self, node: Node): """Creates property for node""" return Property(self.name, self._setter, node)
[ "def", "new", "(", "self", ",", "node", ":", "Node", ")", ":", "return", "Property", "(", "self", ".", "name", ",", "self", ".", "_setter", ",", "node", ")" ]
39.666667
0.016529
def _parse_criteria(self, criteria): """ Internal method to perform mapping of criteria to proper mongo queries using aliases, as well as some useful sanitization. For example, string formulas such as "Fe2O3" are auto-converted to proper mongo queries of {"Fe":2, "O":3}. ...
[ "def", "_parse_criteria", "(", "self", ",", "criteria", ")", ":", "if", "criteria", "is", "None", ":", "return", "dict", "(", ")", "parsed_crit", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "self", ".", "default_criteria", ".", "items", "(", "...
44.882353
0.001283
def reload(self, client=None, retry=DEFAULT_RETRY): """API call: refresh job properties via a GET request. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get :type client: :class:`~google.cloud.bigquery.client.Client` or ``NoneType`` :p...
[ "def", "reload", "(", "self", ",", "client", "=", "None", ",", "retry", "=", "DEFAULT_RETRY", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "extra_params", "=", "{", "}", "if", "self", ".", "location", ":", "extra_params", ...
36.458333
0.002227
def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in...
[ "def", "check_site_dir", "(", "self", ")", ":", "instdir", "=", "normalize_path", "(", "self", ".", "install_dir", ")", "pth_file", "=", "os", ".", "path", ".", "join", "(", "instdir", ",", "'easy-install.pth'", ")", "# Is it a configured, PYTHONPATH, implicit, or...
42.5
0.001095
def variable_type(self, variable): """Get the Type from the variable string or default to String type. The default type is "String" for those cases when the input variable is contains not "DB variable" and is just a String. **Example Variable**:: #App:1234:output!StringArr...
[ "def", "variable_type", "(", "self", ",", "variable", ")", ":", "var_type", "=", "'String'", "if", "variable", "is", "not", "None", ":", "variable", "=", "variable", ".", "strip", "(", ")", "# self.tcex.log.info(u'Variable {}'.format(variable))", "if", "re", "."...
31.888889
0.002255
def _inchi_labels(mol): """ Get the inchi canonical labels of the heavy atoms in the molecule Args: mol: The molecule. OpenBabel OBMol object Returns: The label mappings. List of tuple of canonical label, original label List of equivalent...
[ "def", "_inchi_labels", "(", "mol", ")", ":", "obconv", "=", "ob", ".", "OBConversion", "(", ")", "obconv", ".", "SetOutFormat", "(", "str", "(", "\"inchi\"", ")", ")", "obconv", ".", "AddOption", "(", "str", "(", "\"a\"", ")", ",", "ob", ".", "OBCon...
42.40625
0.002161
def from_serializable_dict(x): """ Reconstruct a dictionary by recursively reconstructing all its keys and values. This is the most hackish part since we rely on key names such as __name__, __class__, __module__ as metadata about how to reconstruct an object. TODO: It would be cleaner to a...
[ "def", "from_serializable_dict", "(", "x", ")", ":", "if", "\"__name__\"", "in", "x", ":", "return", "_lookup_value", "(", "x", ".", "pop", "(", "\"__module__\"", ")", ",", "x", ".", "pop", "(", "\"__name__\"", ")", ")", "non_string_key_objects", "=", "[",...
37.351351
0.000705
def next_frame_sv2p_discrete(): """SV2P discrete model hparams.""" hparams = next_frame_sv2p() hparams.action_injection = "multiplicative" hparams.small_mode = True hparams.add_hparam("bottleneck_bits", 128) hparams.add_hparam("bottleneck_noise", 0.02) hparams.add_hparam("discrete_warmup_steps", 40000) ...
[ "def", "next_frame_sv2p_discrete", "(", ")", ":", "hparams", "=", "next_frame_sv2p", "(", ")", "hparams", ".", "action_injection", "=", "\"multiplicative\"", "hparams", ".", "small_mode", "=", "True", "hparams", ".", "add_hparam", "(", "\"bottleneck_bits\"", ",", ...
41.615385
0.023508
def registerHandler(self, fh): # Do I even need that? possible FIXME. """ Register new file descriptor. Parameters ---------- fh : int File descriptor. """ self.fds.add(fh) self.atime = int(time()) # update access time self.lock.acq...
[ "def", "registerHandler", "(", "self", ",", "fh", ")", ":", "# Do I even need that? possible FIXME.", "self", ".", "fds", ".", "add", "(", "fh", ")", "self", ".", "atime", "=", "int", "(", "time", "(", ")", ")", "# update access time", "self", ".", "lock",...
26.6
0.01016
def down_ec2(connection, instance_id, region, log=False): """ shutdown of an existing EC2 instance """ # get the instance_id from the state file, and stop the instance instance = connection.stop_instances(instance_ids=instance_id)[0] while instance.state != "stopped": if log: log_yel...
[ "def", "down_ec2", "(", "connection", ",", "instance_id", ",", "region", ",", "log", "=", "False", ")", ":", "# get the instance_id from the state file, and stop the instance", "instance", "=", "connection", ".", "stop_instances", "(", "instance_ids", "=", "instance_id"...
42.272727
0.002105
def admin_keywords_submit(request): """ Adds any new given keywords from the custom keywords field in the admin, and returns their IDs for use when saving a model with a keywords field. """ keyword_ids, titles = [], [] remove = punctuation.replace("-", "") # Strip punctuation, allow dashes....
[ "def", "admin_keywords_submit", "(", "request", ")", ":", "keyword_ids", ",", "titles", "=", "[", "]", ",", "[", "]", "remove", "=", "punctuation", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "# Strip punctuation, allow dashes.", "for", "title", "in", "r...
45.222222
0.002407
def compare_zips(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances """ ll = set(left.namelist()) rl = set(right.namelist()) for f in ll: if f in rl: rl.remove(f) if f[-1] == '/': #...
[ "def", "compare_zips", "(", "left", ",", "right", ")", ":", "ll", "=", "set", "(", "left", ".", "namelist", "(", ")", ")", "rl", "=", "set", "(", "right", ".", "namelist", "(", ")", ")", "for", "f", "in", "ll", ":", "if", "f", "in", "rl", ":"...
19.428571
0.001751
def get_collections(self, data): """Return serialized list of collection objects on data that user has `view` permission on.""" collections = self._filter_queryset('view_collection', data.collection_set.all()) from .collection import CollectionSerializer class CollectionWithoutDataSeri...
[ "def", "get_collections", "(", "self", ",", "data", ")", ":", "collections", "=", "self", ".", "_filter_queryset", "(", "'view_collection'", ",", "data", ".", "collection_set", ".", "all", "(", ")", ")", "from", ".", "collection", "import", "CollectionSerializ...
52.7
0.011194
def get_jobs(self, name=None): """Retrieves jobs running on this resource in its instance. Args: name (str, optional): Only return jobs containing property **name** that matches `name`. `name` can be a regular expression. If `name` is not supplied, then all jobs are returned...
[ "def", "get_jobs", "(", "self", ",", "name", "=", "None", ")", ":", "if", "self", ".", "applicationResource", ":", "return", "self", ".", "_get_elements", "(", "self", ".", "jobs", ",", "'jobs'", ",", "Job", ",", "None", ",", "name", ")", "else", ":"...
39.352941
0.008759
def show_subnet(self, subnet, **_params): """Fetches information of a certain subnet.""" return self.get(self.subnet_path % (subnet), params=_params)
[ "def", "show_subnet", "(", "self", ",", "subnet", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "subnet_path", "%", "(", "subnet", ")", ",", "params", "=", "_params", ")" ]
54.333333
0.012121
def piece_wise_linear(scale, points): """Create a palette that is piece-wise linear given some colors at points.""" assert len(points) >= 2 assert points[0][0] == 0 assert points[-1][0] == 1 assert all(i < j for i, j in zip(points[:-1], points[1:])) out = numpy.zeros((scale, 3)) p1, c1 = points[0] p2, c...
[ "def", "piece_wise_linear", "(", "scale", ",", "points", ")", ":", "assert", "len", "(", "points", ")", ">=", "2", "assert", "points", "[", "0", "]", "[", "0", "]", "==", "0", "assert", "points", "[", "-", "1", "]", "[", "0", "]", "==", "1", "a...
27.55
0.026316
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
[ "def", "from_record", "(", "self", ",", "record", ")", ":", "kwargs", "=", "self", ".", "get_field_kwargs", "(", "record", ")", "return", "self", ".", "sequenced_item_class", "(", "*", "*", "kwargs", ")" ]
37.666667
0.008658