code stringlengths 1 18.2k |
|---|
def get_party_address(party_token): """ Returns the address (`'IP:port'` string) of the party server. To generate a `party_token`: ``` from agarnet.utils import find_server _, token = find_server(mode='party') ``` Makes a request to http://m.agar.io/getToken to get the address. """ opener = urllib.request.build_opener(... |
def create_lines(self, draw, n_line, width, height): '''绘制干扰线''' line_num = randint(n_line[0], n_line[1]) # 干扰线条数 for i in range(line_num): # 起始点 begin = (randint(0, width), randint(0, height)) # 结束点 end = (randint(0, width), randint(0, height)) draw.line([begin, end], fill=(0, 0, 0)) |
def create_points(self, draw, point_chance, width, height): '''绘制干扰点''' chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100] for w in range(width): for h in range(height): tmp = randint(0, 100) if tmp > 100 - chance: draw.point((w, h), fill=(0, 0, 0)) |
def call_out(command): """ Run the given command (with shell=False) and return a tuple of (int returncode, str output). Strip the output of enclosing whitespace. """ # start external command process p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # get outputs out, _ = p.communicate() retu... |
def check_call_out(command): """ Run the given command (with shell=False) and return the output as a string. Strip the output of enclosing whitespace. If the return code is non-zero, throw GitInvocationError. """ # start external command process p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PI... |
def _dict_to_map_str_str(self, d): """ Thrift requires the params and headers dict values to only contain str values. """ return dict(map( lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)), d.iteritems() )) |
def suppress_stdout(): """ Context manager that suppresses stdout. Examples: >>> with suppress_stdout(): ... print('Test print') >>> print('test') test """ save_stdout = sys.stdout sys.stdout = DevNull() yield sys.stdout = save_stdout |
def get_domain_name(url): """ Extract a domain name from the url (without subdomain). Args: url (str): Url. Returns: str: Domain name. Raises: DomainNotMatchedError: If url is wrong. Examples: >>> get_domain_name('https://vod.tvp.pl/video/') 'tvp.pl' >>> get_domain_name('https://vod') Traceback (most recent call last):... |
def clean_video_data(_data): """ Clean video data: -> cleans title -> ... Args: _data (dict): Information about the video. Returns: dict: Refined video data. """ data = _data.copy() # TODO: fix this ugliness title = data.get('title') if title: data['title'] = clean_title(title) return data |
def clean_title(title): """ Clean title -> remove dates, remove duplicated spaces and strip title. Args: title (str): Title. Returns: str: Clean title without dates, duplicated, trailing and leading spaces. """ date_pattern = re.compile(r'\W*' r'\d{1,2}' r'[/\-.]' r'\d{1,2}' r'[/\-.]' r'(?=\d*)(?:.{4}|.{2})' r'\W*') ti... |
def get_ext(url): """ Extract an extension from the url. Args: url (str): String representation of a url. Returns: str: Filename extension from a url (without a dot), '' if extension is not present. """ parsed = urllib.parse.urlparse(url) root, ext = os.path.splitext(parsed.path) return ext.lstrip('.') |
def delete_duplicates(seq): """ Remove duplicates from an iterable, preserving the order. Args: seq: Iterable of various type. Returns: list: List of unique objects. """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] |
def joinOn(self, model, onIndex): """ Performs an eqJoin on with the given model. The resulting join will be accessible through the models name. """ return self._joinOnAsPriv(model, onIndex, model.__name__) |
def joinOnAs(self, model, onIndex, whatAs): """ Like `joinOn` but allows setting the joined results name to access it from. Performs an eqJoin on with the given model. The resulting join will be accessible through the given name. """ return self._joinOnAsPriv(model, onIndex, whatAs) |
def _joinOnAsPriv(self, model, onIndex, whatAs): """ Private method for handling joins. """ if self._join: raise Exception("Already joined with a table!") self._join = model self._joinedField = whatAs table = model.table self._query = self._query.eq_join(onIndex, r.table(table)) return self |
def orderBy(self, field, direct="desc"): """ Allows for the results to be ordered by a specific field. If given, direction can be set with passing an additional argument in the form of "asc" or "desc" """ if direct == "desc": self._query = self._query.order_by(r.desc(field)) else: self._query = self._query.order_by(r.a... |
def offset(self, value): """ Allows for skipping a specified number of results in query. Useful for pagination. """ self._query = self._query.skip(value) return self |
def limit(self, value): """ Allows for limiting number of results returned for query. Useful for pagination. """ self._query = self._query.limit(value) return self |
def fetch(self): """ Fetches the query and then tries to wrap the data in the model, joining as needed, if applicable. """ returnResults = [] results = self._query.run() for result in results: if self._join: # Because we can tell the models to ignore certian fields, # through the protectedItems blacklist, we can nest m... |
def coerce_put_post(request): """ Django doesn't particularly understand REST. In case we send data over PUT, Django won't actually look at the data and load it. We need to twist its arm here. The try/except abominiation here is due to a bug in mod_python. This should fix it. """ if request.method == "PUT": # Bug fix: ... |
field which is set # the first time _load_post_and_files is called (both by wsgi.py and # modpython.py). If it's set, the request has to be 'reset' to redo # the query value parsing in POST mode. if hasattr(request, '_post'): del request._post del request._files try: request.method = "POST" request._load_post_and_files... |
def loader_for_type(self, ctype): """ Gets a function ref to deserialize content for a certain mimetype. """ for loadee, mimes in Mimer.TYPES.iteritems(): for mime in mimes: if ctype.startswith(mime): return loadee |
def content_type(self): """ Returns the content type of the request in all cases where it is different than a submitted form - application/x-www-form-urlencoded """ type_formencoded = "application/x-www-form-urlencoded" ctype = self.request.META.get('CONTENT_TYPE', type_formencoded) if type_formencoded in ctype: return... |
def translate(self): """ Will look at the `Content-type` sent by the client, and maybe deserialize the contents into the format they sent. This will work for JSON, YAML, XML and Pickle. Since the data is not just key-value (and maybe just a list), the data will be placed on `request.data` instead, and the handler will ... |
around. self.request.POST = self.request.PUT = dict() except (TypeError, ValueError): # This also catches if loadee is None. raise MimerDataException else: self.request.data = None return self.request |
def getsteps(levels, tagmax): """ Returns a list with the max number of posts per "tagcloud level" """ ntw = levels if ntw < 2: ntw = 2 steps = [(stp, 1 + (stp * int(math.ceil(tagmax * 1.0 / ntw - 1)))) for stp in range(ntw)] # just to be sure~ steps[-1] = (steps[-1][0], tagmax+1) return steps |
def build(site, tagdata): """ Returns the tag cloud for a list of tags. """ tagdata.sort() # we get the most popular tag to calculate the tags' weigth tagmax = 0 for tagname, tagcount in tagdata: if tagcount > tagmax: tagmax = tagcount steps = getsteps(site.tagcloud_levels, tagmax) tags = [] for tagname, tagcount in ta... |
def getquery(query): 'Performs a query and get the results.' try: conn = connection.cursor() conn.execute(query) data = conn.fetchall() conn.close() except: data = list() return data |
def cloudata(site): """ Returns a dictionary with all the tag clouds related to a site. """ # XXX: this looks like it can be done via ORM tagdata = getquery(""" SELECT feedjack_post.feed_id, feedjack_tag.name, COUNT(*) FROM feedjack_post, feedjack_subscriber, feedjack_tag, feedjack_post_tags WHERE feedjack_post.feed_id... |
def getcloud(site, feed_id=None): """ Returns the tag cloud for a site or a site's subscriber. """ cloudict = fjcache.cache_get(site.id, 'tagclouds') if not cloudict: cloudict = cloudata(site) fjcache.cache_set(site, 'tagclouds', cloudict) # A subscriber's tag cloud has been requested. if feed_id: feed_id = int(feed_id... |
def extract_stations(page): '''Extract bus stations from routine page. :param page: crawled page. ''' stations = [_(station.value) for station in page('.stateName')] return { 'terminal': { stations[0]: list(reversed(stations)), stations[-1]: stations }, 'stations': stations } |
def extract_current_routine(page, stations): '''Extract current routine information from page. :param page: crawled page. :param stations: bus stations list. See `~extract_stations`. ''' current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text()) if not current_routines: return terminal_station = stations['stations... |
def extract_bus_routine(page): '''Extract bus routine information from page. :param page: crawled page. ''' if not isinstance(page, pq): page = pq(page) stations = extract_stations(page) return { # Routine name. 'name': extract_routine_name(page), # Bus stations. 'stations': stations, # Current routine. 'current': extr... |
def validate(self): """ Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. """ validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt validation_scope = {} exec(validation_code, validation_scope) # Store the result in th... |
ValidationError(error.format(compare_against_benchmark.callable.__name__, self.callable.__name__, compare_result, validation_scope['validation_result'])) |
def summarize(group, fs=None, include_source=True): """ Tabulate and write the results of ComparisonBenchmarks to a file or standard out. :param str group: name of the comparison group. :param fs: file-like object (Optional) """ _line_break = '{0:-<120}\n'.format('') tests = sorted(ComparisonBenchmark.groups[group], ke... |
as f: f.write(log.getvalue()) elif fs is None: print(log.getvalue()) else: try: fs.write(log.getvalue()) except AttributeError as e: print(e) |
def _grabData(self, key): """ Tries to find the existing document in the database, if it is found, then the objects _data is set to that document, and this returns `True`, otherwise this will return `False` :param key: The primary key of the object we're looking for :type key: Str :return: True if a document was found,... |
def _get(self, item): """ Helper function to keep the __getattr__ and __getitem__ calls KISSish """ if item not in object.__getattribute__(self, "_protectedItems") \ and item[0] != "_": data = object.__getattribute__(self, "_data") if item in data: return data[item] return object.__getattribute__(self, item) |
def _set(self, item, value): """ Helper function to keep the __setattr__ and __setitem__ calls KISSish Will only set the objects _data if the given items name is not prefixed with _ or if the item exists in the protected items List. """ if item not in object.__getattribute__(self, "_protectedItems") \ and item[0] != "_... |
def fromRawEntry(cls, **kwargs): """ Helper function to allow wrapping existing data/entries, such as those returned by collections. """ id = kwargs["id"] kwargs.pop("id") what = cls(**kwargs) what._new = False what.id = id return what |
def create(cls, id=None, **kwargs): """ Similar to new() however this calls save() on the object before returning it. """ what = cls(**kwargs) if id: setattr(what, cls.primaryKey, id) what.save() return what |
def save(self): """ If an id exists in the database, we assume we'll update it, and if not then we'll insert it. This could be a problem with creating your own id's on new objects, however luckily, we keep track of if this is a new object through a private _new variable, and use that to determine if we insert or update... |
def delete(self): """ Deletes the current instance. This assumes that we know what we're doing, and have a primary key in our data already. If this is a new instance, then we'll let the user know with an Exception """ if self._new: raise Exception("This is a new object, %s not in data, \ indicating this entry isn't sto... |
def add_edge(self, node1_name, node2_name, edge_length=DEFAULT_EDGE_LENGTH): """ Adds a new edge to the current tree with specified characteristics Forbids addition of an edge, if a parent node is not present Forbids addition of an edge, if a child node already exists :param node1_name: name of the parent node, to whic... |
def __get_node_by_name(self, name): """ Returns a first TreeNode object, which name matches the specified argument :raises: ValueError (if no node with specified name is present in the tree) """ try: for entry in filter(lambda x: x.name == name, self.nodes()): return entry except StopIteration: raise ValueError("Attemp... |
def __has_edge(self, node1_name, node2_name, account_for_direction=True): """ Returns a boolean flag, telling if a tree has an edge with two nodes, specified by their names as arguments If a account_for_direction is specified as True, the order of specified node names has to relate to parent - child relation, otherwise... |
def has_edge(self, node1_name, node2_name, account_for_direction=True): """ Proxies a call to the __has_edge method """ return self.__has_edge(node1_name=node1_name, node2_name=node2_name, account_for_direction=account_for_direction) |
def get_distance(self, node1_name, node2_name): """ Returns a length of an edge / path, if exists, from the current tree :param node1_name: a first node name in current tree :param node2_name: a second node name in current tree :return: a length of specified by a pair of vertices edge / path :rtype: `Number` :raises: V... |
def __get_v_tree_consistent_leaf_based_hashable_multicolors(self): """ Internally used method, that recalculates VTree-consistent sets of leaves in the current tree """ result = [] nodes = deque([self.__root]) while len(nodes) > 0: current_node = nodes.popleft() children = current_node.children nodes.extend(children) i... |
def __update_consistent_multicolors(self): """ Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology """ v_t_consistent_multicolors = self.__get_v_tree_consistent_leaf_based_hashable_multicolors() hashed_vtree_consistent_leaves_multicolors = {mc.hashable_representa... |
def append(self, node_name, tree, copy=False): """ Append a specified tree (represented by a root TreeNode element) to the node, specified by its name :param copy: a flag denoting if the appended tree has to be added as is, or is the deepcopy of it has to be used :type copy: Boolean :raises: ValueError (if no node with... |
def export(self, hashVal=None, hashPath=None, tags=None, galleries=None): """ The export function needs to: - Move source image to asset folder - Rename to guid.ext - Save thumbnail, small, and image versions """ hashVal = hashVal or self.hash hashPath = hashPath or self.parent / hashVal + self.ext source = hashPath.re... |
n[0], self.source.name.replace(hashVal, '_' * i + hashVal)) workImage.save(ROOT + getattr(self, n[0]).name) else: setattr(self, n[0], self.source) self.generateThumbnail() for gal in galleries: g = Gallery.objects.get(pk=int(gal)) g.images.add(self) self.tagArtist() for tagName in tags: tag = Tag.objects.get_or_create(... |
def generateThumbnail(self): """Generates a square thumbnail""" image = pilImage.open(ROOT / self.source.name) box, width, height = cropBox(self.width, self.height) # Resize image.thumbnail((width, height), pilImage.ANTIALIAS) # Crop from center box = cropBox(*image.size)[0] image = image.crop(box) # save self.thumbnai... |
def export(self, hashVal, hashPath, tags=None, galleries=None): """ The export function needs to: - Move source image to asset folder - Rename to guid.ext - Save thumbnail, video_thumbnail, and MP4 versions. If the source is already h264, then only transcode the thumbnails """ self.source = hashPath.replace('\\', '/').... |
def generateThumbnail(self): """Generates a square thumbnail""" source = ROOT / self.source.name thumbnail = source.parent / '_{}.jpg'.format(source.namebase) # -- Save thumbnail and put into queue poster = source.parent / '__{}.jpg'.format(source.namebase) cmd = [FROG_FFMPEG, '-i', str(source), '-ss', '1', '-vframes',... |
def reload(*command, ignore_patterns=[]): """Reload given command""" path = "." sig = signal.SIGTERM delay = 0.25 ignorefile = ".reloadignore" ignore_patterns = ignore_patterns or load_ignore_patterns(ignorefile) event_handler = ReloadEventHandler(ignore_patterns) reloader = Reloader(command, signal) observer = Observe... |
def reload_me(*args, ignore_patterns=[]): """Reload currently running command with given args""" command = [sys.executable, sys.argv[0]] command.extend(args) reload(*command, ignore_patterns=ignore_patterns) |
def parse_data_string(data_string): """ Parses a string assumed to contain gene order data, retrieving information about fragment type, gene order, blocks names and their orientation First checks if gene order termination signs are present. Selects the earliest one. Checks that information preceding is not empty and co... |
= data_string.strip() linear_terminator_index = data_string.index("$") if "$" in data_string else -1 circular_terminator_index = data_string.index("@") if "@" in data_string else -1 if linear_terminator_index < 0 and circular_terminator_index < 0: raise ValueError("Invalid data string. No chromosome termination sign ($... |
genomic blocks are separated between each other by the space character # ############################################################################################### split_data = data.split() blocks = [] for block in split_data: ########################################################################################... |
def __assign_vertex_pair(block): """ Assigns usual BreakpointGraph type vertices to supplied block. Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation. :param block: information about a genomic block to create a pair of vertices for in a format of ( ``+`` | ``-``, block_na... |
value in tags: head.add_tag(tag, value) tail.add_tag(tag, value) return (tail, head) if sign == "+" else (head, tail) |
def get_edges_from_parsed_data(parsed_data): """ Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph` In case supplied fragment is linear (``$``) special artificial verti... |
############################################################################################### # # if we parse a circular genomic fragment we must introduce an additional pair of vertices (edge) # that would connect two outer most vertices in the vertex list, thus connecting fragment extremities # ####################... |
BGVertex.get_vertex_name_root(vertices[1].name)) for tag, value in vertices[1].tags]) left_iv_root_name = BGVertex.get_vertex_name_root(vertices[2].name) vertices = vertices[2:] else: left_iv_tags = [] left_iv_root_name = vertices[0].name if vertices[-1].is_repeat_vertex: right_iv_tags = sorted( [(tag, value) if tag !=... |
def get_breakpoint_graph(stream, merge_edges=True): """ Taking a file-like object transforms supplied gene order data into the language of :param merge_edges: a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not :type merge_edges: ``bool`` :param stream: any iterable object where ... |
(before EOF or next genome declaration) will be attributed to current genome # ############################################################################################### current_genome = GRIMMReader.parse_genome_declaration_string(data_string=line) fragment_data = {} elif GRIMMReader.is_comment_string(data_string=... |
def get_blocks_in_grimm_from_breakpoint_graph(bg): """ :param bg: a breakpoint graph, that contians all the information :type bg: ``bg.breakpoint_graph.BreakpointGraph`` :return: list of strings, which represent genomes present in breakpoint graph as orders of blocks and is compatible with GRIMM format """ result = [] ... |
def from_json(cls, data, json_schema_class=None): """ JSON deserialization method that retrieves a genome instance from its json representation If specific json schema is provided, it is utilized, and if not, a class specific is used """ schema = cls.json_schema if json_schema_class is None else json_schema_class() ret... |
def send_file(request, filename, content_type='image/jpeg'): """ Send a file through Django without loading the whole file into memory at once. The FileWrapper will turn the file object into an iterator for chunks of 8KB. """ wrapper = FixedFileWrapper(file(filename, 'rb')) response = HttpResponse(wrapper, content_type... |
def send_zipfile(request, fileList): """ Create a ZIP file on disk and transmit it in chunks of 8KB, without loading the whole file into memory. A similar approach can be used for large dynamic PDF files. """ temp = tempfile.TemporaryFile() archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) for artist,files in ... |
def enable(): """ Enable all benchmarking. """ Benchmark.enable = True ComparisonBenchmark.enable = True BenchmarkedFunction.enable = True BenchmarkedClass.enable = True |
def disable(): """ Disable all benchmarking. """ Benchmark.enable = False ComparisonBenchmark.enable = False BenchmarkedFunction.enable = False BenchmarkedClass.enable = False |
def from_json(cls, data, json_schema_class=None): """ This class overwrites the from_json method thus, making sure, that if `from_json` is called from this class instance, it will provide its JSON schema as a default one """ json_schema = cls.json_schema if json_schema_class is None else json_schema_class() return supe... |
def name(self): """ access to classic name attribute is hidden by this property """ return self.NAME_SEPARATOR.join([super(InfinityVertex, self).name, self.NAME_SUFFIX]) |
def from_json(cls, data, json_schema_class=None): """ This class overwrites the from_json method, thus making sure that if `from_json` is called from this class instance, it will provide its JSON schema as a default one""" schema = cls.json_schema if json_schema_class is None else json_schema_class() return super(Infin... |
def name(self): """ access to classic name attribute is hidden by this property """ return self.NAME_SEPARATOR.join([super(TaggedVertex, self).name] + self.get_tags_as_list_of_strings()) |
def add_tag(self, tag, value): """ as tags are kept in a sorted order, a bisection is a fastest way to identify a correct position of or a new tag to be added. An additional check is required to make sure w don't add duplicates """ index = bisect_left(self.tags, (tag, value)) contains = False if index < len(self.tags):... |
def remove_tag(self, tag, value, silent_fail=False): """ we try to remove supplied pair tag -- value, and if does not exist outcome depends on the silent_fail flag """ try: self.tags.remove((tag, value)) except ValueError as err: if not silent_fail: raise err |
def merge(cls, edge1, edge2): """ Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge` Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge. Accounts for subclassing. :param edge1: first out... |
same vertices") elif not forward and edge1.vertex2 != edge2.vertex1: raise ValueError("Edges to be merged do not connect same vertices") return cls(vertex1=edge1.vertex1, vertex2=edge1.vertex2, multicolor=edge1.multicolor + edge2.multicolor) |
def colors_json_ids(self): """ A proxy property based access to vertices in current edge When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors, taking into account their multiplicity, are referenced by their json_ids. """ return [color.json_id if hasattr(color, ... |
def _get_connection_from_url(self, url, timeout, **kwargs): """Returns a connection object given a string url""" url = self._decode_url(url, "") if url.scheme == 'http' or url.scheme == 'https': return HttpConnection(url.geturl(), timeout=timeout, **kwargs) else: if sys.version_info[0] > 2: raise ValueError("Thrift tra... |
def new_log_level(level, name, logger_name=None): """ Quick way to create a custom log level that behaves like the default levels in the logging module. :param level: level number :param name: level name :param logger_name: optional logger name """ @CustomLogLevel(level, name, logger_name) def _default_template(logger,... |
def userToJson(user): """Returns a serializable User dict :param user: User to get info for :type user: User :returns: dict """ obj = { 'id': user.id, 'username': user.username, 'name': user.get_full_name(), 'email': user.email, } return obj |
def commentToJson(comment): """Returns a serializable Comment dict :param comment: Comment to get info for :type comment: Comment :returns: dict """ obj = { 'id': comment.id, 'comment': comment.comment, 'user': userToJson(comment.user), 'date': comment.submit_date.isoformat(), } return obj |
def getPutData(request): """Adds raw post to the PUT and DELETE querydicts on the request so they behave like post :param request: Request object to add PUT/DELETE to :type request: Request """ dataDict = {} data = request.body for n in urlparse.parse_qsl(data): dataDict[n[0]] = n[1] setattr(request, 'PUT', dataDict) s... |
def getHashForFile(f): """Returns a hash value for a file :param f: File to hash :type f: str :returns: str """ hashVal = hashlib.sha1() while True: r = f.read(1024) if not r: break hashVal.update(r) f.seek(0) return hashVal.hexdigest() |
def uniqueID(size=6, chars=string.ascii_uppercase + string.digits): """A quick and dirty way to get a unique string""" return ''.join(random.choice(chars) for x in xrange(size)) |
def getObjectsFromGuids(guids): """Gets the model objects based on a guid list :param guids: Guids to get objects for :type guids: list :returns: list """ guids = guids[:] img = list(Image.objects.filter(guid__in=guids)) vid = list(Video.objects.filter(guid__in=guids)) objects = img + vid sortedobjects = [] if objects:... |
def getClientIP(request): """Returns the best IP address found from the request""" forwardedfor = request.META.get('HTTP_X_FORWARDED_FOR') if forwardedfor: ip = forwardedfor.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip |
def __discoverPlugins(): """ Discover the plugin classes contained in Python files, given a list of directory names to scan. Return a list of plugin classes. """ for app in settings.INSTALLED_APPS: if not app.startswith('django'): module = __import__(app) moduledir = path.Path(module.__file__).parent plugin = moduledir... |
def append(self, val): """Appends the object to the end of the values list. Will also set the value to the first item in the values list :param val: Object to append :type val: primitive """ self.values.append(val) self.value = self.values[0] |
def asDict(self): """Returns a serializable object""" return { 'isError': self.isError, 'message': self.message, 'values': self.values, 'value': self.value, } |
def auth(self, password): """Request for authentication in a password-protected Redis server. Redis can be instructed to require a password before allowing clients to execute commands. This is done using the ``requirepass`` directive in the configuration file. If the password does not match, an :exc:`~tredis.exceptions... |
def info(self, section=None): """The INFO command returns information and statistics about the server in a format that is simple to parse by computers and easy to read by humans. The optional parameter can be used to select a specific section of information: - server: General information about the Redis server - client... |
:param str section: Optional :return: dict """ cmd = [b'INFO'] if section: cmd.append(section) return self._execute(cmd, format_callback=common.format_info_response) |
def select(self, index=0): """Select the DB with having the specified zero-based numeric index. New connections always use DB ``0``. :param int index: The database to select :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError` :raises: :exc:`~tredis.exceptions.InvalidClusterCommand` """ if self._clustering: raise... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.