code stringlengths 1 18.2k |
|---|
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 """ for field, value in kwargs.items(): if field in self.Meta.attributes: setattr(self, field, value) |
def add(db, anime): """Add an anime (or update existing). anime is an AnimeTree instance. """ 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... |
def add_episode(db, aid, episode): """Add an episode.""" values = { 'aid': aid, 'type': episode.type, 'number': episode.number, 'title': episode.title, 'length': episode.length, } upsert(db, 'episode', ['aid', 'type', 'number'], values) |
def delete_episode(db, aid, episode): """Delete an episode.""" db.cursor().execute( 'DELETE FROM episode WHERE aid=:aid AND type=:type AND number=:number', { 'aid': aid, 'type': episode.type, 'number': episode.number, }) |
def set_watched(db, aid, ep_type, number): """Set episode as watched.""" db.cursor().execute( """UPDATE episode SET user_watched=:watched WHERE aid=:aid AND type=:type AND number=:number""", { 'aid': aid, 'type': ep_type, 'number': number, 'watched': 1, }) |
def bump(db, aid): """Bump anime regular episode count.""" 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 reset(db, aid, episode): """Reset episode count for anime.""" params = { 'aid': aid, 'type': get_eptype(db, 'regular').id, 'watched': 1, 'number': episode, } with db: cur = db.cursor() cur.execute( """UPDATE episode SET user_watched=:watched WHERE aid=:aid AND type=:type AND number<=:number""", params) params['watc... |
def train_idf(tokens_stream, out=None, **kwargs): """ Train a IDF model on a list of files (parallelized). """ 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['_... |
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 """ 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: pi... |
def user_info(self): """ General user info information as returned in /account in our API """ 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 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'}) """ req = self.request(self.uri + '/providers', api_version=2) providers = req.get().json() supported_providers = providers['suppo... |
def _list_clouds(self): """ Request a list of all added clouds. Populates self._clouds dict with mist.client.model.Cloud instances """ 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 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. """ if self._clouds is None: self._clouds = {} self._list_clouds() if id: return [self._clouds[cloud_id] for cloud_id... |
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 """ 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 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 """ 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_i... |
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 """ req = self.request(self.uri + "/keys") private_key = req.post().json() return private_key['priv'] |
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. """ payload = { 'name': key_name, 'priv': private } dat... |
def command(state, args): """Add a priority rule for files.""" 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 request_anime(aid: int) -> 'Anime': """Make an anime API request.""" anime_info = alib.request_anime(_CLIENT, aid) return Anime._make(anime_info) |
def number(self) -> int: """Episode number. Unique for an anime and episode type, but not unique across episode types for the same anime. """ match = self._NUMBER_SUFFIX.search(self.epno) return int(match.group(1)) |
def title(self) -> str: """Episode title.""" 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 search(self, query: 're.Pattern') -> 'Iterable[_WorkTitles]': """Search titles using a compiled RE query.""" 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_title(titles.titles), ti... |
def _get_packages(): # type: () -> List[Package] """Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list """ return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set, key=lambda x: str(x).lower())] |
def _get_whitelist_licenses(config_path): # type: (str) -> List[str] """Get whitelist license names from config file. :param config_path: str :return: list """ whitelist_licenses = [] try: print('config path', config_path) with open(config_path) as config: whitelist_licenses = [line.rstrip() for line in config] except ... |
def run_license_checker(config_path): # type: (str) -> None """Generate table of installed packages and check for license warnings based off user defined restricted license values. :param config_path: str :return: """ whitelist_licenses = _get_whitelist_licenses(config_path) table = PrintTable(ROW_HEADERS) warnings = [... |
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.search_for.include_fields("flags") The follow... |
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` """ for component in components: self._component.append(component) 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` """ for product in products: self._product.append(product) 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` """ if start: self._time_frame['chfieldfrom'] = start if end: self._time_frame['chfieldto'] = end return self |
def change_history_fields(self, fields, value=None): 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 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\ ... .keywords("checkin-needed")\ ... .include_fields("fla... |
self._change_history['value'] try: results = self._bugsy.request('bug', params=params) except Exception as e: raise SearchException(e.msg, e.code) return [Bug(self._bugsy, **bug) for bug in results['bugs']] |
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) """ return datetime.datetime.strptime(string, '%Y-%m-%d').date() |
def sync_remote_to_local(force="no"): """ Replace your remote db with your local Example: sync_remote_to_local:force=yes """ 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, ... |
def get_priority_rules(db) -> Iterable[PriorityRule]: """Get file priority rules.""" cur = db.cursor() cur.execute('SELECT id, regexp, priority FROM file_priority') for row in cur: yield PriorityRule(*row) |
def add_priority_rule( db, regexp: str, priority: Optional[int] = None, ) -> int: """Add a file priority rule.""" 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... |
def delete_priority_rule(db, rule_id: int) -> None: """Delete a file priority rule.""" with db: cur = db.cursor() cur.execute('DELETE FROM file_priority WHERE id=?', (rule_id,)) |
def cache_files(db, aid: int, anime_files: AnimeFiles) -> None: """Cache files for anime.""" with db: cache_status(db, aid) db.cursor().execute( """UPDATE cache_anime SET anime_files=? WHERE aid=?""", (anime_files.to_json(), aid)) |
def get_files(conn, aid: int) -> AnimeFiles: """Get cached files for anime.""" 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 add(self, filename): """Try to add a file.""" basename = os.path.basename(filename) match = self.regexp.search(basename) if match: self.by_episode[int(match.group('ep'))].add(filename) |
def available_string(self, episode): """Return a string of available episodes.""" 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 from_json(cls, string): """Create AnimeFiles from JSON string.""" obj = json.loads(string) return cls(obj['regexp'], obj['files']) |
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 PetfinderAPIEr... |
def open_spider(self, spider): """ Initialize Mongodb client. """ 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 _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. """ return self.db_name % {'spider': spider.n... |
def construct_url(self): """Construct a full plex request URI, with `params`.""" 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() # Remove item... |
def login_required(f): """Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in """ @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 load_config(): """Load configuration file containing API KEY and other settings. :rtype: str """ 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 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 """ configfile = get_configfile() if not os.path.exists(configfile): configdir = os... |
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 """ ad = appdirs.AppDirs('pyfilemail') configdir = ad.user_data_dir configfile = os.path.join(... |
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. """ if name != cls.name: return return super(Lo... |
def get_flake8_options(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for `flake8` and add them in the correct `flake8` `options` format. :param config_dir: :return: List[str] """ if FLAKE8_CONFIG_NAME in os.listdir(config_dir): flake8_config_path = FLAKE8_CONFIG_NAME else: flake8_conf... |
def get_license_checker_config_path(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for license checker, if not found it returns the package default. :param config_dir: :return: str """ if LICENSE_CHECKER_CONFIG_NAME in os.listdir(config_dir): license_checker_config_path = LICENSE_CHECK... |
def get_pylint_options(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for `pylint` and add them in the correct `pylint` `options` format. :param config_dir: :return: List [str] """ if PYLINT_CONFIG_NAME in os.listdir(config_dir): pylint_config_path = PYLINT_CONFIG_NAME else: pylint_con... |
def wait_on_any(*events, **kwargs): """ Helper method for waiting for any of the given threading events to be set. The standard threading lib doesn't include any mechanism for waiting on more than one event at a time so we have to monkey patch the events so that their `set()` and `clear()` methods fire a callback we ca... |
def wait_on_event(event, timeout=None): """ Waits on a single threading Event, with an optional timeout. This is here for compatibility reasons as python 2 can't reliably wait on an event without a timeout and python 3 doesn't define a `maxint`. """ if timeout is not None: event.wait(timeout) return if six.PY2: # Thank... |
def validate_config(cls, config): """ Validates that a config file path and a control socket file path and pid file path are all present in the HAProxy config. """ if "config_file" not in config: raise ValueError("No config file path given") if "socket_file" not in config: raise ValueError("No control socket path given... |
def validate_proxies_config(cls, proxies): """ Specific config validation method for the "proxies" portion of a config. Checks that each proxy defines a port and a list of `upstreams`, and that each upstream entry has a host and port defined. """ for name, proxy in six.iteritems(proxies): if "port" not in proxy: raise ... |
def apply_config(self, config): """ Constructs HAProxyConfig and HAProxyControl instances based on the contents of the config. This is mostly a matter of constructing the configuration stanzas. """ self.haproxy_config_path = config["config_file"] global_stanza = Stanza("global") global_stanza.add_lines(config.get("glob... |
def sync_file(self, clusters): """ Generates new HAProxy config file content and writes it to the file at `haproxy_config_path`. If a restart is not necessary the nodes configured in HAProxy will be synced on the fly. If a restart *is* necessary, one will be triggered. """ logger.info("Updating HAProxy config file.") i... |
def restart(self): """ Tells the HAProxy control object to restart the process. If it's been fewer than `restart_interval` seconds since the previous restart, it will wait until the interval has passed. This staves off situations where the process is constantly restarting, as it is possible to drop packets for a short ... |
def sync_nodes(self, clusters): """ Syncs the enabled/disabled status of nodes existing in HAProxy based on the given clusters. This is used to inform HAProxy of up/down nodes without necessarily doing a restart of the process. """ logger.info("Syncing HAProxy backends.") current_nodes, enabled_nodes = self.get_current... |
def get_current_nodes(self, clusters): """ Returns two dictionaries, the current nodes and the enabled nodes. The current_nodes dictionary is keyed off of the cluster name and values are a list of nodes known to HAProxy. The enabled_nodes dictionary is also keyed off of the cluster name and values are list of *enabled*... |
return current_nodes, enabled_nodes |
def validate_config(cls, config): """ Runs a check on the given config to make sure that `port`/`ports` and `discovery` is defined. """ if "discovery" not in config: raise ValueError("No discovery method defined.") if not any([item in config for item in ["port", "ports"]]): raise ValueError("No port(s) defined.") cls.v... |
def validate_check_configs(cls, config): """ Config validation specific to the health check options. Verifies that checks are defined along with an interval, and calls out to the `Check` class to make sure each individual check's config is valid. """ if "checks" not in config: raise ValueError("No checks defined.") if ... |
def apply_config(self, config): """ Takes a given validated config dictionary and sets an instance attribute for each one. For check definitions, a Check instance is is created and a `checks` attribute set to a dictionary keyed off of the checks' names. If the Check instance has some sort of error while being created a... |
def update_ports(self): """ Sets the `ports` attribute to the set of valid port values set in the configuration. """ ports = set() for port in self.configured_ports: try: ports.add(int(port)) except ValueError: logger.error("Invalid port value: %s", port) continue self.ports = ports |
def update_checks(self, check_configs): """ Maintains the values in the `checks` attribute's dictionary. Each key in the dictionary is a port, and each value is a nested dictionary mapping each check's name to the Check instance. This method makes sure the attribute reflects all of the properly configured checks and po... |
def run_checks(self): """ Iterates over the configured ports and runs the checks on each one. Returns a two-element tuple: the first is the set of ports that transitioned from down to up, the second is the set of ports that transitioned from up to down. Also handles the case where a check for a since-removed port is ru... |
not checks_pass: went_down.add(port) self.is_up[port] = False for unused_port in set(self.checks.keys()) - self.ports: went_down.add(unused_port) del self.checks[unused_port] return came_up, went_down |
def parse_with_retrieved(self, retrieved): """ Parse output data folder, store results in database. :param retrieved: a dictionary of retrieved nodes, where the key is the link name :returns: a tuple with two values ``(bool, node_list)``, where: * ``bool``: variable to tell if the parsing succeeded * ``node_list``: lis... |
all expected output files {} were found".format( output_files)) return success, node_list output_links = self._calc.inp.parameters.output_links for fname, link in list(zip(output_files, output_links)): parsed = SinglefileData(file=out_folder.get_abs_path(fname)) node_list.append((link, parsed)) success = True return su... |
def mark_sacrificed(self,request,queryset): """An admin action for marking several animals as sacrificed. This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed. This admin action also shows as the output... |
def mark_deactivated(self,request,queryset): """An admin action for marking several cages as inactive. This action sets the selected cages as Active=False and Death=today. This admin action also shows as the output the number of mice sacrificed.""" rows_updated = queryset.update(Active=False, End=datetime.date.today() ... |
def run(main=None, argv=None): """Runs the program with an optional 'main' function and 'argv' list.""" flags_obj = flags.FLAGS absl_flags_obj = absl_flags.FLAGS # Extract the args from the optional `argv` list. args = argv[1:] if argv else None # Parse the known flags from that list, or from the command # line otherwi... |
def make_unicode(s, encoding='utf-8', encoding_errors='strict'): """ Return the unicode version of an input. """ if not isinstance(s, unicode): if not isinstance(s, basestring): return unicode(str(s), encoding, encoding_errors) return unicode(s, encoding, encoding_errors) return s |
def html_escape(s, encoding='utf-8', encoding_errors='strict'): """ Return the HTML-escaped version of an input. """ return escape(make_unicode(s, encoding, encoding_errors), quote=True) |
def retarget_to_length(song, duration, start=True, end=True, slack=5, beats_per_measure=None): """Create a composition of a song that changes its length to a given duration. :param song: Song to retarget :type song: :py:class:`radiotool.composer.Song` :param duration: Duration of retargeted song (in seconds) :type dura... |
constraints.append( rt_constraints.EndAtEndConstraint(padding=slack)) comp, info = retarget( [song], duration, constraints=[constraints], fade_in_len=None, fade_out_len=None) # force the new track to extend to the end of the song if end: last_seg = sorted( comp.segments, key=lambda seg: seg.comp_location_in_seconds + s... |
def retarget_with_change_points(song, cp_times, duration): """Create a composition of a song of a given duration that reaches music change points at specified times. This is still under construction. It might not work as well with more than 2 ``cp_times`` at the moment. Here's an example of retargeting music to be 40 s... |
""" analysis = song.analysis beat_length = analysis[BEAT_DUR_KEY] beats = np.array(analysis["beats"]) # find change points cps = np.array(novelty(song, nchangepoints=4)) cp_times = np.array(cp_times) # mark change points in original music def music_labels(t): # find beat closest to t closest_beat_idx = np.argmin(np.abs... |
1.0) ] comp, info = retarget( [song], duration, constraints=[constraints], fade_in_len=None, fade_out_len=None) final_cp_locations = [beat_length * i for i, label in enumerate(info['result_labels']) if label == 'cp'] return comp, final_cp_locations |
def retarget(songs, duration, music_labels=None, out_labels=None, out_penalty=None, volume=None, volume_breakpoints=None, springs=None, constraints=None, min_beats=None, max_beats=None, fade_in_len=3.0, fade_out_len=5.0, **kwargs): """Retarget a song to a duration given input and output labels on the music. Suppose you... |
Song("sweet-rock-song.wav") composition, info = retarget(song, 180, music_labels=labels, out_labels=target) composition.export(filename="super-long-solo") You can achieve much more complicated retargetings by adjusting the ``music_labels``, `out_labels` and ``out_penalty`` functions, but this should give you a basic se... |
output label at that time (default is 1.0) :type out_penalty: function :returns: Composition of retargeted song, and dictionary of information about the retargeting :rtype: (:py:class:`radiotool.composer.Composition`, dict) """ # get song analysis if isinstance(songs, Track): songs = [songs] multi_songs = len(songs) > ... |
for item in sublist] if len(music_labels) != len(songs): raise ArgumentException("Did not specify {} sets of music labels". format(len(songs))) start = [[music_labels[i](j) for j in b] for i, b in enumerate(beats)] else: start = [["" for i in b] for b in beats] if out_penalty is not None: pen = np.array([out_penalty(i)... |
j in beats[i]]) in_vas[i] = in_va target_va = kwargs.pop('out_va', None) if callable(target_va): target_va = np.array( [target_va(i) for i in np.arange(0, duration, beat_length)]) # set constraints if constraints is None: min_pause_len = 20. max_pause_len = 35. min_pause_beats = int(np.ceil(min_pause_len / beat_length)... |
b in beats])) total_beats = total_music_beats + max_pause_beats # combine transition cost tables trans_cost = np.ones((total_beats, total_beats)) * np.inf sizes = [len(b) for b in beats] idx = 0 for i, size in enumerate(sizes): trans_cost[idx:idx + size, idx:idx + size] =\ trans_costs[i][:size, :size] idx += size trans... |
min_beats is None: min_beats = 0 elif min_beats is 'default': min_beats = int(20. / beat_length) if max_beats is None: max_beats = -1 elif max_beats is 'default': max_beats = int(90. / beat_length) max_beats = min(max_beats, penalty.shape[1]) tc2 = np.nan_to_num(trans_cost) pen2 = np.nan_to_num(penalty) beat_names = []... |
path = [] if max_beats == -1: max_beats = min_beats + 1 first_pause_full = max_beats * first_pause n_beats = first_pause for i in path_i: if i >= first_pause_full: path.append(('p', i - first_pause_full)) result_labels.append(None) # path.append('p' + str(i - first_pause_full)) else: path.append(beat_names[i % n_beats]... |
prev_node, cost, beat_names, best_idx, N.shape(cost)[1] - 1) # # path_i = [beat_names.index(x) for x in path] # else: # # throw an exception here? # return None # path = [] # result_labels = [] # if max_pause_beats == 0: # n_beats = total_music_beats # first_pause = n_beats # else: # n_beats = first_pause # for i in pa... |
"path": path, "path_i": path_i, "target_labels": target, "result_labels": result_labels, "result_full_labels": result_full_labels, "result_volume": result_volume, "transitions": [Label("crossfade", loc) for loc in cf_locations], "path_cost": cost_labels } return comp, info |
def init_command_set(self, scrapyd_url): """ Initialize command set by scrapyd_url,each element is a list such as ['command','supported http method type'] """ if scrapyd_url[-1:] != '/': scrapyd_url = scrapyd_url + '/' self['daemonstatus'] = [scrapyd_url + 'daemonstatus.json', http_utils.METHOD_GET] self['addversion'] ... |
def get_load_status(self): """ To check the load status of a service. :return: a dictionary that include json data. example: { "status": "ok", "running": "0", "pending": "0", "finished": "0", "node_name": "node-name" } """ url, method = self.command_set['daemonstatus'][0], self.command_set['daemonstatus'][1] response =... |
def schedule(self, project_name, spider_name, priority=0, setting=None, job_id=None, version=None, args={}): """ Schedule a spider run (also known as a job), returning the job id. :param project_name: the project name :param spider_name: the spider name :param priority: the run priority :param setting: a Scrapy setting... |
None: data['_version'] = version for k, v in args.items(): data[k] = v response = http_utils.request(url, method_type=method, data=data, return_type=http_utils.RETURN_JSON) if response is None: logging.warning('%s failure: not found or connection fail' % sys._getframe().f_code.co_name) response = ScheduleResultSet().__... |
def cancel(self, project_name, job_id): """ Cancel a spider run (aka. job). If the job is pending, it will be removed. If the job is running, it will be terminated. :param project_name: the project name :param job_id: the job id :return: a dictionary that status message example: {"status": "ok", "prevstate": "running"}... |
def get_spider_list(self, project_name, version=None): """ Get the list of spiders available in the last (unless overridden) version of some project. :param project_name: the project name :param version: the version of the project to examine :return: a dictionary that spider name list example: {"status": "ok", "spiders... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.