code
stringlengths
1
18.2k
def download_file(self, src_uri, target): """Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or file-like object in write mode """ resource = self.get_resource_by_uri(src_uri) if not isinstance(resource, File): raise MediaFireError("Only files can be downloaded") quick_ke...
if hasattr(target, 'write') else False if not target_is_filehandle: if (os.path.exists(target) and os.path.isdir(target)) or \ target.endswith("/"): target = os.path.join(target, name) if not os.path.isdir(os.path.dirname(target)): os.makedirs(os.path.dirname(target)) logger.info("Downloading %s to %s", src_uri, target...
mismatch ({} != {})".format( resource['hash'], checksum_hex)) logger.info("Download completed successfully") finally: if not target_is_filehandle: out_fd.close()
def update_file_metadata(self, uri, filename=None, description=None, mtime=None, privacy=None): """Update file metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side: filename -- rename file description -- set file description string mtime -- set file ...
got {}'.format(type(resource))) result = self.api.file_update(resource['quickkey'], filename=filename, description=description, mtime=mtime, privacy=privacy) return result
def update_folder_metadata(self, uri, foldername=None, description=None, mtime=None, privacy=None, privacy_recursive=None): """Update folder metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side: filename -- rename file description -- set file descrip...
if not isinstance(resource, Folder): raise ValueError('Expected Folder, got {}'.format(type(resource))) result = self.api.folder_update(resource['folderkey'], foldername=foldername, description=description, mtime=mtime, privacy=privacy, privacy_recursive=privacy_recursive) return result
def _parse_uri(uri): """Parse and validate MediaFire URI.""" tokens = urlparse(uri) if tokens.netloc != '': logger.error("Invalid URI: %s", uri) raise ValueError("MediaFire URI format error: " "host should be empty - mf:///path") if tokens.scheme != '' and tokens.scheme != URI_SCHEME: raise ValueError("MediaFire URI fo...
def merged(self): '''The clean stats from all the hosts reporting to this host.''' stats = {} for topic in self.client.topics()['topics']: for producer in self.client.lookup(topic)['producers']: hostname = producer['broadcast_address'] port = producer['http_port'] host = '%s_%s' % (hostname, port) stats[host] = nsqd.Cl...
def raw(self): '''All the raw, unaggregated stats (with duplicates).''' topic_keys = ( 'message_count', 'depth', 'backend_depth', 'paused' ) channel_keys = ( 'in_flight_count', 'timeout_count', 'paused', 'deferred_count', 'message_count', 'depth', 'backend_depth', 'requeue_count' ) for host, stats in self.merged.items(...
yield ( 'topic.%s.%s' % (topic, key), value, True ) yield ( 'topics.%s' % key, value, True ) for chan, stats in stats.get('channels', {}).items(): data = { key: int(stats.get(key, -1)) for key in channel_keys } data['clients'] = len(stats.get('clients', [])) for key, value in data.items(): yield ( 'host.%s.topic.%s.cha...
yield ( 'topic.%s.channels.%s' % (topic, key), value, True ) yield ( 'channels.%s' % key, value, True )
def stats(self): '''Stats that have been aggregated appropriately.''' data = Counter() for name, value, aggregated in self.raw: if aggregated: data['%s.max' % name] = max(data['%s.max' % name], value) data['%s.total' % name] += value else: data[name] = value return sorted(data.items())
def get_curline(): """Return the current python source line.""" if Frame: frame = Frame.get_selected_python_frame() if frame: line = '' f = frame.get_pyop() if f and not f.is_optimized_out(): cwd = os.path.join(os.getcwd(), '') fname = f.filename() if cwd in fname: fname = fname[len(cwd):] try: line = f.current_line() ...
line = line[:-2] if line.endswith(r'\n') else line return ('-> %s(%s): %s' % (fname, f.current_line_num(), line)) return ''
def reconnected(self, conn): '''Subscribe connection and manipulate its RDY state''' conn.sub(self._topic, self._channel) conn.rdy(1)
def distribute_ready(self): '''Distribute the ready state across all of the connections''' connections = [c for c in self.connections() if c.alive()] if len(connections) > self._max_in_flight: raise NotImplementedError( 'Max in flight must be greater than number of connections') else: # Distribute the ready count evenl...
count > conn.max_rdy_count: logger.info( 'Using max_rdy_count (%i) instead of %i for %s RDY', conn.max_rdy_count, count, conn) count = conn.max_rdy_count logger.info('Sending RDY %i to %s', count, conn) conn.rdy(count)
def needs_distribute_ready(self): '''Determine whether or not we need to redistribute the ready state''' # Try to pre-empty starvation by comparing current RDY against # the last value sent. alive = [c for c in self.connections() if c.alive()] if any(c.ready <= (c.last_ready_sent * 0.25) for c in alive): return True
def read(self): '''Read some number of messages''' found = Client.read(self) # Redistribute our ready state if necessary if self.needs_distribute_ready(): self.distribute_ready() # Finally, return all the results we've read return found
def profiler(): '''Profile the block''' import cProfile import pstats pr = cProfile.Profile() pr.enable() yield pr.disable() ps = pstats.Stats(pr).sort_stats('tottime') ps.print_stats()
def messages(count, size): '''Generator for count messages of the provided size''' import string # Make sure we have at least 'size' letters letters = islice(cycle(chain(string.lowercase, string.uppercase)), size) return islice(cycle(''.join(l) for l in permutations(letters, size)), count)
def grouper(iterable, n): '''Collect data into fixed-length chunks or blocks''' args = [iter(iterable)] * n for group in izip_longest(fillvalue=None, *args): group = [g for g in group if g != None] yield group
def basic(topic='topic', channel='channel', count=1e6, size=10, gevent=False, max_in_flight=2500, profile=False): '''Basic benchmark''' if gevent: from gevent import monkey monkey.patch_all() # Check the types of the arguments count = int(count) size = int(size) max_in_flight = int(max_in_flight) from nsq.http import n...
= -time.time() if profile: with profiler(): for message in islice(client, count): message.fin() else: for message in islice(client, count): message.fin() start += time.time() print 'Finished %i messages in %fs (%5.2f messages / second)' % ( count, start, count / start)
def stats(): '''Read a stream of floats and give summary statistics''' import re import sys import math values = [] for line in sys.stdin: values.extend(map(float, re.findall(r'\d+\.?\d+', line))) mean = sum(values) / len(values) variance = sum((val - mean) ** 2 for val in values) / len(values) print '%3i items; mean: ...
def ready(self): '''Whether or not enough time has passed since the last failure''' if self._last_failed: delta = time.time() - self._last_failed return delta >= self.backoff() return True
def execute_status(args, root_dir=None): """Print the status of the daemon. This function displays the current status of the daemon as well as the whole queue and all available information about every entry in the queue. `terminaltables` is used to format and display the queue contents. `colorclass` is used to color fo...
directory the daemon is running in. """ status = command_factory('status')({}, root_dir=root_dir) # First rows, showing daemon status if status['status'] == 'running': status['status'] = Color('{autogreen}' + '{}'.format(status['status']) + '{/autogreen}') elif status['status'] in ['paused']: status['status'] = Color('...
formatted_data = [] formatted_data.append(['Index', 'Status', 'Code', 'Command', 'Path', 'Start', 'End']) for key, entry in sorted(data.items(), key=operator.itemgetter(0)): formatted_data.append( [ '#{}'.format(key), entry['status'], '{}'.format(entry['returncode']), entry['command'], entry['path'], entry['start'], en...
new size for the Command and Path column. if (reduce(lambda a, b: a+b, table.column_widths) + 10) > terminal_width[0]: # We have to subtract 14 because of table paddings left_space = math.floor((terminal_width[0] - customWidth[0] - customWidth[1] - customWidth[2] - customWidth[5] - customWidth[6] - 14)/2) if customWidt...
left_space customWidth[4] = left_space # Format long strings to match the console width for i, entry in enumerate(table.table_data): for j, string in enumerate(entry): max_width = customWidth[j] wrapped_string = '\n'.join(wrap(string, max_width)) if j == 1: if wrapped_string == 'done' or wrapped_string == 'running' or ...
'{/autoyellow}') elif wrapped_string in ['failed', 'stopping', 'killing']: wrapped_string = Color('{autored}' + '{}'.format(wrapped_string) + '{/autored}') elif j == 2: if wrapped_string == '0' and wrapped_string != 'Code': wrapped_string = Color('{autogreen}' + '{}'.format(wrapped_string) + '{/autogreen}') elif wrappe...
def execute_log(args, root_dir): """Print the current log file. Args: args['keys'] (int): If given, we only look at the specified processes. root_dir (string): The path to the root directory the daemon is running in. """ # Print the logs of all specified processes if args.get('keys'): config_dir = os.path.join(root_dir...
print('Queue log file seems to be corrupted. Aborting.') return queue_file.close() else: print('There is no queue log file. Aborting.') return for key in args.get('keys'): # Check if there is an entry with this key if queue.get(key) and queue[key]['status'] in ['failed', 'done']: entry = queue[key] print('Log of entry:...
> 0: print(Color('{autored}Stderr output: {/autored}\n ') + entry['stderr']) # Write STDOUT if len(entry['stdout']) > 0: print(Color('{autogreen}Stdout output: {/autogreen}\n ') + entry['stdout']) else: print('No finished process with key {}.'.format(key)) # Print the log of all processes else: log_path = os.path.join(...
def execute_show(args, root_dir): """Print stderr and stdout of the current running process. Args: args['watch'] (bool): If True, we open a curses session and tail the output live in the console. root_dir (string): The path to the root directory the daemon is running in. """ key = None if args.get('key'): key = args['k...
'running': print('No running process with this key, use `log` to show finished processes.') return # In case no key provided, we take the oldest running process else: status = command_factory('status')({}, root_dir=root_dir) if isinstance(status['data'], str): print(status['data']) return for k in sorted(status['data']...
os.path.join(root_dir, '.config/pueue') # Get current pueueSTDout file from tmp stdoutFile = os.path.join(config_dir, 'pueue_process_{}.stdout'.format(key)) stderrFile = os.path.join(config_dir, 'pueue_process_{}.stderr'.format(key)) stdoutDescriptor = open(stdoutFile, 'r') stderrDescriptor = open(stderrFile, 'r') runn...
stdoutDescriptor.read() stdscr.addstr(0, 0, message) stdscr.refresh() time.sleep(2) except Exception: # Curses cleanup curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin() else: print('Stdout output:\n') stdoutDescriptor.seek(0) print(get_descriptor_output(stdoutDescriptor, key)) print('\n\nStderr outpu...
def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a song track by given ID. :param track_id: the track ID. :type track_id: str :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`. ''' url = 'https://api.kkbox.com/v1.1/tracks/%s' % track_id url += '...
def show(self, user, feed, id): """ Show a specific indicator by id :param user: feed username :param feed: feed name :param id: indicator endpoint id [INT] :return: dict Example: ret = Indicator.show('csirtgadgets','port-scanners', '1234') """ uri = '/users/{}/feeds/{}/indicators/{}'.format(user, feed, id) return self...
def create(self): """ Submit action on the Indicator object :return: Indicator Object """ uri = '/users/{0}/feeds/{1}/indicators'\ .format(self.user, self.feed) data = { "indicator": json.loads(str(self.indicator)), "comment": self.comment, "content": self.content } if self.attachment: attachment = self._file_to_attach...
def create_bulk(self, indicators, user, feed): from .constants import API_VERSION if API_VERSION == '1': print("create_bulk currently un-avail with APIv1") raise SystemExit """ Submit action against the IndicatorBulk endpoint :param indicators: list of Indicator Objects :param user: feed username :param feed: feed name...
i = { 'indicator': 'example.com', 'feed': 'test', 'user': 'admin', 'comment': 'this is a test', } data = [] cli = Client(remote=remote, token=token, verify_ssl=verify_ssl) for x in range(0, 5): data.append( Indicator(cli, i) ) ret = cli.submit_bulk(data, 'csirtgadgets', 'test-feed') """ uri = '/users/{0}/feeds/{1}/indi...
'portlist_src': i.args.portlist_src, 'comment': { 'content': i.args.comment }, 'rdata': i.args.rdata, 'rtype': i.args.rtype, 'content': i.args.content, 'provider': i.args.provider, } for i in indicators ] } return self.client.post(uri, data)
def bind_global_key(conn, event_type, key_string, cb): """ An alias for ``bind_key(event_type, ROOT_WINDOW, key_string, cb)``. :param event_type: Either 'KeyPress' or 'KeyRelease'. :type event_type: str :param key_string: A string of the form 'Mod1-Control-a'. Namely, a list of zero or more modifiers separated by '-', ...
if the binding was successful, False otherwise. :rtype: bool """ root = conn.get_setup().roots[0].root return bind_key(conn, event_type, root, key_string, cb)
def bind_key(conn, event_type, wid, key_string, cb): """ Binds a function ``cb`` to a particular key press ``key_string`` on a window ``wid``. Whether it's a key release or key press binding is determined by ``event_type``. ``bind_key`` will automatically hook into the ``event`` module's dispatcher, so that if you're u...
'KeyPress' or 'KeyRelease'. :type event_type: str :param wid: The window to bind the key grab to. :type wid: int :param key_string: A string of the form 'Mod1-Control-a'. Namely, a list of zero or more modifiers separated by '-', followed by a single non-modifier key. :type key_string: str :param cb: A first class func...
was successful, False otherwise. :rtype: bool """ assert event_type in ('KeyPress', 'KeyRelease') mods, kc = parse_keystring(conn, key_string) key = (wid, mods, kc) if not kc: print("Could not find a keycode for " + key_string) return False if not __keygrabs[key] and not grab_key(conn, wid, mods, kc): return False __ke...
def parse_keystring(conn, key_string): """ A utility function to turn strings like 'Mod1+Mod4+a' into a pair corresponding to its modifiers and keycode. :param key_string: String starting with zero or more modifiers followed by exactly one key press. Available modifiers: Control, Mod1, Mod2, Mod3, Mod4, Mod5, Shift, Lo...
is temporary hack, requires better abstraction from PyQt5.QtGui import QKeySequence from PyQt5.QtCore import Qt from .qt_keycodes import KeyTbl, ModsTbl keysequence = QKeySequence(key_string) ks = keysequence[0] # Calculate the modifiers mods = Qt.NoModifier qtmods = Qt.NoModifier modifiers = 0 if (ks & Qt.ShiftModifie...
qtmods |= Qt.AltModifier.real modifiers |= getattr(xproto.KeyButMask, "Mod1", 0) if (ks & Qt.ControlModifier == Qt.ControlModifier): mods |= ModsTbl.index(Qt.ControlModifier) qtmods |= Qt.ControlModifier.real modifiers |= getattr(xproto.KeyButMask, "Control", 0) # Calculate the keys qtkeys = ks ^ qtmods key = QKeySeque...
|= getattr(xproto.KeyButMask, part) else: if len(part) == 1: part = part.lower() keycode = lookup_string(conn, part) return modifiers, keycode
def lookup_string(conn, kstr): """ Finds the keycode associated with a string representation of a keysym. :param kstr: English representation of a keysym. :return: Keycode, if one exists. :rtype: int """ if kstr in keysyms: return get_keycode(conn, keysyms[kstr]) elif len(kstr) > 1 and kstr.capitalize() in keysyms: ret...
def get_keyboard_mapping(conn): """ Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode(conn) return conn.core.GetKeyboardMapping(mn, mx - mn + 1)
def get_keyboard_mapping_unchecked(conn): """ Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode() return conn.core.GetKeyboardMappingUnchecked(mn, mx - mn + 1)
def get_keysym(conn, keycode, col=0, kbmap=None): """ Get the keysym associated with a particular keycode in the current X environment. Although we get a list of keysyms from X in 'get_keyboard_mapping', this list is really a table with 'keysys_per_keycode' columns and ``mx - mn`` rows (where ``mx`` is the maximum keyc...
keycode is: ``(keycode - mn) * keysyms_per_keycode + col``. In most cases, setting ``col`` to 0 will work. Witness the utter complexity: http://tronche.com/gui/x/xlib/input/keyboard-encoding.html You may also pass in your own keyboard mapping using the ``kbmap`` parameter, but xpybutil maintains an up-to-date version o...
column in the keysym table to use. Unless you know what you're doing, just use 0. :type col: int :param kbmap: The keyboard mapping to use. :type kbmap: xcb.xproto.GetKeyboardMapingReply """ if kbmap is None: kbmap = __kbmap mn, mx = get_min_max_keycode(conn) per = kbmap.keysyms_per_keycode ind = (keycode - mn) * per +...
def get_keycode(conn, keysym): """ Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this, including all columns. :param keysym: An X keysym. :return: A keycode or None if one could not be found. :rtype: int """ mn, mx = get_min_max_key...
mx + 1): for j in range(0, cols): ks = get_keysym(conn, i, col=j) if ks == keysym: return i return None
def get_keys_to_mods(conn): """ Fetches and creates the keycode -> modifier mask mapping. Typically, you shouldn't have to use this---xpybutil will keep this up to date if it changes. This function may be useful in that it should closely replicate the output of the ``xmodmap`` command. For example: :: keymods = get_key...
very closely replicate ``xmodmap``. I'm not getting precise results quite yet, but I do believe I'm getting at least most of what matters. (i.e., ``xmodmap`` returns valid keysym strings for some that I cannot.) :return: A dict mapping from keycode to modifier mask. :rtype: dict """ mm = xproto.ModMask modmasks = [mm.S...
conn.core.GetModifierMapping().reply() res = {} keyspermod = mods.keycodes_per_modifier for mmi in range(0, len(modmasks)): row = mmi * keyspermod for kc in mods.keycodes[row:row + keyspermod]: res[kc] = modmasks[mmi] return res
def get_modifiers(state): """ Takes a ``state`` (typically found in key press or button press events) and returns a string list representation of the modifiers that were pressed when generating the event. :param state: Typically from ``some_event.state``. :return: List of modifier string representations. :rtype: [str] ...
state & xproto.ModMask._1: ret.append('Mod1') if state & xproto.ModMask._2: ret.append('Mod2') if state & xproto.ModMask._3: ret.append('Mod3') if state & xproto.ModMask._4: ret.append('Mod4') if state & xproto.ModMask._5: ret.append('Mod5') if state & xproto.KeyButMask.Button1: ret.append('Button1') if state & xproto....
def grab_key(conn, wid, modifiers, key): """ Grabs a key for a particular window and a modifiers/key value. If the grab was successful, return True. Otherwise, return False. If your client is grabbing keys, it is useful to notify the user if a key wasn't grabbed. Keyboard shortcuts not responding is disorienting! Also,...
accounts for all of the "trivial" modifiers that may have an effect on X events, but probably shouldn't effect key grabbing. (i.e., whether num lock or caps lock is on.) N.B. You should probably be using 'bind_key' or 'bind_global_key' instead. :param wid: A window identifier. :type wid: int :param modifiers: A modifie...
bool """ try: for mod in TRIVIAL_MODS: conn.core.GrabKeyChecked(True, wid, modifiers | mod, key, GM.Async, GM.Async).check() return True except xproto.BadAccess: return False
def ungrab_key(conn, wid, modifiers, key): """ Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return True on success and False on failure. When ungrabbing a key, the parameters to this function should be *precisely* the same as the parameters to ``grab_key``. :param wid: A window identifier. :type w...
:type key: int :rtype: bool """ try: for mod in TRIVIAL_MODS: conn.core.UngrabKeyChecked(key, wid, modifiers | mod).check() return True except xproto.BadAccess: return False
def update_keyboard_mapping(conn, e): """ Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing of the current keysym table. Indeed, xpybutil will do this for you automatically. Moreover, if something is changed that affects the current keygrabs, xpybutil ...
global __kbmap, __keysmods newmap = get_keyboard_mapping(conn).reply() if e is None: __kbmap = newmap __keysmods = get_keys_to_mods(conn) return if e.request == xproto.Mapping.Keyboard: changes = {} for kc in range(*get_min_max_keycode(conn)): knew = get_keysym(kc, kbmap=newmap) oldkc = get_keycode(conn, knew) if oldkc...
def run_keybind_callbacks(e): """ A function that intercepts all key press/release events, and runs their corresponding callback functions. Nothing much to see here, except that we must mask out the trivial modifiers from the state in order to find the right callback. Callbacks are called in the order that they have be...
if the callback was serviced """ kc, mods = e.detail, e.state for mod in TRIVIAL_MODS: mods &= ~mod key = (e.event, mods, kc) serviced = False for cb in __keybinds.get(key, []): try: cb(e) serviced = True except TypeError: cb() return serviced
def __regrab(changes): """ Takes a dictionary of changes (mapping old keycode to new keycode) and regrabs any keys that have been changed with the updated keycode. :param changes: Mapping of changes from old keycode to new keycode. :type changes: dict :rtype: void """ for wid, mods, kc in __keybinds.keys(): if kc in ch...
new = (wid, mods, changes[kc]) __keybinds[new] = __keybinds[old] del __keybinds[old]
def get_storages(self, storage_type='normal'): """ Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite """ res = self.get_request('/storage/' + storage_type) return Storage._create_storage_objs(res['storages'], cloud_manager=self)
def get_storage(self, storage): """ Return a Storage object from the API. """ res = self.get_request('/storage/' + str(storage)) return Storage(cloud_manager=self, **res['storage'])
def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an object based on the API's response. """ body = { 'storage': { 'size': size, 'tier': tier, 'title': title, 'zone': zone, 'backup_rule': backup_rule } } res = self.post_request(...
def modify_storage(self, storage, size, title, backup_rule={}): """ Modify a Storage object. Returns an object based on the API's response. """ res = self._modify_storage(str(storage), size, title, backup_rule) return Storage(cloud_manager=self, **res['storage'])
def attach_storage(self, server, storage, storage_type, address): """ Attach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {}} if storage: body['storage_device']['storage'] = str(storage) if storage_type: body['storage_device']['type'] = storage_type if address: bod...
def detach_storage(self, server, address): """ Detach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {'address': address}} url = '/server/{0}/storage/detach'.format(server) res = self.post_request(url, body) return Storage._create_storage_objs(res['server']['storage_...
def _reset(self, **kwargs): """ Reset after repopulating from API. """ # there are some inconsistenciens in the API regarding these # note: this could be written in fancier ways, but this way is simpler if 'uuid' in kwargs: self.uuid = kwargs['uuid'] elif 'storage' in kwargs: # let's never use storage.storage internall...
kwargs: self.title = kwargs['storage_title'] if 'size' in kwargs: self.size = kwargs['size'] elif 'storage_size' in kwargs: self.size = kwargs['storage_size'] # send the rest to super._reset filtered_kwargs = dict( (key, val) for key, val in kwargs.items() if key not in ['uuid', 'storage', 'title', 'storage_title', 'si...
def save(self): """ Save (modify) the storage to the API. Note: only size and title are updateable fields. """ res = self.cloud_manager._modify_storage(self, self.size, self.title) self._reset(**res['storage'])
def to_dict(self): """ Return a dict that can be serialised to JSON and sent to UpCloud's API. Uses the convenience attribute `os` for determining `action` and `storage` fields. """ body = { 'tier': self.tier, 'title': self.title, 'size': self.size, } # optionals if hasattr(self, 'address') and self.address: body['addr...
def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches an album by given ID. :param album_id: the album ID. :type album_id: str :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#albums-album_id`. ''' url = 'https://api.kkbox.com/v1....
def lookup(self): """ Prints name, author, size and age """ print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author, self.size, self.age)
def _get_max_page(self, url): """ Open url and return amount of pages """ html = requests.get(url).text pq = PyQuery(html) try: tds = int(pq("h2").text().split()[-1]) if tds % 25: return tds / 25 + 1 return tds / 25 except ValueError: raise ValueError("No results found!")
def build(self, update=True): """ Build and return url. Also update max_page. """ ret = self.base + self.query page = "".join(("/", str(self.page), "/")) if self.category: category = " category:" + self.category else: category = "" if self.order: order = "".join(("?field=", self.order[0], "&sorder=", self.order[1])) el...
def build(self, update=True): """ Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path """ query_str = "?page={}".format(self.page) if self.order: query_str += "".join(("&field=", self.order[0...
def _items(self): """ Parse url and yield namedtuple Torrent for every torrent on page """ torrents = map(self._get_torrent, self._get_rows()) for t in torrents: yield t
def _get_torrent(self, row): """ Parse row into namedtuple """ td = row("td") name = td("a.cellMainLink").text() name = name.replace(" . ", ".").replace(" .", ".") author = td("a.plain").text() verified_author = True if td(".lightgrey>.ka-verify") else False category = td("span").find("strong").find("a").eq(0).text() v...
td("a[data-download]").attr("href") td_centers = row("td.center") size = td_centers.eq(0).text() files = td_centers.eq(1).text() age = " ".join(td_centers.eq(2).text().split()) seed = td_centers.eq(3).text() leech = td_centers.eq(4).text() return Torrent(name, author, verified_author, category, size, files, age, seed, ...
def _get_rows(self): """ Return all rows on page """ html = requests.get(self.url.build()).text if re.search('did not match any documents', html): return [] pq = PyQuery(html) rows = pq("table.data").find("tr") return map(rows.eq, range(rows.size()))[1:]
def pages(self, page_from, page_to): """ Yield torrents in range from page_from to page_to """ if not all([page_from < self.url.max_page, page_from > 0, page_to <= self.url.max_page, page_to > page_from]): raise IndexError("Invalid page numbers") size = (page_to + 1) - page_from threads = ret = [] page_list = range(pag...
function that fetch page for list of torrents """ res = self.page(page_list[pos]).list() locks[pos].acquire() ret.extend(res) if pos != size-1: locks[pos+1].release() threads = [threading.Thread(target=t_function, args=(i,)) for i in range(size)] for thread in threads: thread.start() for thread in threads: thread.join(...