text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def attempt_connection(self): """ Establish a multicast connection - uses 2 sockets (one for sending, the other for receiving) """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,...
[ "def", "attempt_connection", "(", "self", ")", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ",", "socket", ".", "IPPROTO_UDP", ")", "self", ".", "socket", ".", "setsockopt", "(...
56.875
0.00973
def dependencies(project_name): """Get the dependencies for a project.""" log = logging.getLogger('ciu') log.info('Locating dependencies for {}'.format(project_name)) located = distlib.locators.locate(project_name, prereleases=True) if not located: log.warning('{0} not found'.format(project_...
[ "def", "dependencies", "(", "project_name", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ciu'", ")", "log", ".", "info", "(", "'Locating dependencies for {}'", ".", "format", "(", "project_name", ")", ")", "located", "=", "distlib", ".", "locato...
44.9
0.002183
def _do_weak_search(self, obj, recursive): """Search for an element that looks like *obj* within the node list. This follows the same rules as :meth:`_do_strong_search` with some differences. *obj* is treated as a string that might represent any :class:`.Node`, :class:`.Wikicode`, or co...
[ "def", "_do_weak_search", "(", "self", ",", "obj", ",", "recursive", ")", ":", "obj", "=", "parse_anything", "(", "obj", ")", "if", "not", "obj", "or", "obj", "not", "in", "self", ":", "raise", "ValueError", "(", "obj", ")", "results", "=", "[", "]",...
45.046512
0.001011
def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals """ if not g.cpars['hcam_server_on']: g.clog.warn('insertFITSHDU: servers ar...
[ "def", "insertFITSHDU", "(", "g", ")", ":", "if", "not", "g", ".", "cpars", "[", "'hcam_server_on'", "]", ":", "g", ".", "clog", ".", "warn", "(", "'insertFITSHDU: servers are not active'", ")", "return", "False", "run_number", "=", "getRunNumber", "(", "g",...
32.777778
0.001646
def _split_into_chunks(self): """Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects. """ # The list of chunks so far, and the one we'r...
[ "def", "_split_into_chunks", "(", "self", ")", ":", "# The list of chunks so far, and the one we're working on.", "chunks", "=", "[", "]", "chunk", "=", "None", "# A dict mapping byte offsets of line starts to the line numbers.", "bytes_lines_map", "=", "dict", "(", "self", "...
42.145038
0.000885
def authenticate(self, request): """ Authenticate request using HTTP Basic authentication protocl. If the user is successfully identified, the corresponding user object is stored in `request.user`. If the request has already been authenticated (i.e. `request.user` has authenticated user...
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "# todo: can we trust that request.user variable is even defined?", "if", "request", ".", "user", "and", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "request", ".", "user", ...
42.969697
0.001379
def login(self, username, password='', login_key=None, auth_code=None, two_factor_code=None, login_id=None): """Login as a specific user :param username: username :type username: :class:`str` :param password: password :type password: :class:`str` :param login_key: login ...
[ "def", "login", "(", "self", ",", "username", ",", "password", "=", "''", ",", "login_key", "=", "None", ",", "auth_code", "=", "None", ",", "two_factor_code", "=", "None", ",", "login_id", "=", "None", ")", ":", "self", ".", "_LOG", ".", "debug", "(...
38.825581
0.001752
def parse_json_date(value): """ Parses an ISO8601 formatted datetime from a string value """ if not value: return None return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
[ "def", "parse_json_date", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "return", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "JSON_DATETIME_FORMAT", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ...
28.5
0.008511
def parse_network(network_fp): """Parses network file and returns a network instance and a gene set. Attribute: network_fp (str): File path to a network file. """ graph = nx.Graph() gene_set = set() with open(network_fp) as inFile: inFile.readline() # Skip header. ...
[ "def", "parse_network", "(", "network_fp", ")", ":", "graph", "=", "nx", ".", "Graph", "(", ")", "gene_set", "=", "set", "(", ")", "with", "open", "(", "network_fp", ")", "as", "inFile", ":", "inFile", ".", "readline", "(", ")", "# Skip header.\r", "fo...
29.333333
0.001835
def _min_timezone_offset(): "time zone offset (minutes)" now = time.time() return (datetime.datetime.fromtimestamp(now) - datetime.datetime.utcfromtimestamp(now)).seconds // 60
[ "def", "_min_timezone_offset", "(", ")", ":", "now", "=", "time", ".", "time", "(", ")", "return", "(", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "now", ")", "-", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "now", ")", ")", ...
46.25
0.010638
def worker_logwarning(self, message, code, nodeid, fslocation): """Emitted when a node calls the pytest_logwarning hook.""" kwargs = dict(message=message, code=code, nodeid=nodeid, fslocation=fslocation) self.config.hook.pytest_logwarning.call_historic(kwargs=kwargs)
[ "def", "worker_logwarning", "(", "self", ",", "message", ",", "code", ",", "nodeid", ",", "fslocation", ")", ":", "kwargs", "=", "dict", "(", "message", "=", "message", ",", "code", "=", "code", ",", "nodeid", "=", "nodeid", ",", "fslocation", "=", "fs...
72
0.010309
def download(self, file_path=None, verbose=None, silent=None, ignore_existing=None, checksum=None, destdir=None, retries=None, ignore_errors=None, fileobj=None, return_responses=None, no_change_timestamp=None, params=None): """Download the file into the current...
[ "def", "download", "(", "self", ",", "file_path", "=", "None", ",", "verbose", "=", "None", ",", "silent", "=", "None", ",", "ignore_existing", "=", "None", ",", "checksum", "=", "None", ",", "destdir", "=", "None", ",", "retries", "=", "None", ",", ...
39.715909
0.001814
def _metahash(self): """Checksum hash of all the inputs to this rule. Output is invalid until collect_srcs and collect_deps have been run. In theory, if this hash doesn't change, the outputs won't change either, which makes it useful for caching. """ # BE CAREFUL when ...
[ "def", "_metahash", "(", "self", ")", ":", "# BE CAREFUL when overriding/extending this method. You want to copy", "# the if(cached)/return(cached) part, then call this method, then at", "# the end update the cached metahash. Just like this code, basically,", "# only you call the method from the b...
48.119048
0.00097
def _from_dict_dict(cls, dic): """Takes a dict {id : dict_attributes} """ return cls({_convert_id(i): v for i, v in dic.items()})
[ "def", "_from_dict_dict", "(", "cls", ",", "dic", ")", ":", "return", "cls", "(", "{", "_convert_id", "(", "i", ")", ":", "v", "for", "i", ",", "v", "in", "dic", ".", "items", "(", ")", "}", ")" ]
47.666667
0.013793
def _harvest_data(self): """Get the collected data and reset the collector. Also warn about various problems collecting data. """ if not self._measured: return self.data.add_line_data(self.collector.get_line_data()) self.data.add_arc_data(self.collector.get...
[ "def", "_harvest_data", "(", "self", ")", ":", "if", "not", "self", ".", "_measured", ":", "return", "self", ".", "data", ".", "add_line_data", "(", "self", ".", "collector", ".", "get_line_data", "(", ")", ")", "self", ".", "data", ".", "add_arc_data", ...
34.351351
0.00153
def next(self): """Returns the next batch of data.""" if not self.iter_next(): raise StopIteration data = self.getdata() label = self.getlabel() # iter should stop when last batch is not complete if data[0].shape[0] != self.batch_size: # in this case, ...
[ "def", "next", "(", "self", ")", ":", "if", "not", "self", ".", "iter_next", "(", ")", ":", "raise", "StopIteration", "data", "=", "self", ".", "getdata", "(", ")", "label", "=", "self", ".", "getlabel", "(", ")", "# iter should stop when last batch is not...
37.857143
0.009208
def select_row(self, steps): """Move selected row a number of steps. Iterates in a cyclic behaviour. """ row = (self.currentRow() + steps) % self.count() self.setCurrentRow(row)
[ "def", "select_row", "(", "self", ",", "steps", ")", ":", "row", "=", "(", "self", ".", "currentRow", "(", ")", "+", "steps", ")", "%", "self", ".", "count", "(", ")", "self", ".", "setCurrentRow", "(", "row", ")" ]
31.142857
0.008929
def _send_update(self, data): """Send a NetworkTables update via the stored send_update callback""" if isinstance(data, dict): data = json.dumps(data) self.update_callback(data)
[ "def", "_send_update", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "self", ".", "update_callback", "(", "data", ")" ]
41.8
0.00939
def do_decode(cls, obj, obj_type): # type: (Any, ConjureTypeType) -> Any """Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into. """ if inspect.isclass(obj_type) and ...
[ "def", "do_decode", "(", "cls", ",", "obj", ",", "obj_type", ")", ":", "# type: (Any, ConjureTypeType) -> Any", "if", "inspect", ".", "isclass", "(", "obj_type", ")", "and", "issubclass", "(", "# type: ignore", "obj_type", ",", "ConjureBeanType", ")", ":", "retu...
37.060606
0.00239
def dump(c, from_date, with_json=True, latest_only=False, **kwargs): """Dump the community object as dictionary. :param c: Community to be dumped. :type c: `invenio.modules.communities.models.Community` :returns: Community serialized to dictionary. :rtype: dict """ return dict(id=c.id, ...
[ "def", "dump", "(", "c", ",", "from_date", ",", "with_json", "=", "True", ",", "latest_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "dict", "(", "id", "=", "c", ".", "id", ",", "id_user", "=", "c", ".", "id_user", ",", "title...
41.25
0.000987
def flatten_errors(cfg, res, levels=None, results=None): """ An example function that will turn a nested dictionary of results (as returned by ``ConfigObj.validate``) into a flat list. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results dictionary returned by ``validate``. ...
[ "def", "flatten_errors", "(", "cfg", ",", "res", ",", "levels", "=", "None", ",", "results", "=", "None", ")", ":", "if", "levels", "is", "None", ":", "# first time called", "levels", "=", "[", "]", "results", "=", "[", "]", "if", "res", "==", "True"...
33.206897
0.002017
def iso8601interval(value, argument='argument'): """Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exc...
[ "def", "iso8601interval", "(", "value", ",", "argument", "=", "'argument'", ")", ":", "try", ":", "start", ",", "end", "=", "_parse_interval", "(", "value", ")", "if", "end", "is", "None", ":", "end", "=", "_expand_datetime", "(", "start", ",", "value", ...
41.255814
0.001652
def file_groups(self): """ List the ``USE`` attributes of all ``mets:fileGrp``. """ return [el.get('USE') for el in self._tree.getroot().findall('.//mets:fileGrp', NS)]
[ "def", "file_groups", "(", "self", ")", ":", "return", "[", "el", ".", "get", "(", "'USE'", ")", "for", "el", "in", "self", ".", "_tree", ".", "getroot", "(", ")", ".", "findall", "(", "'.//mets:fileGrp'", ",", "NS", ")", "]" ]
39.2
0.015
def iter_paths(src_dir): """ Function that recursively locates files within folder Note: scandir does not guarantee ordering :param src_dir: string for directory to be parsed through :return an iterable of DirEntry objects all files within the src_dir """ for x in scandir(os.path.join(src_d...
[ "def", "iter_paths", "(", "src_dir", ")", ":", "for", "x", "in", "scandir", "(", "os", ".", "path", ".", "join", "(", "src_dir", ")", ")", ":", "if", "x", ".", "is_dir", "(", "follow_symlinks", "=", "False", ")", ":", "for", "x", "in", "iter_paths"...
35.076923
0.002137
def report(request, comment_id): """ Flags a comment on GET. Redirects to whatever is provided in request.REQUEST['next']. """ comment = get_object_or_404( django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) if comment.parent is not None: messages.info(reques...
[ "def", "report", "(", "request", ",", "comment_id", ")", ":", "comment", "=", "get_object_or_404", "(", "django_comments", ".", "get_model", "(", ")", ",", "pk", "=", "comment_id", ",", "site__pk", "=", "settings", ".", "SITE_ID", ")", "if", "comment", "."...
33.823529
0.001692
def version_from_branch(branch): """ return version information from a git branch name """ try: return tuple( map( int, re.match(r"^.*(?P<version>\d+(\.\d+)+).*$", branch) .groupdict()["version"] .split("."), ...
[ "def", "version_from_branch", "(", "branch", ")", ":", "try", ":", "return", "tuple", "(", "map", "(", "int", ",", "re", ".", "match", "(", "r\"^.*(?P<version>\\d+(\\.\\d+)+).*$\"", ",", "branch", ")", ".", "groupdict", "(", ")", "[", "\"version\"", "]", "...
28.058824
0.002028
def get_player_id(player): """ Returns the player ID(s) associated with the player name that is passed in. There are instances where players have the same name so there are multiple player IDs associated with it. Parameters ---------- player : str The desired player's name in 'Last...
[ "def", "get_player_id", "(", "player", ")", ":", "players_df", "=", "get_all_player_ids", "(", "\"all_data\"", ")", "player", "=", "players_df", "[", "players_df", ".", "DISPLAY_LAST_COMMA_FIRST", "==", "player", "]", "# if there are no plyaers by the given name, raise an...
33.464286
0.001037
def render(obj, backend=None, **kwargs): """ Renders the HoloViews object to the corresponding object in the specified backend, e.g. a Matplotlib or Bokeh figure. The backend defaults to the currently declared default backend. The resulting object can then be used with other objects in the spec...
[ "def", "render", "(", "obj", ",", "backend", "=", "None", ",", "*", "*", "kwargs", ")", ":", "backend", "=", "backend", "or", "Store", ".", "current_backend", "renderer_obj", "=", "renderer", "(", "backend", ")", "if", "kwargs", ":", "renderer_obj", "=",...
36.054054
0.00073
def top2_reduced(params, moments): """ Description: Top 2 alternatives 12 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) """ pa...
[ "def", "top2_reduced", "(", "params", ",", "moments", ")", ":", "params", "=", "np", ".", "asarray", "(", "params", ")", "alpha", "=", "params", "[", "0", "]", "a", "=", "params", "[", "1", ":", "5", "]", "b", "=", "params", "[", "5", ":", "]",...
42.7
0.010309
def read_distributions_from_config(cp, section="prior"): """Returns a list of PyCBC distribution instances for a section in the given configuration file. Parameters ---------- cp : WorflowConfigParser An open config file to read. section : {"prior", string} Prefix on section nam...
[ "def", "read_distributions_from_config", "(", "cp", ",", "section", "=", "\"prior\"", ")", ":", "dists", "=", "[", "]", "variable_args", "=", "[", "]", "for", "subsection", "in", "cp", ".", "get_subsections", "(", "section", ")", ":", "name", "=", "cp", ...
32.407407
0.00111
def csrf_protect_all_post_and_cross_origin_requests(): """returns None upon success""" success = None if is_cross_origin(request): logger.warning("Received cross origin request. Aborting") abort(403) if request.method in ["POST", "PUT"]: token = session.get("csrf_token") ...
[ "def", "csrf_protect_all_post_and_cross_origin_requests", "(", ")", ":", "success", "=", "None", "if", "is_cross_origin", "(", "request", ")", ":", "logger", ".", "warning", "(", "\"Received cross origin request. Aborting\"", ")", "abort", "(", "403", ")", "if", "re...
31.722222
0.001701
def interpolate_linear(self, lons, lats, data): """ Interpolate using linear approximation Returns the same as interpolate(lons,lats,data,order=1) """ return self.interpolate(lons, lats, data, order=1)
[ "def", "interpolate_linear", "(", "self", ",", "lons", ",", "lats", ",", "data", ")", ":", "return", "self", ".", "interpolate", "(", "lons", ",", "lats", ",", "data", ",", "order", "=", "1", ")" ]
39.333333
0.008299
def await_reservations(self, sc, status={}, timeout=600): """Block until all reservations are received.""" timespent = 0 while not self.reservations.done(): logging.info("waiting for {0} reservations".format(self.reservations.remaining())) # check status flags for any errors if 'error' in ...
[ "def", "await_reservations", "(", "self", ",", "sc", ",", "status", "=", "{", "}", ",", "timeout", "=", "600", ")", ":", "timespent", "=", "0", "while", "not", "self", ".", "reservations", ".", "done", "(", ")", ":", "logging", ".", "info", "(", "\...
37.875
0.012882
def get_target_forums_for_moved_topics(self, user): """ Returns a list of forums in which the considered user can add topics that have been moved from another forum. """ return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum]
[ "def", "get_target_forums_for_moved_topics", "(", "self", ",", "user", ")", ":", "return", "[", "f", "for", "f", "in", "self", ".", "_get_forums_for_user", "(", "user", ",", "[", "'can_move_topics'", ",", "]", ")", "if", "f", ".", "is_forum", "]" ]
58
0.013605
def _find_references(model_name, references=None): """ Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). """ references = references or [] references.append(model_name) ref = M...
[ "def", "_find_references", "(", "model_name", ",", "references", "=", "None", ")", ":", "references", "=", "references", "or", "[", "]", "references", ".", "append", "(", "model_name", ")", "ref", "=", "MODELS", "[", "model_name", "]", ".", "get", "(", "...
29.588235
0.001927
def _get_receiver_name(self): """Get name of receiver from web interface if not set.""" # If name is not set yet, get it from Main Zone URL if self._name is None and self._urls.mainzone is not None: name_tag = {"FriendlyName": None} try: root = self.get_st...
[ "def", "_get_receiver_name", "(", "self", ")", ":", "# If name is not set yet, get it from Main Zone URL", "if", "self", ".", "_name", "is", "None", "and", "self", ".", "_urls", ".", "mainzone", "is", "not", "None", ":", "name_tag", "=", "{", "\"FriendlyName\"", ...
50.736842
0.002037
def get_position(self): ''' Read chuck position (x, y, z)''' reply = self._intf.query('ReadChuckPosition Y H')[2:] return [float(i) for i in reply.split()]
[ "def", "get_position", "(", "self", ")", ":", "reply", "=", "self", ".", "_intf", ".", "query", "(", "'ReadChuckPosition Y H'", ")", "[", "2", ":", "]", "return", "[", "float", "(", "i", ")", "for", "i", "in", "reply", ".", "split", "(", ")", "]" ]
44
0.011173
def max_nt_to_aa_alignment_left(self, CDR3_seq, ntseq): """Find maximum match between CDR3_seq and ntseq from the left. This function returns the length of the maximum length nucleotide subsequence of ntseq contiguous from the left (or 5' end) that is consistent with the 'amino...
[ "def", "max_nt_to_aa_alignment_left", "(", "self", ",", "CDR3_seq", ",", "ntseq", ")", ":", "max_alignment", "=", "0", "if", "len", "(", "ntseq", ")", "==", "0", ":", "return", "0", "aa_aligned", "=", "True", "while", "aa_aligned", ":", "if", "ntseq", "[...
35.591837
0.008371
def fromfile(self, path='filters'): r"""Load filter values from ascii-files. Load filter base and filter coefficients from ascii files in the directory `path`; `path` can be a relative or absolute path. Examples -------- >>> import empymod >>> # Create an empty ...
[ "def", "fromfile", "(", "self", ",", "path", "=", "'filters'", ")", ":", "# Get name of filter", "name", "=", "self", ".", "savename", "# Get absolute path", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "# Get filter base", "basefile", "...
34.214286
0.001353
def count(self, low, high=None): """ Return the number of items between the given bounds. """ if high is None: high = low return self.database.zcount(self.key, low, high)
[ "def", "count", "(", "self", ",", "low", ",", "high", "=", "None", ")", ":", "if", "high", "is", "None", ":", "high", "=", "low", "return", "self", ".", "database", ".", "zcount", "(", "self", ".", "key", ",", "low", ",", "high", ")" ]
30.857143
0.009009
def set_requestable(self, requestable=True): # type: (bool) -> None """Set the dataset to be of type requestable or not Args: requestable (bool): Set whether dataset is requestable. Defaults to True. Returns: None """ self.data['is_requestdata_ty...
[ "def", "set_requestable", "(", "self", ",", "requestable", "=", "True", ")", ":", "# type: (bool) -> None", "self", ".", "data", "[", "'is_requestdata_type'", "]", "=", "requestable", "if", "requestable", ":", "self", ".", "data", "[", "'private'", "]", "=", ...
30.076923
0.009926
def Alias(name, **metadata): """ Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare. class MyClass(HasTraits): line_width = Float(3.0) thickness = Alias("line_width") """ return Property(lambda obj: getattr(obj, name), ...
[ "def", "Alias", "(", "name", ",", "*", "*", "metadata", ")", ":", "return", "Property", "(", "lambda", "obj", ":", "getattr", "(", "obj", ",", "name", ")", ",", "lambda", "obj", ",", "val", ":", "setattr", "(", "obj", ",", "name", ",", "val", ")"...
29.923077
0.002494
def _evaluate(self,z,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential INPUT: z t OUTPUT: Pot(z,t;R) HISTORY: 2010-07-13 - Written - Bovy (NYU) """ return self._Pot(self._R,z,phi=sel...
[ "def", "_evaluate", "(", "self", ",", "z", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_Pot", "(", "self", ".", "_R", ",", "z", ",", "phi", "=", "self", ".", "_phi", ",", "t", "=", "t", ",", "use_physical", "=", "False", ")", "-", ...
25.5
0.030733
def get_webhook(self, id, **data): """ GET /webhooks/:id/ Returns a :format:`webhook` for the specified webhook as ``webhook``. """ return self.get("/webhooks/{0}/".format(id), data=data)
[ "def", "get_webhook", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/webhooks/{0}/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
32.857143
0.012712
def get_ip(self, access='public', addr_family=None, strict=None): """ Return the server's IP address. Params: - addr_family: IPv4, IPv6 or None. None prefers IPv4 but will return IPv6 if IPv4 addr was not available. - access: 'public' or 'private' ...
[ "def", "get_ip", "(", "self", ",", "access", "=", "'public'", ",", "addr_family", "=", "None", ",", "strict", "=", "None", ")", ":", "if", "addr_family", "not", "in", "[", "'IPv4'", ",", "'IPv6'", ",", "None", "]", ":", "raise", "Exception", "(", "\"...
37.5625
0.002433
def add_volume_bricks(name, bricks): ''' Add brick(s) to an existing volume name Volume name bricks List of bricks to add to the volume .. code-block:: yaml myvolume: glusterfs.add_volume_bricks: - bricks: - host1:/srv/gluster/drive1 ...
[ "def", "add_volume_bricks", "(", "name", ",", "bricks", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "False", "}", "volinfo", "=", "__salt__", "[", "'glusterfs.inf...
29.872727
0.001768
def _StatusUpdateThreadMain(self): """Main function of the status update thread.""" while self._status_update_active: # Make a local copy of the PIDs in case the dict is changed by # the main thread. for pid in list(self._process_information_per_pid.keys()): self._CheckStatusAnalysisPr...
[ "def", "_StatusUpdateThreadMain", "(", "self", ")", ":", "while", "self", ".", "_status_update_active", ":", "# Make a local copy of the PIDs in case the dict is changed by", "# the main thread.", "for", "pid", "in", "list", "(", "self", ".", "_process_information_per_pid", ...
36.357143
0.01341
def draw_additive_plot(data, figsize, show, text_rotation=0): """Draw additive plot.""" # Turn off interactive plot if show == False: plt.ioff() # Format data neg_features, total_neg, pos_features, total_pos = format_data(data) # Compute overall metrics base_value = data['b...
[ "def", "draw_additive_plot", "(", "data", ",", "figsize", ",", "show", ",", "text_rotation", "=", "0", ")", ":", "# Turn off interactive plot", "if", "show", "==", "False", ":", "plt", ".", "ioff", "(", ")", "# Format data", "neg_features", ",", "total_neg", ...
32.046154
0.009315
def prepare_percolator_output(self, fn): """Returns namespace and static xml from percolator output file""" ns = xml.get_namespace(fn) static = readers.get_percolator_static_xml(fn, ns) return ns, static
[ "def", "prepare_percolator_output", "(", "self", ",", "fn", ")", ":", "ns", "=", "xml", ".", "get_namespace", "(", "fn", ")", "static", "=", "readers", ".", "get_percolator_static_xml", "(", "fn", ",", "ns", ")", "return", "ns", ",", "static" ]
46.2
0.008511
def reopenOutputFiles(): """ Reopens the stdout and stderr output files, as set by L{outputToFiles}. """ if not _stdout and not _stderr: debug('log', 'told to reopen log files, but log files not set') return def reopen(name, fileno, *args): oldmask = os.umask(0026) ...
[ "def", "reopenOutputFiles", "(", ")", ":", "if", "not", "_stdout", "and", "not", "_stderr", ":", "debug", "(", "'log'", ",", "'told to reopen log files, but log files not set'", ")", "return", "def", "reopen", "(", "name", ",", "fileno", ",", "*", "args", ")",...
25.083333
0.0016
def contains(self, k): """Return True if key `k` exists""" if self._changed(): self._read() return k in self.store.keys()
[ "def", "contains", "(", "self", ",", "k", ")", ":", "if", "self", ".", "_changed", "(", ")", ":", "self", ".", "_read", "(", ")", "return", "k", "in", "self", ".", "store", ".", "keys", "(", ")" ]
30.6
0.012739
def parse_request(): """Parse request endpoint and return (resource, action)""" find = None if request.endpoint is not None: find = PATTERN_ENDPOINT.findall(request.endpoint) if not find: raise ValueError("invalid endpoint %s" % request.endpoint) __, resource, action_name = find[0] ...
[ "def", "parse_request", "(", ")", ":", "find", "=", "None", "if", "request", ".", "endpoint", "is", "not", "None", ":", "find", "=", "PATTERN_ENDPOINT", ".", "findall", "(", "request", ".", "endpoint", ")", "if", "not", "find", ":", "raise", "ValueError"...
35.692308
0.002101
def fit(self, X, y, model_filename=None): """Fit FastText according to X, y Parameters: ---------- X : list of text each item is a text y: list each item is either a label (in multi class problem) or list of labels (in multi label problem) ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "model_filename", "=", "None", ")", ":", "train_file", "=", "\"temp.train\"", "X", "=", "[", "x", ".", "replace", "(", "\"\\n\"", ",", "\" \"", ")", "for", "x", "in", "X", "]", "y", "=", "[", ...
35.478261
0.002387
def solveConsAggMarkov(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,MrkvArray, PermGroFac,PermGroFacAgg,aXtraGrid,BoroCnstArt,Mgrid, AFunc,Rfunc,wFunc,DeprFac): ''' Solve one period of a consumption-saving problem with idiosyncratic and aggregate shocks (transit...
[ "def", "solveConsAggMarkov", "(", "solution_next", ",", "IncomeDstn", ",", "LivPrb", ",", "DiscFac", ",", "CRRA", ",", "MrkvArray", ",", "PermGroFac", ",", "PermGroFacAgg", ",", "aXtraGrid", ",", "BoroCnstArt", ",", "Mgrid", ",", "AFunc", ",", "Rfunc", ",", ...
54.892157
0.017367
def coerce(value): """ Coerces a Bool, None, or int into Bit/Propositional form """ if isinstance(value, BoolCell): return value elif isinstance(value, Cell): raise CellConstructionFailure("Cannot convert %s to BoolCell" % \ type(value)...
[ "def", "coerce", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "BoolCell", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "Cell", ")", ":", "raise", "CellConstructionFailure", "(", "\"Cannot convert %s to BoolCell\"", "%...
34.055556
0.009524
def _from_objects(cls, objects): """ Private constructor: create graph from the given Python objects. The constructor examines the referents of each given object to build up a graph showing the objects and their links. """ vertices = ElementTransformSet(transform=id) ...
[ "def", "_from_objects", "(", "cls", ",", "objects", ")", ":", "vertices", "=", "ElementTransformSet", "(", "transform", "=", "id", ")", "out_edges", "=", "KeyTransformDict", "(", "transform", "=", "id", ")", "in_edges", "=", "KeyTransformDict", "(", "transform...
31.511628
0.001432
def send(self, msg, timeout=None): """ Send a message over the serial device. :param can.Message msg: Message to send. .. note:: Flags like ``extended_id``, ``is_remote_frame`` and ``is_error_frame`` will be ignored. .. note:: If the t...
[ "def", "send", "(", "self", ",", "msg", ",", "timeout", "=", "None", ")", ":", "try", ":", "timestamp", "=", "struct", ".", "pack", "(", "'<I'", ",", "int", "(", "msg", ".", "timestamp", "*", "1000", ")", ")", "except", "struct", ".", "error", ":...
32.837838
0.001599
def _do_connection(self, wgt, sig, func): """ Make a connection between a GUI widget and a callable. wgt and sig are strings with widget and signal name func is a callable for that signal """ #new style (we use this) #self.btn_name.clicked.connect(self.on_btn_na...
[ "def", "_do_connection", "(", "self", ",", "wgt", ",", "sig", ",", "func", ")", ":", "#new style (we use this)", "#self.btn_name.clicked.connect(self.on_btn_name_clicked)", "#old style", "#self.connect(self.btn_name, SIGNAL('clicked()'), self.on_btn_name_clicked)", "if", "hasattr"...
35.2
0.009682
def pickle_save(thing,fname=None): """save something to a pickle file""" if fname is None: fname=os.path.expanduser("~")+"/%d.pkl"%time.time() assert type(fname) is str and os.path.isdir(os.path.dirname(fname)) pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL) print("saved",fname)
[ "def", "pickle_save", "(", "thing", ",", "fname", "=", "None", ")", ":", "if", "fname", "is", "None", ":", "fname", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "+", "\"/%d.pkl\"", "%", "time", ".", "time", "(", ")", "assert", "typ...
44.857143
0.021875
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['pattern'] = utilities.convert_python_regex_to_ecma( self.pattern, self.flags)
[ "def", "modify_schema", "(", "self", ",", "field_schema", ")", ":", "field_schema", "[", "'pattern'", "]", "=", "utilities", ".", "convert_python_regex_to_ecma", "(", "self", ".", "pattern", ",", "self", ".", "flags", ")" ]
45.5
0.010811
def change_minion_cachedir( minion_id, cachedir, data=None, base=None, ): ''' Changes the info inside a minion's cachedir entry. The type of cachedir must be specified (i.e., 'requested' or 'active'). A dict is also passed in which contains the data to be changed. Ex...
[ "def", "change_minion_cachedir", "(", "minion_id", ",", "cachedir", ",", "data", "=", "None", ",", "base", "=", "None", ",", ")", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "False", "if", "base", "is", "None", ":", ...
27.611111
0.000972
def delete_board(self, id): """Delete an agile board.""" board = Board(self._options, self._session, raw={'id': id}) board.delete()
[ "def", "delete_board", "(", "self", ",", "id", ")", ":", "board", "=", "Board", "(", "self", ".", "_options", ",", "self", ".", "_session", ",", "raw", "=", "{", "'id'", ":", "id", "}", ")", "board", ".", "delete", "(", ")" ]
38
0.012903
def _rfc822(date): """Parse RFC 822 dates and times http://tools.ietf.org/html/rfc822#section-5 There are some formatting differences that are accounted for: 1. Years may be two or four digits. 2. The month and day can be swapped. 3. Additional timezone names are supported. 4. A default tim...
[ "def", "_rfc822", "(", "date", ")", ":", "daynames", "=", "set", "(", "[", "'mon'", ",", "'tue'", ",", "'wed'", ",", "'thu'", ",", "'fri'", ",", "'sat'", ",", "'sun'", "]", ")", "months", "=", "{", "'jan'", ":", "1", ",", "'feb'", ":", "2", ","...
31.892157
0.000298
def update(self, *args, **kwargs): '''Preserves order if given an assoc list. ''' arg = dict_arg(*args, **kwargs) if isinstance(arg, list): for key, val in arg: self[key] = val else: super(AssocDict, self).update(arg)
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arg", "=", "dict_arg", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "arg", ",", "list", ")", ":", "for", "key", ",", "val", "in", ...
31.666667
0.013652
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) ...
[ "def", "inv_cipher", "(", "rkey", ",", "ct", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "rkey", "=", "rkey", ".", "reshape", "(", "4", "*", "(", "Nr", "+", "1", ")", ...
24.826087
0.001686
def collect_state(self, configurations): """Collect state from this helper. A set of attributes which summarizes the state of the routers and configurations managed by this config agent. :param configurations: dict of configuration values :return dict of updated configuration va...
[ "def", "collect_state", "(", "self", ",", "configurations", ")", ":", "num_ex_gw_ports", "=", "0", "num_interfaces", "=", "0", "num_floating_ips", "=", "0", "router_infos", "=", "self", ".", "router_info", ".", "values", "(", ")", "num_routers", "=", "len", ...
45.428571
0.001232
def surface(cls, predstr): """Instantiate a Pred from its quoted string representation.""" lemma, pos, sense, _ = split_pred_string(predstr) return cls(Pred.SURFACE, lemma, pos, sense, predstr)
[ "def", "surface", "(", "cls", ",", "predstr", ")", ":", "lemma", ",", "pos", ",", "sense", ",", "_", "=", "split_pred_string", "(", "predstr", ")", "return", "cls", "(", "Pred", ".", "SURFACE", ",", "lemma", ",", "pos", ",", "sense", ",", "predstr", ...
53.5
0.009217
def add_tgt(self, as_rep, enc_as_rep_part, override_pp = True): #from AS_REP """ Creates credential object from the TGT and adds to the ccache file The TGT is basically the native representation of the asn1 encoded AS_REP data that the AD sends upon a succsessful TGT request. This function doesn't do decrypt...
[ "def", "add_tgt", "(", "self", ",", "as_rep", ",", "enc_as_rep_part", ",", "override_pp", "=", "True", ")", ":", "#from AS_REP", "c", "=", "Credential", "(", ")", "c", ".", "client", "=", "CCACHEPrincipal", ".", "from_asn1", "(", "as_rep", "[", "'cname'", ...
47.6
0.034596
def amplification_type(self, channels=None): """ Get the amplification type used for the specified channel(s). Each channel uses one of two amplification types: linear or logarithmic. This function returns, for each channel, a tuple of two numbers, in which the first number indi...
[ "def", "amplification_type", "(", "self", ",", "channels", "=", "None", ")", ":", "# Check default", "if", "channels", "is", "None", ":", "channels", "=", "self", ".", "_channels", "# Get numerical indices of channels", "channels", "=", "self", ".", "_name_to_inde...
41.066667
0.001057
def sort_func(kd1, kd2): """ Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2 """ _l = _cmp(kd1['type'], kd2['type']) if _l: return _l if kd1['type'] == 'EC': ...
[ "def", "sort_func", "(", "kd1", ",", "kd2", ")", ":", "_l", "=", "_cmp", "(", "kd1", "[", "'type'", "]", ",", "kd2", "[", "'type'", "]", ")", "if", "_l", ":", "return", "_l", "if", "kd1", "[", "'type'", "]", "==", "'EC'", ":", "_l", "=", "_cm...
18.880952
0.001199
def attach_loop(argv): """Spawn the process, then repeatedly attach to the process.""" # Check if the pdbhandler module is built into python. p = Popen((sys.executable, '-X', 'pdbhandler', '-c', 'import pdbhandler; pdbhandler.get_handler().host'), stdout=PIPE, stderr=STDOUT) ...
[ "def", "attach_loop", "(", "argv", ")", ":", "# Check if the pdbhandler module is built into python.", "p", "=", "Popen", "(", "(", "sys", ".", "executable", ",", "'-X'", ",", "'pdbhandler'", ",", "'-c'", ",", "'import pdbhandler; pdbhandler.get_handler().host'", ")", ...
33.72
0.001729
def ignored_corner( intersection, tangent_s, tangent_t, edge_nodes1, edge_nodes2 ): """Check if an intersection is an "ignored" corner. .. note:: This is a helper used only by :func:`classify_intersection`. An "ignored" corner is one where the surfaces just "kiss" at the point of intersect...
[ "def", "ignored_corner", "(", "intersection", ",", "tangent_s", ",", "tangent_t", ",", "edge_nodes1", ",", "edge_nodes2", ")", ":", "if", "intersection", ".", "s", "==", "0.0", ":", "if", "intersection", ".", "t", "==", "0.0", ":", "# Double corner.", "retur...
35.947368
0.000475
def run_length_decode(in_array): """A function to run length decode an int array. :param in_array: the input array of integers :return the decoded array""" switch=False out_array=[] in_array = in_array.tolist() for item in in_array: if switch==False: this_item = item ...
[ "def", "run_length_decode", "(", "in_array", ")", ":", "switch", "=", "False", "out_array", "=", "[", "]", "in_array", "=", "in_array", ".", "tolist", "(", ")", "for", "item", "in", "in_array", ":", "if", "switch", "==", "False", ":", "this_item", "=", ...
29.4375
0.014403
def searchNs(self, node, nameSpace): """Search a Ns registered under a given name space for a document. recurse on the parents until it finds the defined namespace or return None otherwise. @nameSpace can be None, this is a search for the default namespace. We don't allow ...
[ "def", "searchNs", "(", "self", ",", "node", ",", "nameSpace", ")", ":", "if", "node", "is", "None", ":", "node__o", "=", "None", "else", ":", "node__o", "=", "node", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlSearchNs", "(", "self", ".", "_o", ...
52.5
0.008021
def submit(self, job_id, directory, script=None): """Submits a job to the queue. If the runtime is not there, it will be installed. If it is a broken chain of links, error. """ if job_id is None: job_id = '%s_%s_%s' % (Path(directory).unicodename, ...
[ "def", "submit", "(", "self", ",", "job_id", ",", "directory", ",", "script", "=", "None", ")", ":", "if", "job_id", "is", "None", ":", "job_id", "=", "'%s_%s_%s'", "%", "(", "Path", "(", "directory", ")", ".", "unicodename", ",", "self", ".", "desti...
33.037736
0.001109
def verify_signature(key_dict, signature, data): """ <Purpose> Determine whether the private key belonging to 'key_dict' produced 'signature'. verify_signature() will use the public key found in 'key_dict', the 'sig' objects contained in 'signature', and 'data' to complete the verification. >>...
[ "def", "verify_signature", "(", "key_dict", ",", "signature", ",", "data", ")", ":", "# Does 'key_dict' have the correct format?", "# This check will ensure 'key_dict' has the appropriate number", "# of objects and object types, and that all dict keys are properly named.", "# Raise 'secure...
36.978417
0.008905
def AppConfigFlagHandler(feature=None): """ This is the default handler. It checks for feature flags in the current app's configuration. For example, to have 'unfinished_feature' hidden in production but active in development: config.py class ProductionConfig(Config): FEATURE_FLAGS = { 'unfinished...
[ "def", "AppConfigFlagHandler", "(", "feature", "=", "None", ")", ":", "if", "not", "current_app", ":", "log", ".", "warn", "(", "u\"Got a request to check for {feature} but we're outside the request context. Returning False\"", ".", "format", "(", "feature", "=", "feature...
25.310345
0.010499
def isSigned(self, ns_uri, ns_key): """Return whether a particular key is signed, regardless of its namespace alias """ return self.message.getKey(ns_uri, ns_key) in self.signed_fields
[ "def", "isSigned", "(", "self", ",", "ns_uri", ",", "ns_key", ")", ":", "return", "self", ".", "message", ".", "getKey", "(", "ns_uri", ",", "ns_key", ")", "in", "self", ".", "signed_fields" ]
42.4
0.009259
def publish(self, data, type=None, id=None, retry=None, channel='sse'): """ Publish data as a server-sent event. :param data: The event data. If it is not a string, it will be serialized to JSON using the Flask application's :class:`~flask.json.JSONEncoder`. :par...
[ "def", "publish", "(", "self", ",", "data", ",", "type", "=", "None", ",", "id", "=", "None", ",", "retry", "=", "None", ",", "channel", "=", "'sse'", ")", ":", "message", "=", "Message", "(", "data", ",", "type", "=", "type", ",", "id", "=", "...
50.157895
0.00206
def _trim(cls, s): """ Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colons removed :rtype: string TEST: trailing colons necessary >>> s = '1:2::::' >>> CPE._trim(s)...
[ "def", "_trim", "(", "cls", ",", "s", ")", ":", "reverse", "=", "s", "[", ":", ":", "-", "1", "]", "idx", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "reverse", ")", ")", ":", "if", "reverse", "[", "i", "]", "==", "\":...
25.1875
0.002389
def get_parser(segmenter, **options): """Gets a parser. Args: segmenter (str): Segmenter to use. options (:obj:`dict`, optional): Optional settings. Returns: Parser (:obj:`budou.parser.Parser`) Raises: ValueError: If unsupported segmenter is specified. """ if segmenter == 'nlapi': ret...
[ "def", "get_parser", "(", "segmenter", ",", "*", "*", "options", ")", ":", "if", "segmenter", "==", "'nlapi'", ":", "return", "NLAPIParser", "(", "*", "*", "options", ")", "elif", "segmenter", "==", "'mecab'", ":", "return", "MecabParser", "(", ")", "eli...
25.285714
0.010889
def merge(self, from_email, source_incidents): """Merge other incidents into this incident.""" if from_email is None or not isinstance(from_email, six.string_types): raise MissingFromEmail(from_email) add_headers = {'from': from_email, } endpoint = '/'.join((self.endpoint, s...
[ "def", "merge", "(", "self", ",", "from_email", ",", "source_incidents", ")", ":", "if", "from_email", "is", "None", "or", "not", "isinstance", "(", "from_email", ",", "six", ".", "string_types", ")", ":", "raise", "MissingFromEmail", "(", "from_email", ")",...
41.9
0.002334
def getattrs(value, attrs, default=_no_default): """ Perform a chained application of ``getattr`` on ``value`` with the values in ``attrs``. If ``default`` is supplied, return it if any of the attribute lookups fail. Parameters ---------- value : object Root of the lookup chain. ...
[ "def", "getattrs", "(", "value", ",", "attrs", ",", "default", "=", "_no_default", ")", ":", "try", ":", "for", "attr", "in", "attrs", ":", "value", "=", "getattr", "(", "value", ",", "attr", ")", "except", "AttributeError", ":", "if", "default", "is",...
24.145833
0.000829
def line_intersects_itself(lons, lats, closed_shape=False): """ Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not ...
[ "def", "line_intersects_itself", "(", "lons", ",", "lats", ",", "closed_shape", "=", "False", ")", ":", "assert", "len", "(", "lons", ")", "==", "len", "(", "lats", ")", "if", "len", "(", "lons", ")", "<=", "3", ":", "# line can not intersect itself unless...
36.243243
0.000726
def load_catalog(filename): """ Load a catalogue and extract the source positions (only) Parameters ---------- filename : str Filename to read. Supported types are csv, tab, tex, vo, vot, and xml. Returns ------- catalogue : list A list of [ (ra, dec), ...] """ ...
[ "def", "load_catalog", "(", "filename", ")", ":", "supported", "=", "get_table_formats", "(", ")", "fmt", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "-", "1", "]", "[", "1", ":", "]", ".", "lower", "(", ")", "# extension sans...
33.425
0.00218
def ls(): """List all items in the database in a predefined format.""" if not os.path.exists(ARGS.database): exit('Error: The database does not exist; you must create it first.') with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.curs...
[ "def", "ls", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "ARGS", ".", "database", ")", ":", "exit", "(", "'Error: The database does not exist; you must create it first.'", ")", "with", "sqlite3", ".", "connect", "(", "ARGS", ".", "data...
42.0625
0.000726
def compare_registries(fs0, fs1, concurrent=False): """Compares the Windows Registry contained within the two File Systems. If the concurrent flag is True, two processes will be used speeding up the comparison on multiple CPUs. Returns a dictionary. {'created_keys': {'\\Reg\\Key': (('Key', 'T...
[ "def", "compare_registries", "(", "fs0", ",", "fs1", ",", "concurrent", "=", "False", ")", ":", "hives", "=", "compare_hives", "(", "fs0", ",", "fs1", ")", "if", "concurrent", ":", "future0", "=", "concurrent_parse_registries", "(", "fs0", ",", "hives", ")...
36.285714
0.000959
def toggleCollapseBefore( self ): """ Collapses the splitter before this handle. """ if ( self.isCollapsed() ): self.uncollapse() else: self.collapse( XSplitterHandle.CollapseDirection.Before )
[ "def", "toggleCollapseBefore", "(", "self", ")", ":", "if", "(", "self", ".", "isCollapsed", "(", ")", ")", ":", "self", ".", "uncollapse", "(", ")", "else", ":", "self", ".", "collapse", "(", "XSplitterHandle", ".", "CollapseDirection", ".", "Before", "...
31.25
0.031128
def map_metabolites_to_structures(metabolites, compartments): """ Map metabolites from the identifier namespace to structural space. Metabolites who lack structural annotation (InChI or InChIKey) are ignored. Parameters ---------- metabolites : iterable The cobra.Metabolites to map. ...
[ "def", "map_metabolites_to_structures", "(", "metabolites", ",", "compartments", ")", ":", "# TODO (Moritz Beber): Consider SMILES?", "unique_identifiers", "=", "[", "\"inchikey\"", ",", "\"inchi\"", "]", "met2mol", "=", "{", "}", "molecules", "=", "{", "c", ":", "[...
34.591837
0.001147
def get_redirect_url(request): """Redirects to referring page, or CAS_REDIRECT_URL if no referrer is set. """ next_ = request.GET.get(REDIRECT_FIELD_NAME) if not next_: redirect_url = resolve_url(django_settings.CAS_REDIRECT_URL) if django_settings.CAS_IGNORE_REFERER: ne...
[ "def", "get_redirect_url", "(", "request", ")", ":", "next_", "=", "request", ".", "GET", ".", "get", "(", "REDIRECT_FIELD_NAME", ")", "if", "not", "next_", ":", "redirect_url", "=", "resolve_url", "(", "django_settings", ".", "CAS_REDIRECT_URL", ")", "if", ...
34.5
0.001567
def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try...
[ "def", "option_in_select", "(", "browser", ",", "select_name", ",", "option", ")", ":", "select", "=", "find_field", "(", "browser", ",", "'select'", ",", "select_name", ")", "assert", "select", "try", ":", "return", "select", ".", "find_element_by_xpath", "("...
30.0625
0.002016
def _get_default_projection(cls): """Construct the default projection document.""" projected = [] # The fields explicitly requested for inclusion. neutral = [] # Fields returning neutral (None) status. omitted = False # Have any fields been explicitly omitted? for name, field in cls.__fields__.items(...
[ "def", "_get_default_projection", "(", "cls", ")", ":", "projected", "=", "[", "]", "# The fields explicitly requested for inclusion.", "neutral", "=", "[", "]", "# Fields returning neutral (None) status.", "omitted", "=", "False", "# Have any fields been explicitly omitted?", ...
28.541667
0.042373
def __get_resource(dao, url): """ Issue a GET request to IASystem with the given url and return a response in Collection+json format. :returns: http response with content in json """ headers = {"Accept": "application/vnd.collection+json"} response = dao.getURL(url, headers) status = resp...
[ "def", "__get_resource", "(", "dao", ",", "url", ")", ":", "headers", "=", "{", "\"Accept\"", ":", "\"application/vnd.collection+json\"", "}", "response", "=", "dao", ".", "getURL", "(", "url", ",", "headers", ")", "status", "=", "response", ".", "status", ...
30.72
0.001263
def _get_lrs(self, indices): """Gets the learning rates given the indices of the weights. Parameters ---------- indices : list of int Indices corresponding to weights. Returns ------- lrs : list of float Learning rates for those indices. ...
[ "def", "_get_lrs", "(", "self", ",", "indices", ")", ":", "if", "self", ".", "lr_scheduler", "is", "not", "None", ":", "lr", "=", "self", ".", "lr_scheduler", "(", "self", ".", "num_update", ")", "else", ":", "lr", "=", "self", ".", "lr", "lrs", "=...
30.851852
0.002328
def get_healthcheck(self, service_id, version_number, name): """Get the healthcheck for a particular service and version.""" content = self._fetch("/service/%s/version/%d/healthcheck/%s" % (service_id, version_number, name)) return FastlyHealthCheck(self, content)
[ "def", "get_healthcheck", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/healthcheck/%s\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")", ")",...
66.75
0.022222
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', ...
[ "def", "subscribe", "(", "self", ",", "user_token", ",", "topic", ")", ":", "response", "=", "_request", "(", "'POST'", ",", "url", "=", "self", ".", "url_v1", "(", "'/user/subscriptions/'", "+", "topic", ")", ",", "user_agent", "=", "self", ".", "user_a...
34.357143
0.012146
def _initialize_operations(self): """Initializer for _operations. Raises: TypeError: _graph is not a tf.Graph or mtf.Graph. Returns: a list of (tf.Operation or mtf.Operation) """ if isinstance(self._graph, tf.Graph): return self._graph.get_operations() elif isinstance(self._g...
[ "def", "_initialize_operations", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_graph", ",", "tf", ".", "Graph", ")", ":", "return", "self", ".", "_graph", ".", "get_operations", "(", ")", "elif", "isinstance", "(", "self", ".", "_graph",...
30.0625
0.008065
def parse_args(*args): """ Parse the arguments for the command """ parser = argparse.ArgumentParser( description="Send push notifications for a feed") parser.add_argument('--version', action='version', version="%(prog)s " + __version__.__version__) parser.add_argument('...
[ "def", "parse_args", "(", "*", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Send push notifications for a feed\"", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "v...
51.260274
0.00236
def get_form_class(self): """ Returns the form class to use in this view. Makes sure that the form_field_callback is set to use the `formfield_for_dbfield` method and that any custom form classes are prepared by the `customize_form_widgets` method. """ if ...
[ "def", "get_form_class", "(", "self", ")", ":", "if", "self", ".", "fieldsets", ":", "fields", "=", "flatten_fieldsets", "(", "self", ".", "get_fieldsets", "(", ")", ")", "else", ":", "if", "(", "self", ".", "form_class", "and", "getattr", "(", "self", ...
36.942029
0.000764
def _download_initial_config(self): """Loads the initial config.""" _initial_config = self._download_running_config() # this is a bit slow! self._last_working_config = _initial_config self._config_history.append(_initial_config) self._config_history.append(_initial_config)
[ "def", "_download_initial_config", "(", "self", ")", ":", "_initial_config", "=", "self", ".", "_download_running_config", "(", ")", "# this is a bit slow!", "self", ".", "_last_working_config", "=", "_initial_config", "self", ".", "_config_history", ".", "append", "(...
51.5
0.009554