code
stringlengths
1
18.2k
def get_project(self, project_id): """ Get project info """ try: result = self._request('/getproject/', {'projectid': project_id}) return TildaProject(**result) except NetworkError: return []
def get_project_export(self, project_id): """ Get project info for export """ try: result = self._request('/getprojectexport/', {'projectid': project_id}) return TildaProject(**result) except NetworkError: return []
def get_pages_list(self, project_id): """ Get pages list """ try: result = self._request('/getpageslist/', {'projectid': project_id}) return [TildaPage(**p) for p in result] except NetworkError: return []
def get_page(self, page_id): """ Get short page info and body html code """ try: result = self._request('/getpage/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
def get_page_full(self, page_id): """ Get full page info and full html code """ try: result = self._request('/getpagefull/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
def get_page_export(self, page_id): """ Get short page info for export and body html code """ try: result = self._request('/getpageexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
def get_page_full_export(self, page_id): """ Get full page info for export and body html code """ try: result = self._request('/getpagefullexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
def fullsplit(path, result=None, base_path=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if base_path: path = path.replace(base_path, '') if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: ret...
def _flatten(l): """helper to flatten a list of lists """ res = [] for sublist in l: if isinstance(sublist, whaaaaat.Separator): res.append(sublist) else: for item in sublist: res.append(item) return res
def handle(app): # TODO: for this to work properly we need a generator registry # generator, lifecycle etc. # list of tuples (label, value) # TODO customize & use own style default_choices = [ { 'name': 'Install a generator', 'value': 'install' }, { 'name': 'Find some help', 'value': 'help' }, { 'name': 'Get me out of ...
(generatorList.length) { defaultChoices.unshift({ name: 'Update your generators', value: 'update' }); } ''' # app.insight.track('yoyo', 'home'); generator_list = [{'name': g.title(), 'value': {'name': g, 'method': 'run'}} for g in app.generators] choices = _flatten([ whaaaaat.Separator('Run a generator'), generator_lis...
def read_thrift(file_obj, ttype): """Read a thrift structure from the given fo.""" from thrift.transport.TTransport import TFileObjectTransport, TBufferedTransport starting_pos = file_obj.tell() # set up the protocol chain ft = TFileObjectTransport(file_obj) bufsize = 2 ** 16 # for accelerated reading ensure that we wr...
def write_thrift(fobj, thrift): """Write binary compact representation of thiftpy structured object Parameters ---------- fobj: open file-like object (binary mode) thrift: thriftpy object to write Returns ------- Number of bytes written """ t0 = fobj.tell() pout = TCompactProtocol(fobj) try: thrift.write(pout) fail = F...
def thrift_print(structure, offset=0): """ Handy recursive text ouput for thrift structures """ if not is_thrift_item(structure): return str(structure) s = str(structure.__class__) + '\n' for key in dir(structure): if key.startswith('_') or key in ['thrift_spec', 'read', 'write', 'default_spec', 'validate']: continue s...
def insert_load_command(target_path, library_install_name): """ Inserts a new LC_LOAD_DYLIB load command into the target Mach-O header. Note: the target file will be overwritten. Consider backing it up first before calling this function. Returns True if everything is OK. Otherwise rises an exception. """ def patchHeade...
def macho_dependencies_list(target_path, header_magic=None): """ Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templates ...
if needed if isinstance(header_magic, basestring): header_magic = _MH_MAGIC_from_string(header_magic) macho = MachO(target_path) # Obtain a list of headers for the required magic value (if any) suggestions = filter(lambda t: t.header.magic == header_magic or # just add all headers if user didn't specifiy the magic head...
decodeLoadCommandData(data), list) def weakReferencesFromHeader(h): list = filter(lambda (lc,cmd,data): lc.cmd == LC_LOAD_WEAK_DYLIB, h.commands) return map(lambda (lc,cmd,data): decodeLoadCommandData(data), list) strongRefs = strongReferencesFromHeader(header) weakRefs = weakReferencesFromHeader(header) return MachODe...
def insert_load_command_into_header(header, load_command): """ Inserts the given load command into the header and adjust its size. """ lc, cmd, path = load_command header.commands.append((lc, cmd, path)) header.header.ncmds += 1 header.changedHeaderSizeBy(lc.cmdsize)
def generate_dylib_load_command(header, libary_install_name): """ Generates a LC_LOAD_DYLIB command for the given header and a library install path. Note: the header must already contain at least one LC_LOAD_DYLIB command (see code comments). Returns a ready-for-use load_command in terms of macholib. """ # One can not ...
if (command.cmd == LC_LOAD_DYLIB) and isinstance(internal_cmd, dylib_command): lc = deepcopy(command) cmd = deepcopy(internal_cmd) break if not lc or not cmd: raise Exception("Invalid Mach-O file. I mean, there must be at least one LC_LOAD_DYLIB load command.") return None # Well, now we just replace everything with ou...
else 8 aligned_name = libary_install_name + (b'\x00' * (align - (len(libary_install_name) % align))) # So now we finally can say what size this load_command is lc.cmdsize = base + len(aligned_name) return (lc, cmd, aligned_name)
def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. Also validates that the username is not listed in ACCOUNTS_FORBIDDEN_USERNAMES list. """ try: get_user_model().objects.get( username__iexact=self.cleaned_data['username']) except get_user_model().DoesNotExist: pass else:...
def clean_email(self): """ Validate that the e-mail address is unique. """ if get_user_model().objects.filter( email__iexact=self.cleaned_data['email']): raise forms.ValidationError(_('This email is already in use. Please supply a different email.')) return self.cleaned_data['email']
def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password, first_name, last_name = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'], self.cleaned_data['first_name'], self.cleaned_data['last_name'],) new_user = get_user_mod...
def get_authenticate_header(self, request): """ If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any. """ authenticators = self.get_authenticators() if authenticators: return authenticators[0].authenticate_header(request)
def create_dir(dst): """create directory if necessary :param dst: """ directory = os.path.dirname(dst) if directory and not os.path.exists(directory): os.makedirs(directory)
def copy_wildcard(src_folder, dst_folder, glob): """copy """ create_dir(dst_folder) for sname in iglob(os.path.join(src_folder, glob)): rname = os.path.relpath(sname, src_folder) dname = os.path.join(dst_folder, rname) create_dir(dname) shutil.copy(sname, dname)
def copy_tpl(template_file, dst, template_vars): """This supports jinja2 templates. Please feel encouraged to use the template framework of your choosing. jinja2 docu: http://jinja.pocoo.org/docs/2.9/ :param template_file: :param dst: :param template_vars: dictionary containing key, values used in the template """ crea...
def recompute_table_revnums(self): ''' Recomputes the revnums for the csetLog table by creating a new table, and copying csetLog to it. The INTEGER PRIMARY KEY in the temp table auto increments as rows are added. IMPORTANT: Only call this after acquiring the lock `self.working_locker`. :return: ''' with self.conn.trans...
def check_for_maintenance(self): ''' Returns True if the maintenance worker should be run now, and False otherwise. :return: ''' numrevs = self.conn.get_one("SELECT count(revnum) FROM csetLog")[0] if numrevs >= SIGNAL_MAINTENACE_CSETS: return True return False
def add_cset_entries(self, ordered_rev_list, timestamp=False, number_forward=True): ''' Adds a list of revisions to the table. Assumes ordered_rev_list is an ordered based on how changesets are found in the changelog. Going forwards or backwards is dealt with by flipping the list :param ordered_cset_list: Order given f...
if not current_min or not current_max: current_min = 0 current_max = 0 direction = -1 start = current_min - 1 if number_forward: direction = 1 start = current_max + 1 ordered_rev_list = ordered_rev_list[::-1] insert_list = [ ( start + direction * count, rev, int(time.time()) if timestamp else -1 ) for count, rev in enu...
def _fill_in_range(self, parent_cset, child_cset, timestamp=False, number_forward=True): ''' Fills cset logs in a certain range. 'parent_cset' can be an int and in that case, we get that many changesets instead. If parent_cset is an int, then we consider that we are going backwards (number_forward is False) and we igno...
None csets_found = 0 clogs_seen = 0 final_rev = child_cset while not found_parent and clogs_seen < MAX_BACKFILL_CLOGS: clog_url = self.tuid_service.hg_url / self.config.hg.branch / 'json-log' / final_rev clog_obj = self._get_clog(clog_url) clog_csets_list = list(clog_obj['changesets']) for clog_cset in clog_csets_list[...
= clog_csets_list[-1]['node'][:12] if found_parent: self.add_cset_entries(csets_to_add, timestamp=timestamp, number_forward=number_forward) else: Log.warning( "Couldn't find the end of the request for {{request}}. " "Max number that can be requested through _fill_in_range is {{maxnum}}.", request={ 'parent_cset': paren...
def fill_backward_with_list(self, please_stop=None): ''' Expects requests of the tuple form: (parent_cset, timestamp) parent_cset can be an int X to go back by X changesets, or a string to search for going backwards in time. If timestamp is false, no timestamps will be added to the entries. :param please_stop: :return:...
def update_tip(self): ''' Returns False if the tip is already at the newest, or True if an update has taken place. :return: ''' clog_obj = self._get_clog(self.tuid_service.hg_url / self.config.hg.branch / 'json-log' / 'tip') # Get current tip in DB with self.conn.transaction() as t: _, newest_known_rev = self.get_tip(t...
clog_cset['node'][:12] if not csets_to_gather: if nodes_cset == newest_known_rev: found_newest_known = True break else: if csets_found >= csets_to_gather: found_newest_known = True break csets_found += 1 csets_to_add.append(nodes_cset) if not found_newest_known: # Get the next page clogs_seen += 1 final_rev = clog_cset...
def csetLog_maintenance(self, please_stop=None): ''' Handles deleting old csetLog entries and timestamping revisions once they pass the length for permanent storage for deletion later. :param please_stop: :return: ''' while not please_stop: try: # Wait until something signals the maintenance cycle # to begin (or end). ...
type(timestamp) != int or timestamp == -1: modified = True new_data.append((revnum, revision, int(time.time()))) else: new_data.append((revnum, revision, timestamp)) # Delete annotations at revisions with timestamps # that are too old. The csetLog entries will have # their timestamps reset here. new_data1 = [] annrevs_...
FROM annotations WHERE revision IN " + quote_set(annrevs_to_del) ) # Delete any overflowing entries new_data2 = new_data1 reved_all_data = all_data[::-1] deleted_data = reved_all_data[MAXIMUM_NONPERMANENT_CSETS:] delete_overflowing_revstart = None if len(deleted_data) > 0: _, delete_overflowing_revstart, _ = deleted_da...
or len(old_files) <= 0: still_exist = False # Update table and schedule a deletion if modified: with self.conn.transaction() as t: t.execute( "INSERT OR REPLACE INTO csetLog (revnum, revision, timestamp) VALUES " + sql_list( quote_set(cset_entry) for cset_entry in new_data2 ) ) if not deleted_data: continue Log.note("S...
def csetLog_deleter(self, please_stop=None): ''' Deletes changesets from the csetLog table and also changesets from the annotation table that have revisions matching the given changesets. Accepts lists of csets from self.deletions_todo. :param please_stop: :return: ''' while not please_stop: try: request = self.deletio...
= t.query( "SELECT revision FROM latestFileMod WHERE revision IN " + quote_set(csets_to_del) ).data existing_frontiers = [existing_frontiers[i][0] for i, _ in enumerate(existing_frontiers)] Log.note( "Deleting all annotations and changeset log entries with revisions in the list: {{csets}}", csets=csets_to_del ) if len(...
def DataClass(name, columns, constraint=None): """ Use the DataClass to define a class, but with some extra features: 1. restrict the datatype of property 2. restrict if `required`, or if `nulls` are allowed 3. generic constraints on object properties It is expected that this class become a real class (or be removed) i...
a Python datatype } :param constraint: a JSON query Expression for extra constraints (return true if all constraints are met) :return: The class that has been created """ columns = wrap( [ {"name": c, "required": True, "nulls": False, "type": object} if is_text(c) else c for c in columns ] ) slots = columns.name requir...
{{constraint_expr}} except Exception as e: return False def __init__(self, **kwargs): if not kwargs: return for s in {{slots}}: object.__setattr__(self, s, kwargs.get(s, {{defaults}}.get(s, None))) missed = {{required}}-set(kwargs.keys()) if missed: Log.error("Expecting properties {"+"{missed}}", missed=missed) illegal...
is other def __dict__(self): return {k: getattr(self, k) for k in {{slots}}} def items(self): return ((k, getattr(self, k)) for k in {{slots}}) def __copy__(self): _set = object.__setattr__ output = object.__new__({{class_name}}) {{assign}} return output def __iter__(self): return {{slots}}.__iter__() def __len__(self)...
+ v.__name__ for k, v in types.items())) + "}", "constraint_expr": Python[jx_expression(constraint)].to_python(), "constraint": value2json(constraint), }, ) output = _exec(code, name) register_data(output) return output
def sign(self, method, params): """Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate """ query_str = utils.percent_encode(params.items(), True) str_to_sign = "{0}&%2F&{1}".format( method, utils....
def getPathOfExecutable(executable): """ Returns the full path of the executable, or None if the executable can not be found. """ exe_paths = os.environ['PATH'].split(':') for exe_path in exe_paths: exe_file = os.path.join(exe_path, executable) if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK): return exe_fi...
def requireExecutables(executables): """ Check that all of the given executables are on the path. If at least one of them is not, exit the script and inform the user of the missing requirement(s). """ missingExecutables = [] for executable in executables: if getPathOfExecutable(executable) is None: missingExecutables.a...
def runCommandReturnOutput(cmd): """ Runs a shell command and return the stdout and stderr """ splits = shlex.split(cmd) proc = subprocess.Popen( splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode != 0: raise subprocess.CalledProcessError(stdout, stderr) retur...
def getYamlDocument(filePath): """ Return a yaml file's contents as a dictionary """ with open(filePath) as stream: doc = yaml.load(stream) return doc
def captureOutput(func, *args, **kwargs): """ Runs the specified function and arguments, and returns the tuple (stdout, stderr) as strings. """ stdout = sys.stdout sys.stdout = StringIO.StringIO() stderr = sys.stderr sys.stderr = StringIO.StringIO() try: func(*args, **kwargs) stdoutOutput = sys.stdout.getvalue() stderr...
def zipLists(*lists): """ Checks to see if all of the lists are the same length, and throws an AssertionError otherwise. Returns the zipped lists. """ length = len(lists[0]) for i, list_ in enumerate(lists[1:]): if len(list_) != length: msg = "List at index {} has length {} != {}".format( i + 1, len(list_), length) rai...
def getLinesFromLogFile(stream): """ Returns all lines written to the passed in stream """ stream.flush() stream.seek(0) lines = stream.readlines() return lines
def getFilePathsWithExtensionsInDirectory(dirTree, patterns, sort=True): """ Returns all file paths that match any one of patterns in a file tree with its root at dirTree. Sorts the paths by default. """ filePaths = [] for root, dirs, files in os.walk(dirTree): for filePath in files: for pattern in patterns: if fnmatch...
def performInDirectory(dirPath): """ Change the current working directory to dirPath before performing an operation, then restore the original working directory after """ originalDirectoryPath = os.getcwd() try: os.chdir(dirPath) yield finally: os.chdir(originalDirectoryPath)
def filenames(self): """Returns the filenames that this par2 file repairs.""" return [p.name for p in self.packets if isinstance(p, FileDescriptionPacket)]
def related_pars(self): """Returns a list of related par2 files (ones par2 will try to read from to find file recovery blocks). If this par2 file was a file-like object (like a StringIO) without an associated path, return []. Otherwise, the name of this file + associated files are returned.""" if not self.path: return ...
def _set_slots_to_null(self, cls): """ WHY ARE SLOTS NOT ACCESIBLE UNTIL WE ASSIGN TO THEM? """ if hasattr(cls, "__slots__"): for s in cls.__slots__: self.__setattr__(s, Null) for b in cls.__bases__: self._set_slots_to_null(b)
def main(): """Play Conway's Game of Life on the terminal.""" def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y LOAD_FACTOR = 9 # Smaller means more crowded. NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller means a bigger nudge. term = Terminal() width = te...
def cell_strings(term): """Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports. """ num_colors = term.number_of_colors if num_colors >= 16: funcs = term.on_bright_red, term.on_bright_green, term.on_bright_cyan elif num_colors >= 8: funcs = term.on_red, ...
def random_board(max_x, max_y, load_factor): """Return a random board with given max x and y coords.""" return dict(((randint(0, max_x), randint(0, max_y)), 0) for _ in xrange(int(max_x * max_y / load_factor)))
def clear(board, term, height): """Clear the droppings of the given board.""" for y in xrange(height): print term.move(y, 0) + term.clear_eol,
def draw(board, term, cells): """Draw a board to the terminal.""" for (x, y), state in board.iteritems(): with term.location(x, y): print cells[state],
def next_board(board, wrap): """Given a board, return the board one interation later. Adapted from Jack Diedrich's implementation from his 2012 PyCon talk "Stop Writing Classes" :arg wrap: A callable which takes a point and transforms it, for example to wrap to the other edge of the screen. Return None to remove a poin...
wrapped = wrap(point) if wrapped: new_board[wrapped] = state return new_board
def neighbors((x, y)): """Return the (possibly out of bounds) neighbors of a point.""" yield x + 1, y yield x - 1, y yield x, y + 1 yield x, y - 1 yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y + 1 yield x - 1, y - 1
def is_bored_of(self, board): """Return whether the simulation is probably in a loop. This is a stochastic guess. Basically, it detects whether the simulation has had the same number of cells a lot lately. May have false positives (like if you just have a screen full of gliders) or take awhile to catch on sometimes. I'...
def droit_d_accise(depense, droit_cn, consommation_cn, taux_plein_tva): """ Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat. """ return depense * ((1 + taux_plein_tva) * droit_cn) / (consommation_cn - (1 + taux_plein_tva) * droit_cn)
def add(self, value, timeout=None, force=False): """ :param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self """ with self.lock: if value is THREAD_STOP: # INSIDE THE lock S...
def push(self, value): """ SNEAK value TO FRONT OF THE QUEUE """ if self.closed and not self.allow_add_after_close: Log.error("Do not push to closed queue") with self.lock: self._wait_for_queue_space() if not self.closed: self.queue.appendleft(value) return self
def pop_message(self, till=None): """ RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE DUMMY IMPLEMENTATION FOR DEBUGGING """ if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") return Null, self.pop(till=till)
def _wait_for_queue_space(self, timeout=DEFAULT_WAIT_TIME): """ EXPECT THE self.lock TO BE HAD, WAITS FOR self.queue TO HAVE A LITTLE SPACE """ wait_time = 5 (DEBUG and len(self.queue) > 1 * 1000 * 1000) and Log.warning("Queue {{name}} has over a million items") now = time() if timeout != None: time_to_stop_waiting = n...
def pop_all(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ with self.lock: output = list(self.queue) self.queue.clear() return output
def pop_one(self): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if self.closed: return [THREAD_STOP] elif not self.queue: return None else: v =self.queue.pop() if v is THREAD_STOP: # SENDING A STOP INTO THE QUEUE IS ALSO AN OPTION self.closed.go() return v
def pop(self, till=None, priority=None): """ WAIT FOR NEXT ITEM ON THE QUEUE RETURN THREAD_STOP IF QUEUE IS CLOSED RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY :param till: A `Signal` to stop waiting and return None :return: A value, or a THREAD_STOP or None """ if till is not None and not isinstance(till, S...
def pop_all(self, priority=None): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: if not priority: priority = self.highest_entry() if priority: output = list(self.queue[priority].queue) self.queue[priority].queue.clear() return output
def pop_all_queues(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: for q in self.queue: output.extend(list(q.queue)) q.queue.clear() return output
def pop_one(self, priority=None): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if not priority: priority = self.highest_entry() if self.closed: return [THREAD_STOP] elif not self.queue: return None else: v =self.pop(priority=priority) if v is THREAD_STOP: # SENDING A STOP INTO THE QUEUE IS ALSO AN OPTION s...
def typed_encode(self, r): """ :param record: expecting id and value properties :return: dict with id and json properties """ try: value = r.get('value') if "json" in r: value = json2value(r["json"]) elif is_data(value) or value != None: pass else: from mo_logs import Log raise Log.error("Expecting every record given t...
_buffer) json = _buffer.build() return given_id, version, json except Exception as e: # THE PRETTY JSON WILL PROVIDE MORE DETAIL ABOUT THE SERIALIZATION CONCERNS from mo_logs import Log Log.error("Serialization of JSON problems", cause=e)
def weight(weights): """ RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS """ total = sum(weights) p = SEED.random() acc = 0 for i, w in enumerate(weights): acc += w / total if p < acc: return i return len(weights) - 1
def cipher_block (self, state): """Perform AES block cipher on input""" # PKCS7 Padding state=state+[16-len(state)]*(16-len(state))# Fails test if it changes the input with += self._add_round_key(state, 0) for i in range(1, self._Nr): self._sub_bytes(state) self._shift_rows(state) self._mix_columns(state, False) self._...
def decipher_block (self, state): """Perform AES block decipher on input""" if len(state) != 16: Log.error(u"Expecting block of 16") self._add_round_key(state, self._Nr) for i in range(self._Nr - 1, 0, -1): self._i_shift_rows(state) self._i_sub_bytes(state) self._add_round_key(state, i) self._mix_columns(state, True) s...
def dry_run(func): """Dry run: simulate sql execution.""" @wraps(func) def inner(dry_run, *args, **kwargs): ret = func(dry_run=dry_run, *args, **kwargs) if not dry_run: db.session.commit() else: db.session.rollback() return ret return inner
def tree(names): """Show the tree of the collection(s) specified.""" # query query = Collection.query if names: query = query.filter(Collection.name.in_(names)) else: query = query.filter(Collection.level == 1) # print tree tr = LeftAligned(traverse=AttributeTraversal()) for coll in query.all(): click.secho(tr(coll))
def path(name): """Print path to root.""" try: coll = Collection.query.filter(Collection.name == name).one() tr = LeftAligned( traverse=CollTraversalPathToRoot(coll.path_to_root().all())) click.echo(tr(coll)) except NoResultFound: raise click.UsageError('Collection {0} not found'.format(name))
def create(name, dry_run, verbose, query=None, parent=None): """Create new collection.""" if parent is not None: parent = Collection.query.filter_by(name=parent).one().id collection = Collection(name=name, dbquery=query, parent_id=parent) db.session.add(collection) if verbose: click.secho('New collection: {0}'.format(c...
def delete(name, dry_run, verbose): """Delete a collection.""" collection = Collection.query.filter_by(name=name).one() if verbose: tr = LeftAligned(traverse=AttributeTraversal()) click.secho(tr(collection), fg='red') db.session.delete(collection)
def query(name): """Print the collection query.""" collection = Collection.query.filter_by(name=name).one() click.echo(collection.dbquery)
def attach(names, parent, dry_run, verbose): """Attach collection(s) to a parent.""" parent = Collection.query.filter_by(name=parent).one() collections = Collection.query.filter(Collection.name.in_(names)).all() for collection in collections: collection.move_inside(parent.id) if verbose: click.secho( 'Collection "{0}" ...
def get_text(self, node): """Get node text representation.""" return click.style( repr(node), fg='green' if node.level > 1 else 'red' )
def get_children(self, node): """Get children.""" # if node in self.nodes: try: index = self.nodes.index(node) + 1 return [self.nodes[index]] except IndexError: return []
def cli_char(name, tibiadata, json): """Displays information about a Tibia character.""" name = " ".join(name) char = _fetch_and_parse(Character.get_url, Character.from_content, Character.get_url_tibiadata, Character.from_tibiadata, tibiadata, name) if json and char: print(char.to_json(indent=2)) return print(get_chara...
def cli_guild(name, tibiadata, json): """Displays information about a Tibia guild.""" name = " ".join(name) guild = _fetch_and_parse(Guild.get_url, Guild.from_content, Guild.get_url_tibiadata, Guild.from_tibiadata, tibiadata, name) if json and guild: print(guild.to_json(indent=2)) return print(get_guild_string(guild))
def cli_guilds(world, tibiadata, json): """Displays the list of guilds for a specific world""" world = " ".join(world) guilds = _fetch_and_parse(ListedGuild.get_world_list_url, ListedGuild.list_from_content, ListedGuild.get_world_list_url_tibiadata, ListedGuild.list_from_tibiadata, tibiadata, world) if json and guilds:...