code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.launch_thread(service.name, self.check_loop, service)
def on_service_add(self, service)
When a new service is added, a worker thread is launched to periodically run the checks for that service.
17.883516
9.594398
1.863954
logger.info("Starting check loop for service '%s'", service.name) def handle_checks_result(f): try: came_up, went_down = f.result() except Exception: logger.exception("Error checking service '%s'", service.name) return ...
def check_loop(self, service)
While the reporter is not shutting down and the service being checked is present in the reporter's configuration, this method will launch a job to run all of the service's checks and then pause for the configured interval.
3.157723
3.049707
1.035418
logger.debug("Running checks. (%s)", service.name) if service.discovery not in self.configurables[Discovery]: logger.warn( "Service %s is using Unknown/unavailable discovery '%s'.", service.name, service.discovery ) return set...
def run_checks(self, service)
Runs each check for the service and reports to the service's discovery method based on the results. If all checks pass and the service's present node was previously reported as down, the present node is reported as up. Conversely, if any of the checks fail and the service's present nod...
6.84191
6.532867
1.047306
# Developer API keys, auth tokens, and other standard, required args. data.update({ "key": self.api_key, # No API methods currently use this, but we're ready for it, # should that change. "token": self.api_auth_token, }) # Ends u...
def _do_api_call(self, method, data)
Convenience method to carry out a standard API call against the Petfinder API. :param basestring method: The API method name to call. :param dict data: Key/value parameters to send to the API method. This varies based on the method. :raises: A number of :py:exc:`petfinder.ex...
6.358608
5.955751
1.067642
# Used to determine whether to fail noisily if no results are returned. has_records = {"has_records": False} while True: try: root = self._do_api_call(method, kwargs) except RecordDoesNotExistError: if not has_records["has_records...
def _do_autopaginating_api_call(self, method, kwargs, parser_func)
Given an API method, the arguments passed to it, and a function to hand parsing off to, loop through the record sets in the API call until all records have been yielded. This is mostly done this way to reduce duplication through the various API methods. :param basestring method...
9.159184
9.57048
0.957025
return datetime.datetime.strptime( dtime_str, "%Y-%m-%dT%H:%M:%SZ" ).replace(tzinfo=pytz.utc)
def _parse_datetime_str(self, dtime_str)
Given a standard datetime string (as seen throughout the Petfinder API), spit out the corresponding UTC datetime instance. :param str dtime_str: The datetime string to parse. :rtype: datetime.datetime :returns: The parsed datetime.
2.741076
2.882666
0.950883
record = { "breeds": [], "photos": [], "options": [], "contact": {}, } # These fields can just have their keys and text values copied # straight over to the dict record. straight_copy_fields = [ "id", "shelterI...
def _parse_pet_record(self, root)
Given a <pet> Element from a pet.get or pet.getRandom response, pluck out the pet record. :param lxml.etree._Element root: A <pet> tag Element. :rtype: dict :returns: An assembled pet record.
4.180086
4.244826
0.984748
root = self._do_api_call("breed.list", kwargs) breeds = [] for breed in root.find("breeds"): breeds.append(breed.text) return breeds
def breed_list(self, **kwargs)
breed.list wrapper. Returns a list of breed name strings. :rtype: list :returns: A list of breed names.
3.627087
3.241428
1.118978
root = self._do_api_call("pet.get", kwargs) return self._parse_pet_record(root.find("pet"))
def pet_get(self, **kwargs)
pet.get wrapper. Returns a record dict for the requested pet. :rtype: dict :returns: The pet's record dict.
6.789951
7.762208
0.874745
root = self._do_api_call("pet.getRandom", kwargs) output_brevity = kwargs.get("output", "id") if output_brevity == "id": return root.find("petIds/id").text else: return self._parse_pet_record(root.find("pet"))
def pet_getrandom(self, **kwargs)
pet.getRandom wrapper. Returns a record dict or Petfinder ID for a random pet. :rtype: dict or str :returns: A dict of pet data if ``output`` is ``'basic'`` or ``'full'``, and a string if ``output`` is ``'id'``.
8.134354
5.653129
1.438912
def pet_find_parser(root, has_records): for pet in root.findall("pets/pet"): # This is changed in the original record, since it's passed # by reference. has_records["has_records"] = True yield self._parse_pet_reco...
def pet_find(self, **kwargs)
pet.find wrapper. Returns a generator of pet record dicts matching your search criteria. :rtype: generator :returns: A generator of pet record dicts. :raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have reached the maximum number of records your credentials ...
7.847006
8.040074
0.975987
def shelter_find_parser(root, has_records): for shelter in root.find("shelters"): has_records["has_records"] = True record = {} for field in shelter: record[field.tag] = field.text yield record...
def shelter_find(self, **kwargs)
shelter.find wrapper. Returns a generator of shelter record dicts matching your search criteria. :rtype: generator :returns: A generator of shelter record dicts. :raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have reached the maximum number of records your cr...
4.84959
4.710674
1.02949
root = self._do_api_call("shelter.get", kwargs) shelter = root.find("shelter") for field in shelter: record = {} for field in shelter: record[field.tag] = field.text return record
def shelter_get(self, **kwargs)
shelter.get wrapper. Given a shelter ID, retrieve its details in dict form. :rtype: dict :returns: The shelter's details.
4.137618
4.07298
1.01587
def shelter_getpets_parser_ids(root, has_records): pet_ids = root.findall("petIds/id") for pet_id in pet_ids: yield pet_id.text def shelter_getpets_parser_records(root, has_records): for pet in root.findall("pets/pe...
def shelter_getpets(self, **kwargs)
shelter.getPets wrapper. Given a shelter ID, retrieve either a list of pet IDs (if ``output`` is ``'id'``), or a generator of pet record dicts (if ``output`` is ``'full'`` or ``'basic'``). :rtype: generator :returns: Either a generator of pet ID strings or pet record dicts, ...
3.14091
2.742198
1.145399
root = self._do_api_call("shelter.listByBreed", kwargs) shelter_ids = root.findall("shelterIds/id") for shelter_id in shelter_ids: yield shelter_id.text
def shelter_listbybreed(self, **kwargs)
shelter.listByBreed wrapper. Given a breed and an animal type, list the shelter IDs with pets of said breed. :rtype: generator :returns: A generator of shelter IDs that have breed matches.
3.380706
3.203372
1.055358
'''Add a callback to this node. Callbacks are called when the specified event occurs. The available events depends on the specific node type. Args should be a value to pass to the callback when it is called. The callback should be of the format: def callback(node, value...
def add_callback(self, event, cb, args=None)
Add a callback to this node. Callbacks are called when the specified event occurs. The available events depends on the specific node type. Args should be a value to pass to the callback when it is called. The callback should be of the format: def callback(node, value, cb_args):...
6.136438
1.749888
3.50676
'''Get a child node of this node, or this node, based on a path. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return The node p...
def get_node(self, path)
Get a child node of this node, or this node, based on a path. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return The node pointed to b...
3.066597
1.315391
2.331319
'''Check if a path exists below this node. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return True if the path points to a nod...
def has_path(self, path)
Check if a path exists below this node. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return True if the path points to a node in the tr...
3.132201
1.286236
2.435168
'''Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value ...
def iterate(self, func, args=None, filter=[])
Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref arg...
3.494098
1.271566
2.74787
'''Remove a callback from this node. The callback is removed from the specified event. @param cb The callback function to remove. ''' if event not in self._cbs: raise exceptions.NoSuchEventError(self.name, event) c = [(x[0], x[1]) for x in self._cbs[event]]...
def rem_callback(self, event, cb)
Remove a callback from this node. The callback is removed from the specified event. @param cb The callback function to remove.
3.821441
3.065655
1.246533
'''The full path of this node.''' with self._mutex: if self._parent: return self._parent.full_path + [self._name] else: return [self._name]
def full_path(self)
The full path of this node.
3.716002
3.461085
1.073652
'''The full path of this node as a string.''' with self._mutex: if self._parent: if self._parent._name == '/': return self._parent.full_path_str + self._name else: return self._parent.full_path_str + '/' + self._name ...
def full_path_str(self)
The full path of this node as a string.
3.012367
2.764001
1.089857
'''The name server of the node (i.e. its top-most parent below /).''' with self._mutex: if not self._parent: # The root node does not have a name server return None elif self._parent.name == '/': return self else: ...
def nameserver(self)
The name server of the node (i.e. its top-most parent below /).
5.946942
3.332984
1.78427
'''The ORB used to access this object. This property's value will be None if no object above this object is a name server. ''' with self._mutex: if self._parent.name == '/': return None return self._parent.orb
def orb(self)
The ORB used to access this object. This property's value will be None if no object above this object is a name server.
11.760714
3.767123
3.121935
'''The root node of the tree this node is in.''' with self._mutex: if self._parent: return self._parent.root else: return self
def root(self)
The root node of the tree this node is in.
5.447094
4.124724
1.320596
args = parser.parse_args(args[1:]) query.files.delete_priority_rule(state.db, args.id) del state.file_picker
def command(state, args)
Delete priority rule.
12.632776
7.717827
1.636831
with db: cur = db.cursor() cur.execute( 'UPDATE {} SET {} WHERE {}'.format( table, ','.join(_sqlpformat(col) for col in update_dict.keys()), ' AND '.join(_sqlpformat(col) for col in key_cols), ), update_dict, ...
def upsert(db, table, key_cols, update_dict)
Fabled upsert for SQLiteDB. Perform an upsert based on primary key. :param SQLiteDB db: database :param str table: table to upsert into :param str key_cols: name of key columns :param dict update_dict: key-value pairs to upsert
2.44754
2.87408
0.851591
if len(args) < 2: print(f'Usage: {args[0]} {{ID|aid:AID}}') return aid = state.results.parse_aid(args[1], default_key='anidb') anime = request_anime(aid) query.update.add(state.db, anime)
def command(state, args)
Add an anime from an AniDB search.
8.244963
6.991624
1.179263
return self.bg.Omega_lambda(z) + self.bg.Omega_fld(z)
def Ode(self, z)
Returns the sum of :func:`~classylss.binding.Background.Omega_lambda` and :func:`~classylss.binding.Background.Omega_fld`.
11.404132
3.244506
3.514905
return self.bg.Omega_ncdm(z) + self.bg.Omega_ur(z)
def Onu(self, z)
Returns the sum of :func:`~classylss.binding.Background.Omega_ncdm` and :func:`~classylss.binding.Background.Omega_ur`.
15.983313
2.862867
5.582975
host = socket.getfqdn() return cls( host=host, ip=socket.gethostbyname(host), port=port, metadata=service.metadata )
def current(cls, service, port)
Returns a Node instance representing the current service node. Collects the host and IP information for the current machine and the port information from the given service.
3.805348
3.904427
0.974624
return json.dumps({ "port": self.port, "ip": self.ip, "host": self.host, "peer": self.peer.serialize() if self.peer else None, "metadata": json.dumps(self.metadata or {}, sort_keys=True), }, sort_keys=True)
def serialize(self)
Serializes the node data as a JSON map string.
3.080426
2.872962
1.072212
if getattr(value, "decode", None): value = value.decode() logger.debug("Deserializing node data: '%s'", value) parsed = json.loads(value) if "port" not in parsed: raise ValueError("No port defined for node.") if "ip" not in parsed: r...
def deserialize(cls, value)
Creates a new Node instance via a JSON map string. Note that `port` and `ip` and are required keys for the JSON map, `peer` and `host` are optional. If `peer` is not present, the new Node instance will use the current peer. If `host` is not present, the hostname of the given `ip` is l...
3.050558
2.587455
1.17898
for config_class in self.watched_configurables: monitor = ConfigFileMonitor(config_class, self.config_dir) self.observers.append( monitor.start( self.add_configurable, self.update_configurable, self.remo...
def start(self)
Iterates over the `watched_configurabes` attribute and starts a config file monitor for each. The resulting observer threads are kept in an `observers` list attribute.
6.030729
3.796948
1.58831
logger.debug( "Launching thread '%s': %s(%s, %s)", name, fn, args, kwargs ) self.thread_pool[name] = threading.Thread( target=fn, args=args, kwargs=kwargs ) self.thread_pool[name].daemon = True self.thread_pool[name].start()
def launch_thread(self, name, fn, *args, **kwargs)
Adds a named thread to the "thread pool" dictionary of Thread objects. A daemon thread that executes the passed-in function `fn` with the given args and keyword args is started and tracked in the `thread_pool` attribute with the given `name` as the key.
2.151799
2.089876
1.02963
if name not in self.thread_pool: return self.thread_pool[name].join() del self.thread_pool[name]
def kill_thread(self, name)
Joins the thread in the `thread_pool` dict with the given `name` key.
2.712243
2.161491
1.254802
configurable_class_name = configurable_class.__name__.lower() logger.info( "updating %s: '%s'", configurable_class_name, name ) registry = self.registry_for(configurable_class) if name not in registry: logger.warn( "Tried to upd...
def update_configurable(self, configurable_class, name, config)
Callback fired when a configurable instance is updated. Looks up the existing configurable in the proper "registry" and `apply_config()` is called on it. If a method named "on_<configurable classname>_update" is defined it is called in the work pool and passed the configurable's name, ...
2.982624
2.953473
1.00987
configurable_class_name = configurable_class.__name__.lower() logger.info("Removing %s: '%s'", configurable_class_name, name) registry = self.registry_for(configurable_class) if name not in registry: logger.warn( "Tried to remove unknown active %s:...
def remove_configurable(self, configurable_class, name)
Callback fired when a configurable instance is removed. Looks up the existing configurable in the proper "registry" and removes it. If a method named "on_<configurable classname>_remove" is defined it is called via the work pooland passed the configurable's name. If the remove...
3.094924
3.146701
0.983546
configurable_class_name = configurable_class.__name__.lower() return getattr( self, "on_" + configurable_class_name + "_" + action, None )
def hook_for(self, configurable_class, action)
Helper method for determining if an on_<configurable class>_<action> method is present, to be used as a hook in the add/update/remove configurable methods.
3.474445
3.059225
1.135727
self.shutdown.set() for monitor in self.observers: monitor.stop() self.wind_down() for monitor in self.observers: monitor.join() for thread in self.thread_pool.values(): thread.join() self.work_pool.shutdown()
def stop(self)
Method for shutting down the watcher. All config file observers are stopped and their threads joined, along with the worker thread pool.
4.584139
4.162812
1.101212
if self._subresource_map: self.set_subresources(**kwargs) for key in self._subresource_map.keys(): # Don't let these attributes be overridden later kwargs.pop(key, None) for field, value in kwargs.items(): if field in self.Meta...
def set_attributes(self, **kwargs)
Set the resource attributes from the kwargs. Only sets items in the `self.Meta.attributes` white list. Subclass this method to customise attributes. Args: kwargs: Keyword arguements passed into the init of this class
4.381009
4.551409
0.962561
if resource.Meta.resource_name: url = '{}/{}'.format(base_url, resource.Meta.resource_name) else: p = inflect.engine() plural_name = p.plural(resource.Meta.name.lower()) url = '{}/{}'.format(base_url, plural_name) return cls._parse_url_and...
def get_resource_url(cls, resource, base_url)
Construct the URL for talking to this resource. i.e.: http://myapi.com/api/resource Note that this is NOT the method for calling individual instances i.e. http://myapi.com/api/resource/1 Args: resource: The resource class instance base_url: The Base U...
3.157692
3.589922
0.879599
if uid: url = '{}/{}'.format(url, uid) else: url = url return cls._parse_url_and_validate(url)
def get_url(cls, url, uid, **kwargs)
Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additional keyword argueents returns: final_url: The URL f...
4.362803
5.651897
0.771918
return '{}_{}'.format(method_type.lower(), resource.Meta.name.lower())
def get_method_name(resource, method_type)
Generate a method name for this resource based on the method type.
7.624622
5.516559
1.382134
parsed_url = urlparse(url) if parsed_url.scheme and parsed_url.netloc: final_url = parsed_url.geturl() else: raise BadURLException return final_url
def _parse_url_and_validate(cls, url)
Recieves a URL string and validates it using urlparse. Args: url: A URL string Returns: parsed_url: A validated URL Raises: BadURLException
2.97156
2.938152
1.01137
method_name = self.get_method_name(resource, 'get') def get(self, **kwargs): return self._call_api_single_related_resource( resource, full_resource_url, method_name, **kwargs ) def get_list(self, **kwargs): return self._call_api_many...
def set_related_method(self, resource, full_resource_url)
Using reflection, generate the related method and return it.
2.098974
2.037864
1.029988
valid_values = {} for resource in self.Meta.related_resources: for k, v in url_values.items(): resource_url = resource.get_resource_url( resource, resource.Meta.base_url) if isinstance(v, list): if all([resource...
def match_urls_to_resources(self, url_values)
For the list of valid URLs, try and match them up to resources in the related_resources attribute. Args: url_values: A dictionary of keys and URL strings that could be related resources. Returns: valid_values: The values that are valid
3.044018
2.866582
1.061898
if not self.Meta.related_resources: # Just do what the normal BaseResource does super(HypermediaResource, self).set_attributes(**kwargs) return # Extract all the values that are URLs url_values = {} for k, v in kwargs.items(): try...
def set_attributes(self, **kwargs)
Similar to BaseResource.set_attributes except it will attempt to match URL strings with registered related resources, and build their get_* method and attach it to this resource.
4.164268
3.706697
1.123444
for field, value in kwargs.items(): if field in self.Meta.attributes: setattr(self, field, value)
def set_attributes(self, **kwargs)
Set the resource attributes from the kwargs. Only sets items in the `self.Meta.attributes` white list. Args: kwargs: Keyword arguements passed into the init of this class
3.516534
3.315668
1.060581
aid = anime.aid values = { 'aid': aid, 'title': anime.title, 'type': anime.type, 'episodecount': anime.episodecount, } if anime.startdate is not None: values['startdate'] = datets.to_ts(anime.startdate) if anime.enddate is not None: values['enddat...
def add(db, anime)
Add an anime (or update existing). anime is an AnimeTree instance.
2.896334
2.911438
0.994812
values = { 'aid': aid, 'type': episode.type, 'number': episode.number, 'title': episode.title, 'length': episode.length, } upsert(db, 'episode', ['aid', 'type', 'number'], values)
def add_episode(db, aid, episode)
Add an episode.
2.74694
2.682309
1.024095
db.cursor().execute( 'DELETE FROM episode WHERE aid=:aid AND type=:type AND number=:number', { 'aid': aid, 'type': episode.type, 'number': episode.number, })
def delete_episode(db, aid, episode)
Delete an episode.
2.716038
2.656264
1.022503
db.cursor().execute( , { 'aid': aid, 'type': ep_type, 'number': number, 'watched': 1, })
def set_watched(db, aid, ep_type, number)
Set episode as watched.
3.755948
3.634992
1.033276
anime = lookup(db, aid) if anime.complete: return episode = anime.watched_episodes + 1 with db: set_watched(db, aid, get_eptype(db, 'regular').id, episode) set_status( db, aid, anime.enddate and episode >= anime.episodecount, episode)
def bump(db, aid)
Bump anime regular episode count.
8.023639
6.663606
1.204099
params = { 'aid': aid, 'type': get_eptype(db, 'regular').id, 'watched': 1, 'number': episode, } with db: cur = db.cursor() cur.execute( , params) params['watched'] = 0 cur.execute( , params) ...
def reset(db, aid, episode)
Reset episode count for anime.
5.667524
5.575932
1.016426
idfs = parallel(count_idf, tokens_stream, n_jobs=-1) N = len(idfs) # n docs idf = merge(idfs) for k, v in idf.items(): idf[k] = math.log(N/v) # v ~= N/(math.e ** idf[k]) # Keep track of N to update IDFs idf['_n_docs'] = N if out is not None: with open(out, 'w'...
def train_idf(tokens_stream, out=None, **kwargs)
Train a IDF model on a list of files (parallelized).
4.206697
4.104735
1.02484
if self.api_token: # verify current API token check_auth_uri = self.uri.split('/api/v1')[0] + '/check_token' req = self.request(check_auth_uri) try: ping = req.get().json() except Exception as exc: if str(exc).s...
def __authenticate(self)
Sends a json payload with the email and password in order to get the authentication api_token to be used with the rest of the requests
3.622112
3.563379
1.016482
account_uri = self.uri.split('/api/v1')[0] + '/account' req = self.request(account_uri) account_info = req.get() user_data = HTMLParser(account_info.content) return user_data
def user_info(self)
General user info information as returned in /account in our API
5.78317
5.095102
1.135045
req = self.request(self.uri + '/providers', api_version=2) providers = req.get().json() supported_providers = providers['supported_providers'] return supported_providers
def supported_providers(self)
Request a list of all available providers :returns: A list of all available providers (e.g. {'provider': 'ec2_ap_northeast', 'title': 'EC2 AP NORTHEAST'})
6.307559
6.108217
1.032635
req = self.request(self.uri + '/clouds') clouds = req.get().json() if clouds: for cloud in clouds: self._clouds[cloud['id']] = Cloud(cloud, self) else: self._clouds = {}
def _list_clouds(self)
Request a list of all added clouds. Populates self._clouds dict with mist.client.model.Cloud instances
3.592475
3.096249
1.160267
if self._clouds is None: self._clouds = {} self._list_clouds() if id: return [self._clouds[cloud_id] for cloud_id in self._clouds.keys() if id == self._clouds[cloud_id].id] elif name: return [self._clouds[cloud_id] for...
def clouds(self, id=None, name=None, provider=None, search=None)
Property-like function to call the _list_clouds function in order to populate self._clouds dict :returns: A list of Cloud instances.
1.473757
1.453806
1.013723
req = self.request(self.uri + '/keys') keys = req.get().json() if keys: self._keys = {} for key in keys: self._keys[key['id']] = Key(key, self) else: self._keys = {}
def _list_keys(self)
Retrieves a list of all added Keys and populates the self._keys dict with Key instances :returns: A list of Keys instances
3.397937
3.39537
1.000756
if self._keys is None: self._keys = {} self._list_keys() if id: return [self._keys[key_id] for key_id in self._keys.keys() if id == self._keys[key_id].id] elif search: return [self._keys[key_id] for key_id in self._key...
def keys(self, id=None, search=None)
Property-like function to call the _list_keys function in order to populate self._keys dict :returns: A list of Key instances
1.814925
1.706325
1.063646
req = self.request(self.uri + "/keys") private_key = req.post().json() return private_key['priv']
def generate_key(self)
Ask mist.io to randomly generate a private ssh-key to be used with the creation of a new Key :returns: A string of a randomly generated ssh private key
9.44401
8.953648
1.054767
payload = { 'name': key_name, 'priv': private } data = json.dumps(payload) req = self.request(self.uri + '/keys', data=data) response = req.put().json() self.update_keys() return response
def add_key(self, key_name, private)
Add a new key to mist.io :param key_name: Name of the new key (it will be used as the key's id as well). :param private: Private ssh-key in string format (see also generate_key() ). :returns: An updated list of added keys.
4.556722
5.40263
0.843427
args = parser.parse_args(args[1:]) row_id = query.files.add_priority_rule(state.db, args.regexp, args.priority) del state.file_picker print('Added rule {}'.format(row_id))
def command(state, args)
Add a priority rule for files.
9.544711
5.949882
1.604185
anime_info = alib.request_anime(_CLIENT, aid) return Anime._make(anime_info)
def request_anime(aid: int) -> 'Anime'
Make an anime API request.
13.710291
11.143814
1.230305
match = self._NUMBER_SUFFIX.search(self.epno) return int(match.group(1))
def number(self) -> int
Episode number. Unique for an anime and episode type, but not unique across episode types for the same anime.
15.049546
11.782796
1.277247
for title in self.titles: if title.lang == 'ja': return title.title # In case there's no Japanese title. return self.titles[0].title
def title(self) -> str
Episode title.
5.495946
3.803953
1.444799
titles: 'Titles' for titles in self._titles_list: title: 'AnimeTitle' for title in titles.titles: if query.search(title.title): yield WorkTitles( aid=titles.aid, main_title=_get_main_titl...
def search(self, query: 're.Pattern') -> 'Iterable[_WorkTitles]'
Search titles using a compiled RE query.
4.105193
4.373884
0.938569
# type: () -> List[Package] return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set, key=lambda x: str(x).lower())]
def _get_packages()
Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list
5.013335
6.240042
0.803414
# type: (str) -> List[str] whitelist_licenses = [] try: print('config path', config_path) with open(config_path) as config: whitelist_licenses = [line.rstrip() for line in config] except IOError: # pragma: no cover print('Warning: No {} file was found.'.format...
def _get_whitelist_licenses(config_path)
Get whitelist license names from config file. :param config_path: str :return: list
3.630805
4.537755
0.800133
# type: (str) -> None whitelist_licenses = _get_whitelist_licenses(config_path) table = PrintTable(ROW_HEADERS) warnings = [] for pkg in _get_packages(): allowed = pkg.license in whitelist_licenses table.add_row((pkg.name, pkg.version, pkg.license, str(allowed))) if n...
def run_license_checker(config_path)
Generate table of installed packages and check for license warnings based off user defined restricted license values. :param config_path: str :return:
4.360303
4.62509
0.94275
r for arg in args: self._includefields.append(arg) return self
def include_fields(self, *args)
r""" Include fields is the fields that you want to be returned when searching. These are in addition to the fields that are always included below. :param args: items passed in will be turned into a list :returns: :class:`Search` >>> bugzilla.sear...
8.823112
10.043653
0.878476
r for component in components: self._component.append(component) return self
def component(self, *components)
r""" When search() is called it will limit results to items in a component. :param component: items passed in will be turned into a list :returns: :class:`Search`
11.710054
13.832018
0.84659
r for product in products: self._product.append(product) return self
def product(self, *products)
r""" When search is called, it will limit the results to items in a Product. :param product: items passed in will be turned into a list :returns: :class:`Search`
10.822777
10.883819
0.994392
r if start: self._time_frame['chfieldfrom'] = start if end: self._time_frame['chfieldto'] = end return self
def timeframe(self, start, end)
r""" When you want to search bugs for a certain time frame. :param start: :param end: :returns: :class:`Search`
7.736043
7.734725
1.00017
r if not isinstance(fields, list): raise Exception('fields should be a list') self._change_history['fields'] = fields if value: self._change_history['value'] = value return self
def change_history_fields(self, fields, value=None)
r"""
3.680524
3.950319
0.931703
r params = {} params.update(self._time_frame.items()) if self._includefields: params['include_fields'] = list(self._includefields) if self._bug_numbers: bugs = [] for bug in self._bug_numbers: result = self._bugsy.request('bug/...
def search(self)
r""" Call the Bugzilla endpoint that will do the search. It will take the information used in other methods on the Search object and build up the query string. If no bugs are found then an empty list is returned. >>> bugs = bugzilla.search_for\ .....
2.844174
2.721128
1.045219
return datetime.datetime.strptime(string, '%Y-%m-%d').date()
def _parse_date(string: str) -> datetime.date
Parse an ISO format date (YYYY-mm-dd). >>> _parse_date('1990-01-02') datetime.date(1990, 1, 2)
3.901812
4.492661
0.868486
assert "local_wp_dir" in env, "Missing local_wp_dir in env" if force != "yes": message = "This will replace your local database with your "\ "remote, are you sure [y/n]" answer = prompt(message, "y") if answer != "y": logger.info("Sync stopped") ...
def sync_remote_to_local(force="no")
Replace your remote db with your local Example: sync_remote_to_local:force=yes
4.423147
4.406089
1.003871
cur = db.cursor() cur.execute('SELECT id, regexp, priority FROM file_priority') for row in cur: yield PriorityRule(*row)
def get_priority_rules(db) -> Iterable[PriorityRule]
Get file priority rules.
4.870672
3.573406
1.363034
with db: cur = db.cursor() if priority is None: cur.execute('SELECT MAX(priority) FROM file_priority') highest_priority = cur.fetchone()[0] if highest_priority is None: priority = 1 else: priority = highest_priority...
def add_priority_rule( db, regexp: str, priority: Optional[int] = None, ) -> int
Add a file priority rule.
2.787715
2.398584
1.162234
with db: cur = db.cursor() cur.execute('DELETE FROM file_priority WHERE id=?', (rule_id,))
def delete_priority_rule(db, rule_id: int) -> None
Delete a file priority rule.
5.273096
2.997376
1.759237
with db: cache_status(db, aid) db.cursor().execute( , (anime_files.to_json(), aid))
def cache_files(db, aid: int, anime_files: AnimeFiles) -> None
Cache files for anime.
11.644906
9.766185
1.19237
with conn: cur = conn.cursor().execute( 'SELECT anime_files FROM cache_anime WHERE aid=?', (aid,)) row = cur.fetchone() if row is None: raise ValueError('No cached files') return AnimeFiles.from_json(row[0])
def get_files(conn, aid: int) -> AnimeFiles
Get cached files for anime.
3.373676
3.041557
1.109194
basename = os.path.basename(filename) match = self.regexp.search(basename) if match: self.by_episode[int(match.group('ep'))].add(filename)
def add(self, filename)
Try to add a file.
4.117354
4.150384
0.992042
available = [ep for ep in self if ep > episode] string = ','.join(str(ep) for ep in available[:self.EPISODES_TO_SHOW]) if len(available) > self.EPISODES_TO_SHOW: string += '...' return string
def available_string(self, episode)
Return a string of available episodes.
3.171527
2.799063
1.133067
obj = json.loads(string) return cls(obj['regexp'], obj['files'])
def from_json(cls, string)
Create AnimeFiles from JSON string.
8.995348
6.887594
1.306022
if status_code == '100': return None exc_class = STATUS_CODE_MAPPING.get(status_code) if not exc_class: # No status code match, return the "I don't know wtf this is" # exception class. return STATUS_CODE_MAPPING['UNKNOWN'] else: # Match found, yay. r...
def _get_exception_class_from_status_code(status_code)
Utility function that accepts a status code, and spits out a reference to the correct exception class to raise. :param str status_code: The status code to return an exception class for. :rtype: PetfinderAPIError or None :returns: The appropriate PetfinderAPIError subclass. If the status code is...
5.360241
5.379432
0.996433
if self.url == "": self.client = pymongo.MongoClient(self.host, self.port) else: self.client = pymongo.MongoClient(self.url) self.db_name, self.collection_name = self._replace_placeholder(spider) self.db = self.client[self.db_name]
def open_spider(self, spider)
Initialize Mongodb client.
2.767857
2.390046
1.158077
return self.db_name % {'spider': spider.name}, self.collection_name % {'spider': spider.name}
def _replace_placeholder(self, spider)
Returns replaced db_name and collection_name(base on spider's name). if your db_name or collection_name does not have a placeholder or your db_name or collection_name that not base on spider's name you must override this function.
6.17297
2.658595
2.321892
path = [self.path] path.extend([str(x) for x in self.params]) url = self.client.base_url + '/'.join(x for x in path if x) query = self.kwargs.get('query') if query: # Dict -> List if type(query) is dict: query = query.items() ...
def construct_url(self)
Construct a full plex request URI, with `params`.
3.405879
3.132422
1.087299
@wraps(f) def check_login(cls, *args, **kwargs): if not cls.logged_in: raise FMBaseError('Please login to use this method') return f(cls, *args, **kwargs) return check_login
def login_required(f)
Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in
4.372603
2.515544
1.738233
configfile = get_configfile() if not os.path.exists(configfile): data = { 'apikey': 'GET KEY AT: https://www.filemail.com/apidoc/ApiKey.aspx' } save_config(data) with open(configfile, 'rb') as f: return json.load(f)
def load_config()
Load configuration file containing API KEY and other settings. :rtype: str
5.168173
4.87738
1.059621
configfile = get_configfile() if not os.path.exists(configfile): configdir = os.path.dirname(configfile) if not os.path.exists(configdir): os.makedirs(configdir) data = config with open(configfile, 'wb') as f: json.dump(data, f, indent=2)
def save_config(config)
Save configuration file to users data location. - Linux: ~/.local/share/pyfilemail - OSX: ~/Library/Application Support/pyfilemail - Windows: C:\\\Users\\\{username}\\\AppData\\\Local\\\pyfilemail :rtype: str
2.275856
2.427725
0.937444
ad = appdirs.AppDirs('pyfilemail') configdir = ad.user_data_dir configfile = os.path.join(configdir, 'pyfilemail.cfg') return configfile
def get_configfile()
Return full path to configuration file. - Linux: ~/.local/share/pyfilemail - OSX: ~/Library/Application Support/pyfilemail - Windows: C:\\\Users\\\{username}\\\AppData\\\Local\\\pyfilemail :rtype: str
4.320101
3.340397
1.29329
if name != cls.name: return return super(Logging, cls).from_config(name, config)
def from_config(cls, name, config)
Override of the base `from_config()` method that returns `None` if the name of the config file isn't "logging". We do this in case this `Configurable` subclass winds up sharing the root of the config directory with other subclasses.
6.184375
5.368618
1.151949
# type: (str) -> List[str] if FLAKE8_CONFIG_NAME in os.listdir(config_dir): flake8_config_path = FLAKE8_CONFIG_NAME else: flake8_config_path = DEFAULT_FLAKE8_CONFIG_PATH return ['--config={}'.format(flake8_config_path)]
def get_flake8_options(config_dir='.')
Checks for local config overrides for `flake8` and add them in the correct `flake8` `options` format. :param config_dir: :return: List[str]
2.485821
3.119017
0.796989
# type: (str) -> List[str] if LICENSE_CHECKER_CONFIG_NAME in os.listdir(config_dir): license_checker_config_path = LICENSE_CHECKER_CONFIG_NAME else: license_checker_config_path = DEFAULT_LICENSE_CHECKER_CONFIG_PATH return license_checker_config_path
def get_license_checker_config_path(config_dir='.')
Checks for local config overrides for license checker, if not found it returns the package default. :param config_dir: :return: str
2.571696
3.196814
0.804456