code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
data = self.sock.recv(bufsize) if len(data) == 0: raise socket.error('no data to receive') self.recvbuf += data while contains_frame(self.recvbuf): frame, self.recvbuf = pop_frame(self.recvbuf) frame = self.apply_recv_hooks(frame, False) ...
def do_async_recv(self, bufsize)
Receive any completed frames from the socket. This function should only be called after a read event on a file descriptor.
3.754739
3.66283
1.025092
if self.handshake_sent: raise SSLError('can only enable SSL before handshake') self.secure = True self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
def enable_ssl(self, *args, **kwargs)
Transforms the regular socket.socket to an ssl.SSLSocket for secure connections. Any arguments are passed to ssl.wrap_socket: http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket
4.812591
4.581057
1.050542
''' Is the nonce one that was generated by this library using the provided secret? ''' nonce_components = nonce.split(':', 2) if not len(nonce_components) == 3: return False timestamp = nonce_components[0] salt = nonce_components[1] nonce_signature = nonce_components[2] calc...
def validate_nonce(nonce, secret)
Is the nonce one that was generated by this library using the provided secret?
3.481179
2.483219
1.401882
''' Calculate a partial digest that may be stored and used to authenticate future HTTP Digest sessions. ''' return md5.md5("%s:%s:%s" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest()
def calculate_partial_digest(username, realm, password)
Calculate a partial digest that may be stored and used to authenticate future HTTP Digest sessions.
5.474537
2.77177
1.975105
''' Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header in a 401 or 403 response. 'opaque' may be any value - it will be returned by the client. 'timestamp' will be incorporated and signed in the nonce - it may be retrieved from the client's authentication ...
def build_digest_challenge(timestamp, secret, realm, opaque, stale)
Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header in a 401 or 403 response. 'opaque' may be any value - it will be returned by the client. 'timestamp' will be incorporated and signed in the nonce - it may be retrieved from the client's authentication request usin...
5.343005
1.974676
2.705763
''' Calculates a value for the 'response' value of the client authentication request. Requires the 'partial_digest' calculated from the realm, username, and password. Either call it with a digest_response to use the values from an authentication request, or pass the individual parameters (i.e. to g...
def calculate_request_digest(method, partial_digest, digest_response=None, uri=None, nonce=None, nonce_count=None, client_nonce=None)
Calculates a value for the 'response' value of the client authentication request. Requires the 'partial_digest' calculated from the realm, username, and password. Either call it with a digest_response to use the values from an authentication request, or pass the individual parameters (i.e. to generate an a...
3.823184
2.185745
1.749145
''' Extract the timestamp from a Nonce. To be sure the timestamp was generated by this site, make sure you validate the nonce using validate_nonce(). ''' components = nonce.split(':',2) if not len(components) == 3: return None try: return float(components[0]) except Valu...
def get_nonce_timestamp(nonce)
Extract the timestamp from a Nonce. To be sure the timestamp was generated by this site, make sure you validate the nonce using validate_nonce().
6.724085
2.634063
2.552742
''' Generate a nonce using the provided timestamp, secret, and salt. If the salt is not provided, (and one should only be provided when validating a nonce) one will be generated randomly in order to ensure that two simultaneous requests do not generate identical nonces. ''' if not salt: ...
def calculate_nonce(timestamp, secret, salt=None)
Generate a nonce using the provided timestamp, secret, and salt. If the salt is not provided, (and one should only be provided when validating a nonce) one will be generated randomly in order to ensure that two simultaneous requests do not generate identical nonces.
4.35428
1.908109
2.281987
''' Builds an authorization request that may be sent as the value of the 'Authorization' header in an HTTP request. Either a digest_challenge object (as returned from parse_digest_challenge) or its required component parameters (nonce, realm, opaque) must be provided. The nonce_count should be...
def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None, realm=None, nonce=None, opaque=None, password=None, request_digest=None, client_nonce=None)
Builds an authorization request that may be sent as the value of the 'Authorization' header in an HTTP request. Either a digest_challenge object (as returned from parse_digest_challenge) or its required component parameters (nonce, realm, opaque) must be provided. The nonce_count should be the last us...
2.801033
1.921113
1.458026
''' Parse the parameters of a Digest response. The input is a comma separated list of token=(token|quoted-string). See RFCs 2616 and 2617 for details. Known issue: this implementation will fail if there are commas embedded in quoted-strings. ''' parts = parse_parts(digest_response_string, defa...
def parse_digest_response(digest_response_string)
Parse the parameters of a Digest response. The input is a comma separated list of token=(token|quoted-string). See RFCs 2616 and 2617 for details. Known issue: this implementation will fail if there are commas embedded in quoted-strings.
4.722504
2.62057
1.80209
''' Parses the value of a 'WWW-Authenticate' header. Returns an object with properties corresponding to each of the recognized parameters in the header. ''' if not is_digest_challenge(authentication_header): return None parts = parse_parts(authentication_header[7:], defaults={'algorithm...
def parse_digest_challenge(authentication_header)
Parses the value of a 'WWW-Authenticate' header. Returns an object with properties corresponding to each of the recognized parameters in the header.
3.684374
2.798176
1.316706
for v1, v2, key, data in self.bg.edges(nbunch=nbunch, data=True, keys=True): bgedge = BGEdge(vertex1=v1, vertex2=v2, multicolor=data["attr_dict"]["multicolor"], data=data["attr_dict"]["data"]) if not keys: yield bgedge else...
def __edges(self, nbunch=None, keys=False)
Iterates over edges in current :class:`BreakpointGraph` instance. Returns a generator over the edges in current :class:`BreakpointGraph` instance producing instances of :class:`bg.edge.BGEdge` instances wrapping around information in underlying MultiGraph object. :param nbunch: a vertex to iterate ove...
3.615063
3.028533
1.193668
for entry in self.__edges(nbunch=nbunch, keys=keys): yield entry
def edges(self, nbunch=None, keys=False)
Iterates over edges in current :class:`BreakpointGraph` instance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__edges`. :param nbunch: a vertex to iterate over edges outgoing from, if not provided,iteration over all edges is performed. :type nbuch: any hashable python object ...
5.748983
6.168074
0.932055
self.__add_bgedge(BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor, data=data), merge=merge)
def add_edge(self, vertex1, vertex2, multicolor, merge=True, data=None)
Creates a new :class:`bg.edge.BGEdge` object from supplied information and adds it to current instance of :class:`BreakpointGraph`. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method. :param vertex1: first vertex instance out of two in current :class:`BreakpointGraph` ...
4.451097
2.807169
1.585618
if bgedge.vertex1 in self.bg and bgedge.vertex2 in self.bg[bgedge.vertex1] and merge: key = min(self.bg[bgedge.vertex1][bgedge.vertex2].keys()) self.bg[bgedge.vertex1][bgedge.vertex2][key]["attr_dict"]["multicolor"] += bgedge.multicolor self.bg[bgedge.vertex1][bgedge...
def __add_bgedge(self, bgedge, merge=True)
Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Checks that vertices in supplied :class:`bg.edge.BGEdge` instance actually are present in current :class:`BreakpointGraph` if **merge** option of provided. Otherwise a new edge is added to the current :class:`Breakpoi...
2.789798
2.73578
1.019745
self.__add_bgedge(bgedge=bgedge, merge=merge)
def add_bgedge(self, bgedge, merge=True)
Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method. :param bgedge: instance of :class:`bg.edge.BGEdge` infromation form which is to be added to current :class:`BreakpointGraph` ...
3.953763
4.188242
0.944015
vertex_class = BGVertex.get_vertex_class_from_vertex_name(vertex_name) data = vertex_name.split(BlockVertex.NAME_SEPARATOR) root_name, data = data[0], data[1:] if issubclass(vertex_class, TaggedVertex): tags = [entry.split(TaggedVertex.TAG_SEPARATOR) for entry in dat...
def __get_vertex_by_name(self, vertex_name)
Obtains a vertex object by supplied label Returns a :class:`bg.vertex.BGVertex` or its subclass instance :param vertex_name: a vertex label it is identified by. :type vertex_name: any hashable python object. ``str`` expected. :return: vertex with supplied label if present in current :c...
3.222013
3.131346
1.028955
if vertex1 in self.bg and vertex2 in self.bg[vertex1]: if key is None: key = min(self.bg[vertex1][vertex2]) return BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=self.bg[vertex1][vertex2][key]["attr_dict"]["multicolor"], ...
def __get_edge_by_two_vertices(self, vertex1, vertex2, key=None)
Returns an instance of :class:`bg.edge.BBGEdge` edge between to supplied vertices (if ``key`` is supplied, returns a :class:`bg.edge.BBGEdge` instance about specified edge). Checks that both specified vertices are in current :class:`BreakpointGraph` and then depending on ``key`` argument, creates a new :class:...
3.06695
2.641667
1.16099
return self.__get_edge_by_two_vertices(vertex1=vertex1, vertex2=vertex2, key=key)
def get_edge_by_two_vertices(self, vertex1, vertex2, key=None)
Returns an instance of :class:`bg.edge.BBGEdge` edge between to supplied vertices (if ``key`` is supplied, returns a :class:`bg.edge.BBGEdge` instance about specified edge). Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__get_edge_by_two_vertices`. :param vertex1: first vertex instance out ...
2.609389
2.948709
0.884926
if vertex in self.bg: for vertex2, edges in self.bg[vertex].items(): for key, data in self.bg[vertex][vertex2].items(): bg_edge = BGEdge(vertex1=vertex, vertex2=vertex2, multicolor=data["attr_dict"]["multicolor"], data...
def __get_edges_by_vertex(self, vertex, keys=False)
Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to it. Wraps each yielded object into :class:`bg.edge.BGEdge` object....
3.453418
3.443462
1.002891
for entry in self.__get_edges_by_vertex(vertex=vertex, keys=keys): yield entry
def get_edges_by_vertex(self, vertex, keys=False)
Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Proxies a call to :meth:`Breakpoint._Breakpoint__get_edges_by_vertex` method. :param vertex: a vertex object in current :class:`BreakpointGraph` object :type vertex: any hashable object. :clas...
5.211972
4.866927
1.070896
for vertex in vertex1, vertex2: if vertex not in self.bg: raise ValueError("Supplied vertex ({vertex_name}) is not present in current BreakpointGraph" "".format(vertex_name=str(vertex.name))) for bgedge, key in self.__get_edges_by_ver...
def __edges_between_two_vertices(self, vertex1, vertex2, keys=False)
Iterates over edges between two supplied vertices in current :class:`BreakpointGraph` Checks that both supplied vertices are present in current breakpoint graph and then yield all edges that are located between two supplied vertices. If keys option is specified, then not just edges are yielded, but rat...
4.366993
3.64327
1.198646
for entry in self.__edges_between_two_vertices(vertex1=vertex1, vertex2=vertex2, keys=keys): yield entry
def edges_between_two_vertices(self, vertex1, vertex2, keys=False)
Iterates over edges between two supplied vertices in current :class:`BreakpointGraph` Proxies a call to :meth:`Breakpoint._Breakpoint__edges_between_two_vertices` method. :param vertex1: a first vertex out of two, edges of interest are incident to :type vertex1: any hashable object, :class:`bg...
3.507012
3.414985
1.026948
for component in nx.connected_components(self.bg): component = self.bg.subgraph(component) if copy: component.copy() yield BreakpointGraph(component)
def connected_components_subgraphs(self, copy=True)
Iterates over connected components in current :class:`BreakpointGraph` object, and yields new instances of :class:`BreakpointGraph` with respective information deep-copied by default (week reference is possible of specified in method call). :param copy: a flag to signal if graph information has to be deep copi...
4.379066
3.434276
1.275106
############################################################################################################ # # determines which edge to delete # candidate edges setup # ############################################################################################...
def __delete_bgedge(self, bgedge, key=None, keep_vertices=False)
Deletes a supplied :class:`bg.edge.BGEdge` from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.similarity_score` result) edge between respective vertices is chosen for change. If no unique identifier for...
3.082789
2.848029
1.082429
self.__delete_bgedge(bgedge=BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor), key=key)
def delete_edge(self, vertex1, vertex2, multicolor, key=None)
Creates a new :class:`bg.edge.BGEdge` instance from supplied information and deletes it from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.similarity_score` result) edge between respective vertices is chosen for...
4.217925
2.733139
1.543253
self.__delete_bgedge(bgedge=bgedge, key=key)
def delete_bgedge(self, bgedge, key=None)
Deletes a supplied :class:`bg.edge.BGEdge` from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.similarity_score` result) edge between respective vertices is chosen for change. Proxies a call to :math:`Br...
3.75205
3.918436
0.957537
candidate_id = None candidate_score = 0 candidate_data = None if key is not None: new_multicolors = Multicolor.split_colors( multicolor=self.bg[bgedge.vertex1][bgedge.vertex2][key]["attr_dict"]["multicolor"], guidance=guidance, sorted_...
def __split_bgedge(self, bgedge, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None)
Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied guidance. If no unique identifier for edge to be changed is specified, edge to be split is determined by iterating over all edges between vert...
1.807423
1.717364
1.05244
self.__split_bgedge(bgedge=BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor), guidance=guidance, sorted_guidance=sorted_guidance, account_for_colors_multiplicity_in_guidance=account_for_colors_multiplicity_in_guidance, ...
def split_edge(self, vertex1, vertex2, multicolor, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None)
Splits an edge in current :class:`BreakpointGraph` most similar to supplied data (if no unique identifier ``key`` is provided) with respect to supplied guidance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__split_bgedge` method. :param vertex1: a first vertex out of two the edge to be sp...
2.287738
1.870502
1.223061
self.__split_bgedge(bgedge=bgedge, guidance=guidance, sorted_guidance=sorted_guidance, account_for_colors_multiplicity_in_guidance=account_for_colors_multiplicity_in_guidance, key=key)
def split_bgedge(self, bgedge, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None)
Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied guidance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__split_bgedge` method. :param bgedge: an edge to find most "simil...
1.571554
1.70715
0.920571
edges_to_be_split_keys = [key for v1, v2, key in self.bg.edges(nbunch=vertex1, keys=True) if v2 == vertex2] for key in edges_to_be_split_keys: self.__split_bgedge(BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=None), guidance=guidance, sorted_gui...
def __split_all_edges_between_two_vertices(self, vertex1, vertex2, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True)
Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to the provided guidance. Iterates over all edges between two supplied vertices and splits each one of them with respect to the guidance. :param vertex1: a first out of two vertices edges between w...
2.848888
2.609282
1.091828
self.__split_all_edges_between_two_vertices(vertex1=vertex1, vertex2=vertex2, guidance=guidance, sorted_guidance=sorted_guidance, account_for_colors_multiplicity_in_guidance=account_for_colors_multip...
def split_all_edges_between_two_vertices(self, vertex1, vertex2, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True)
Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to the provided guidance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__split_all_edges_between_two_vertices` method. :param vertex1: a first out of two vertices edges between which ar...
1.586712
1.622357
0.978029
vertex_pairs = [(edge.vertex1, edge.vertex2) for edge in self.edges()] for v1, v2 in vertex_pairs: self.__split_all_edges_between_two_vertices(vertex1=v1, vertex2=v2, guidance=guidance, sorted_guidance=sorted_guidance, ...
def split_all_edges(self, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True)
Splits all edge in current :class:`BreakpointGraph` instance with respect to the provided guidance. Iterate over all possible distinct pairs of vertices in current :class:`BreakpointGraph` instance and splits all edges between such pairs with respect to provided guidance. :param guidance: a guidance f...
2.05925
2.144906
0.960065
edges_to_be_deleted_with_keys = [(key, data) for v1, v2, key, data in self.bg.edges(nbunch=vertex1, keys=True, data=True) if v2 == vertex2] for key, data in edges_to_be_deleted_with_keys: sel...
def __delete_all_bgedges_between_two_vertices(self, vertex1, vertex2)
Deletes all edges between two supplied vertices :param vertex1: a first out of two vertices edges between which are to be deleted :type vertex1: any python hashable object. :class:`bg.vertex.BGVertex` is expected :param vertex2: a second out of two vertices edges between which are to be deleted...
3.649951
3.760459
0.970613
self.__delete_all_bgedges_between_two_vertices(vertex1=vertex1, vertex2=vertex2)
def delete_all_edges_between_two_vertices(self, vertex1, vertex2)
Deletes all edges between two supplied vertices Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__delete_all_bgedges_between_two_vertices` method. :param vertex1: a first out of two vertices edges between which are to be deleted :type vertex1: any python hashable object. :class:`bg.ve...
4.881775
2.630878
1.855569
############################################################################################################ # # no actual merging is performed, but rather all edges between two vertices are deleted # and then added with a merge argument set to true # ###########...
def __merge_all_bgedges_between_two_vertices(self, vertex1, vertex2)
Merges all edge between two supplied vertices into a single edge from a perspective of multi-color merging. :param vertex1: a first out of two vertices edges between which are to be merged together :type vertex1: any python hashable object. :class:`bg.vertex.BGVertex` is expected :param vertex2...
4.198257
4.161689
1.008787
self.__merge_all_bgedges_between_two_vertices(vertex1=vertex1, vertex2=vertex2)
def merge_all_edges_between_two_vertices(self, vertex1, vertex2)
Merges all edge between two supplied vertices into a single edge from a perspective of multi-color merging. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__merge_all_bgedges_between_two_vertices` :param vertex1: a first out of two vertices edges between which are to be merged together ...
5.239367
2.702396
1.938786
pairs_of_vetices = [(edge.vertex1, edge.vertex2) for edge in self.edges()] for v1, v2 in pairs_of_vetices: ############################################################################################################ # # we iterate over all pairs of vertices i...
def merge_all_edges(self)
Merges all edges in a current :class`BreakpointGraph` instance between same pairs of vertices into a single edge from a perspective of multi-color merging. Iterates over all possible pairs of vertices in current :class:`BreakpointGraph` and merges all edges between respective pairs. :return: ``None``,...
5.213197
4.937865
1.055759
result = cls() for bgedge in breakpoint_graph1.edges(): result.__add_bgedge(bgedge=bgedge, merge=merge_edges) for bgedge in breakpoint_graph2.edges(): result.__add_bgedge(bgedge=bgedge, merge=merge_edges) return result
def merge(cls, breakpoint_graph1, breakpoint_graph2, merge_edges=False)
Merges two given instances of :class`BreakpointGraph` into a new one, that gather all available information from both supplied objects. Depending of a ``merge_edges`` flag, while merging of two dat structures is occurring, edges between similar vertices can be merged during the creation of a result :class`Brea...
2.228768
2.453912
0.908251
for bgedge in breakpoint_graph.edges(): self.__add_bgedge(bgedge=deepcopy(bgedge), merge=merge_edges)
def __update(self, breakpoint_graph, merge_edges=False)
Updates a current :class`BreakpointGraph` object with information from a supplied :class`BreakpointGraph` instance. Depending of a ``merge_edges`` flag, while updating of a current :class`BreakpointGraph` object is occuring, edges between similar vertices can be merged to already existing ones. :param...
5.938732
7.454913
0.79662
self.__update(breakpoint_graph=breakpoint_graph, merge_edges=merge_edges)
def update(self, breakpoint_graph, merge_edges=False)
Updates a current :class`BreakpointGraph` object with information from a supplied :class`BreakpointGraph` instance. Proxoes a call to :meth:`BreakpointGraph._BreakpointGraph__update` method. :param breakpoint_graph: a breakpoint graph to extract information from, which will be then added to the curren...
4.647868
5.334831
0.87123
genomes = set() result = {} result["edges"] = [] for bgedge in self.edges(): genomes |= bgedge.multicolor.colors result["edges"].append(bgedge.to_json(schema_info=schema_info)) result["vertices"] = [bgvertex.to_json(schema_info=schema_info) for bg...
def to_json(self, schema_info=True)
JSON serialization method that account for all information-wise important part of breakpoint graph
3.228473
3.011913
1.071901
res = Result() if obj_id: if obj_id == '0': obj = { 'id': 0, 'name': 'TAGLESS', 'artist': False, } else: obj = get_object_or_404(Tag, pk=obj_id).json() res.append(obj) return JsonResponse(re...
def get(request, obj_id=None)
Lists all tags :returns: json
2.919305
2.976249
0.980867
res = Result() data = request.POST or json.loads(request.body)['body'] name = data.get('name', None) if not name: res.isError = True res.message = "No name given" return JsonResponse(res.asDict()) tag = Tag.objects.get_or_create(name=name.lower())[0] res.appe...
def post(request)
Creates a tag object :param name: Name for tag :type name: str :returns: json
3.720317
3.572642
1.041335
res = Result() data = request.PUT or json.loads(request.body)['body'] if obj_id: # -- Edit the tag tag = Tag.objects.get(pk=obj_id) tag.name = data.get('name', tag.name) tag.artist = data.get('artist', tag.artist) tag.save() else: tags = [_ for _ in d...
def put(request, obj_id=None)
Adds tags from objects resolved from guids :param tags: Tags to add :type tags: list :param guids: Guids to add tags from :type guids: list :returns: json
3.665221
3.720776
0.985069
res = Result() if obj_id: # -- Delete the tag itself tag = Tag.objects.get(pk=obj_id) guids = [] images = Image.objects.filter(tags__id=obj_id) guids += [_.guid for _ in images] videos = Video.objects.filter(tags__id=obj_id) guids += [_.guid for _ in...
def delete(request, obj_id=None)
Removes tags from objects resolved from guids :param tags: Tags to remove :type tags: list :param guids: Guids to remove tags from :type guids: list :returns: json
3.282888
3.303313
0.993817
q = request.GET.get('q', '') includeSearch = request.GET.get('search', False) nonZero = request.GET.get('zero', False) excludeArtist = request.GET.get('artist', False) if includeSearch: l = [{'id': 0, 'name': 'Search for: %s' % q}] else: l = [] query = Tag.objects.filt...
def search(request)
Search for Tag objects and returns a Result object with a list of searialize Tag objects. :param search: Append a "Search for" tag :type search: bool :param zero: Exclude Tags with no items :type zero: bool :param artist: Exclude artist tags :type artist: bool :returns: json
2.744226
2.24653
1.22154
res = Result() if request.POST: tags = json.loads(request.POST['tags']) else: tags = json.loads(request.body)['body']['tags'] guids = [] images = Image.objects.filter(tags__id__in=tags) guids += [_.guid for _ in images] videos = Video.objects.filter(tags__id__in=tags) ...
def merge(request, obj_id)
Merges multiple tags into a single tag and all related objects are reassigned
3.690493
3.404897
1.083878
objects = getObjectsFromGuids(guids) tags = [] for tag in tagList: try: t = Tag.objects.get(pk=int(tag)) except ValueError: t = Tag.objects.get_or_create(name=tag.lower())[0] tags.append(t) if add: return _addTags(tags, objects) else: ...
def _manageTags(tagList, guids, add=True)
Adds or Removes Guids from Tags
2.482724
2.536249
0.978896
for t in tags: for o in objects: o.tags.add(t) return True
def _addTags(tags, objects)
Adds tags to objects
3.48604
3.706
0.940648
for t in tags: for o in objects: o.tags.remove(t) return True
def _removeTags(tags, objects)
Removes tags from objects
3.400419
3.550789
0.957652
try: cmd_text, option_text = xsl.split(None, 1) except ValueError: cmd_text = xsl option_text = '' try: context, cmd = cmd_text.strip().lower().split(':', 1) except ValueError: cmd = cmd_text.lower() conte...
def parse(self, xsl='text')
TODO: add double-quoted string literals that allows for escaped double quotes https://gist.github.com/prathe/2439752 or http://www.metaltoad.com/blog/regex-quoted-string-escapable-quotes
3.191707
3.131712
1.019157
body = self.body(e) p = self.p(e) if body == p.getparent(): return p else: raise ElementNotFound("could not find top level w:p element in %s" % e)
def p0(self, e)
Returns top level w:p node
7.4516
4.890325
1.523743
'''Generates regexp for parsing of shortened relative timestamps, as shown in the table.''' ts_re = ['^'] for k in it.chain(_short_ts_days, _short_ts_s): ts_re.append(r'(?P<{0}>\d+{0}\s*)?'.format(k)) return re.compile(''.join(ts_re), re.I | re.U)
def _short_ts_regexp()
Generates regexp for parsing of shortened relative timestamps, as shown in the table.
5.813034
3.713733
1.565281
'''Match time either in human-readable format (as accepted by dateutil), or same time-offset format, as used in the table (e.g. "NdMh ago", or just "NdMh").''' assert isinstance(ts_str, bytes), [type(ts_str), repr(ts_str)] ts_str = ts_str.replace('_', ' ') # Try to parse time offset in short format match = _sho...
def parse_timestamp(ts_str)
Match time either in human-readable format (as accepted by dateutil), or same time-offset format, as used in the table (e.g. "NdMh ago", or just "NdMh").
3.607976
2.94475
1.225223
with self._lock: if timeout is None: while self.empty(): self._not_empty.wait() else: time_end = time.time() + timeout while self.empty(): time_left = time_end - time.time() ...
def _get(self, timeout)
Get a resource from the pool. If timeout is ``None`` waits indefinitely. :param timeout: Time in seconds to wait for a resource. :type timeout: int :return: A resource. :rtype: :class:`_ResourceTracker` :raises PoolEmptyError: When timeout has elapsed and unable to ...
3.190218
2.839643
1.123458
with self._lock: for rt in self._reference_queue: if rt is not None and resource is rt.resource: return rt raise UnknownResourceError('Resource not created by pool')
def _get_tracker(self, resource)
Return the resource tracker that is tracking ``resource``. :param resource: A resource. :return: A resource tracker. :rtype: :class:`_ResourceTracker`
9.587815
9.532483
1.005805
with self._lock: for i in self._unavailable_range(): rtracker = self._reference_queue[i] if rtracker is not None and rtracker.available(): self.put_resource(rtracker.resource)
def _harvest_lost_resources(self)
Return lost resources to pool.
8.1745
7.099592
1.151404
with self._lock: for i in self._unavailable_range(): if self._reference_queue[i] is None: rtracker = _ResourceTracker( self._factory(**self._factory_arguments)) self._reference_queue[i] = rtracker ...
def _make_resource(self)
Returns a resource instance.
7.783104
7.118
1.09344
with self._lock: if self._available < self.capacity: for i in self._unavailable_range(): if self._reference_queue[i] is rtracker: # i retains its value and will be used to swap with # first "empty" space in ...
def _put(self, rtracker)
Put a resource back in the queue. :param rtracker: A resource. :type rtracker: :class:`_ResourceTracker` :raises PoolFullError: If pool is full. :raises UnknownResourceError: If resource can't be found.
5.692697
5.062598
1.124461
with self._lock: i = self._reference_queue.index(rtracker) self._reference_queue[i] = None self._size -= 1
def _remove(self, rtracker)
Remove a resource from the pool. :param rtracker: A resource. :type rtracker: :class:`_ResourceTracker`
4.130357
5.236049
0.788831
with self._lock: i = self._resource_end j = self._resource_start if j < i or self.empty(): j += self.maxsize for k in range(i, j): yield k % self.maxsize
def _unavailable_range(self)
Return a generator for the indices of the unavailable region of ``_reference_queue``.
6.588768
5.53643
1.190075
rtracker = None if resource_wrapper is None: resource_wrapper = self._resource_wrapper if self.empty(): self._harvest_lost_resources() try: rtracker = self._get(0) except PoolEmptyError: pass if rtracker is None...
def get_resource(self, resource_wrapper=None)
Returns a ``Resource`` instance. :param resource_wrapper: A Resource subclass. :return: A ``Resource`` instance. :raises PoolEmptyError: If attempt to get resource fails or times out.
5.405752
5.225309
1.034533
rtracker = self._get_tracker(resource) try: self._put(rtracker) except PoolFullError: self._remove(rtracker)
def put_resource(self, resource)
Adds a resource back to the pool or discards it if the pool is full. :param resource: A resource object. :raises UnknownResourceError: If resource was not made by the pool.
8.110282
7.576186
1.070497
resource = resource_wrapper(self.resource, pool) self._weakref = weakref.ref(resource) return resource
def wrap_resource(self, pool, resource_wrapper)
Return a resource wrapped in ``resource_wrapper``. :param pool: A pool instance. :type pool: :class:`CuttlePool` :param resource_wrapper: A wrapper class for the resource. :type resource_wrapper: :class:`Resource` :return: A wrapped resource. :rtype: :class:`Resource`
4.97444
8.884249
0.559917
if self._resource is not None: self._pool.put_resource(self._resource) self._resource = None self._pool = None
def close(self)
Returns the resource to the resource pool.
3.956563
2.815914
1.405072
for frame in self.message_to_frames(message, fragment_size, mask): self.send_frame(frame)
def send(self, message, fragment_size=None, mask=False)
Send a message. If `fragment_size` is specified, the message is fragmented into multiple frames whose payload size does not extend `fragment_size`.
3.633049
3.324403
1.092842
fragments = [] while not len(fragments) or not fragments[-1].final: frame = self.sock.recv() if isinstance(frame, ControlFrame): self.handle_control_frame(frame) elif len(fragments) > 0 and frame.opcode != OPCODE_CONTINUATION: ...
def recv(self)
Receive a message. A message may consist of multiple (ordered) data frames. A control frame may be delivered at any time, also when expecting the next continuation frame of a fragmented message. These control frames are handled immediately by handle_control_frame().
4.060087
3.469209
1.170321
if frame.opcode == OPCODE_CLOSE: self.close_frame_received = True code, reason = frame.unpack_close() if self.close_frame_sent: self.onclose(code, reason) self.sock.close() raise SocketClosed(True) else: ...
def handle_control_frame(self, frame)
Handle a control frame as defined by RFC 6455.
3.126458
3.027488
1.03269
while True: try: self.onmessage(self.recv()) except (KeyboardInterrupt, SystemExit, SocketClosed): break except Exception as e: self.onerror(e) self.onclose(None, 'error: %s' % e) try: ...
def receive_forever(self)
Receive and handle messages in an endless loop. A message may consist of multiple data frames, but this is not visible for onmessage(). Control messages (or control frames) are handled automatically.
3.87882
3.695251
1.049677
self.send_frame(ControlFrame(OPCODE_PING, payload), lambda: self.onping(payload)) self.ping_payload = payload self.ping_sent = True
def send_ping(self, payload='')
Send a PING control frame with an optional payload.
6.028692
5.240201
1.150469
self.send_close_frame(code, reason) frame = self.sock.recv() if frame.opcode != OPCODE_CLOSE: raise ValueError('expected CLOSE frame, got %s' % frame) self.handle_control_frame(frame)
def close(self, code=None, reason='')
Close the socket by sending a CLOSE frame and waiting for a response close message, unless such a message has already been received earlier (prior to calling this function, for example). The onclose() handler is called after the response has been received, but before the socket is actual...
4.31851
4.164224
1.03705
'''Get object by numeric id or exact and unique part of specified attrs (name, title, etc).''' try: pk = int(query) except ValueError: pass else: return cls.objects.get(pk=pk) obj = list(cls.objects.filter(reduce( op.or_, list(Q(**{'{}__icontains'.format(f): query}) for f in fields) ))) if len(obj) > 1: rai...
def get_by_string(cls, fields, query)
Get object by numeric id or exact and unique part of specified attrs (name, title, etc).
4.636717
3.385008
1.36978
'Handler function' from feedjack import filters # shouldn't be imported globally, as they may depend on models proc_func = getattr(filters, self.handler_name or self.name, None) if proc_func is None: if '.' not in self.handler_name: raise ImportError('Processing function not available: {0}'.format(self.h...
def handler(self)
Handler function
4.62617
4.579075
1.010285
'Parametrized handler function' return ft.partial(self.base.handler, parameter=self.parameter)\ if self.parameter else self.base.handler
def handler(self)
Parametrized handler function
9.544518
7.301284
1.307238
'''Calculate interval for checks as average time (ewma) between updates for specified period.''' if not add_partial: posts_base = self.posts.only('date_modified').order_by('date_modified') if ewma_ts: posts_base = posts_base.filter(date_modified__gt=ewma_ts) posts = posts_base if max_days: posts ...
def calculate_check_interval( self, max_interval, ewma_factor, max_days=None, max_updates=None, ewma=0, ewma_ts=None, add_partial=None )
Calculate interval for checks as average time (ewma) between updates for specified period.
3.019428
2.699213
1.118633
'''Update all cross-referencing filters results for feeds and others, related to them. Intended to be called from non-Feed update hooks (like new Post saving).''' # Check if this call is a result of actions initiated from # one of the hooks in a higher frame (resulting in recursion). if Feed._filters_update...
def update_handler(feeds)
Update all cross-referencing filters results for feeds and others, related to them. Intended to be called from non-Feed update hooks (like new Post saving).
23.95734
6.937113
3.453503
'''Find text-based field matches with similarity (1-levenshtein/length) higher than specified threshold (0 to 1, 1 being an exact match)''' # XXX: use F from https://docs.djangoproject.com/en/1.8/ref/models/expressions/ meta = self.model._meta funcs, params = list(), list() for name,val in criterias.iterit...
def similar(self, threshold, **criterias)
Find text-based field matches with similarity (1-levenshtein/length) higher than specified threshold (0 to 1, 1 being an exact match)
6.553475
5.210707
1.257694
'''Check if post passes all / at_least_one (by_or parameter) filter(s). Filters are evaluated on only-if-necessary ("lazy") basis.''' filters, results = it.imap(set, ( self.feed.filters.all(), self.filtering_results.values_list('filter', flat=True) )) # Check if conclusion can already be made, based on cac...
def _filtering_result_checked(self, by_or)
Check if post passes all / at_least_one (by_or parameter) filter(s). Filters are evaluated on only-if-necessary ("lazy") basis.
9.235098
7.105212
1.299764
future = concurrent.Future() if self.connected: raise exceptions.ConnectError('already connected') LOGGER.debug('%s connecting', self.name) self.io_loop.add_future( self._client.connect(self.host, self.port), lambda f: self._on_connected(f, ...
def connect(self)
Connect to the Redis server if necessary. :rtype: :class:`~tornado.concurrent.Future` :raises: :class:`~tredis.exceptions.ConnectError` :class:`~tredis.exceptinos.RedisError`
4.140942
3.94667
1.049224
LOGGER.debug('execute(%r, %r)', command, future) if self.connected: self._write(command, future) else: def on_connected(cfuture): if cfuture.exception(): return future.set_exception(cfuture.exception()) self._w...
def execute(self, command, future)
Execute a command after connecting if necessary. :param bytes command: command to execute after the connection is established :param tornado.concurrent.Future future: future to resolve when the command's response is received.
3.010574
2.652786
1.134873
LOGGER.error('Redis connection closed') self.connected = False self._on_close() self._stream = None
def _on_closed(self)
Invoked when the connection is closed
10.686356
9.939205
1.075172
if stream_future.exception(): connect_future.set_exception( exceptions.ConnectError(stream_future.exception())) else: self._stream = stream_future.result() self._stream.set_close_callback(self._on_closed) self.connected = True ...
def _on_connected(self, stream_future, connect_future)
Invoked when the socket stream has connected, setting up the stream callbacks and invoking the on connect callback if set. :param stream_future: The connection socket future :type stream_future: :class:`~tornado.concurrent.Future` :param stream_future: The connection response future ...
2.362406
2.591102
0.911738
def on_written(): self._on_written(command, future) try: self._stream.write(command.command, callback=on_written) except iostream.StreamClosedError as error: future.set_exception(exceptions.ConnectionError(error)) except Exception as error: ...
def _write(self, command, future)
Write a command to the socket :param Command command: the Command data structure
4.022456
4.472879
0.899299
LOGGER.debug('Creating a%s connection to %s:%s (db %s)', ' cluster node' if self._clustering else '', self._hosts[0]['host'], self._hosts[0]['port'], self._hosts[0].get( 'db', DEFAULT_DB)) self._connect_futu...
def connect(self)
Connect to the Redis server or Cluster. :rtype: tornado.concurrent.Future
3.610806
3.260139
1.107562
if not self._connected.is_set(): raise exceptions.ConnectionError('not connected') self._closing = True if self._clustering: for host in self._cluster.keys(): self._cluster[host].close() elif self._connection: self._connection....
def close(self)
Close any open connections to Redis. :raises: :exc:`tredis.exceptions.ConnectionError`
4.76312
4.448766
1.070661
if self._clustering: return (all([c.connected for c in self._cluster.values()]) and len(self._cluster)) return (self._connection and self._connection.connected)
def ready(self)
Indicates that the client is connected to the Redis server or cluster and is ready for use. :rtype: bool
7.503299
6.247694
1.200971
LOGGER.debug('Creating a cluster connection to %s:%s', node.ip, node.port) conn = _Connection( node.ip, node.port, 0, self._read, self._on_closed, self.io_loop, cluster_node=True, ...
def _create_cluster_connection(self, node)
Create a connection to a Redis server. :param node: The node to connect to :type node: tredis.cluster.ClusterNode
4.721762
4.461291
1.058385
if isinstance(value, bytes): return b''.join( [b'$', ascii(len(value)).encode('ascii'), CRLF, value, CRLF]) elif isinstance(value, str): # pragma: nocover return self._encode_resp(value.encode('utf-8')) elif isinstance(value, int...
def _encode_resp(self, value)
Dynamically build the RESP payload based upon the list provided. :param mixed value: The list of command parts to encode :rtype: bytes
2.073761
2.132954
0.972249
if isinstance(command.expectation, int) and command.expectation > 1: future.set_result(response == command.expectation or response) else: future.set_result(response == command.expectation)
def _eval_expectation(command, response, future)
Evaluate the response from Redis to see if it matches the expected response. :param command: The command that is being evaluated :type command: tredis.client.Command :param bytes response: The response value to check :param future: The future representing the execution of the co...
3.372571
3.548476
0.950428
future = concurrent.TracebackFuture() try: command = self._build_command(parts) except ValueError as error: future.set_exception(error) return future def on_locked(_): if self.ready: if self._clustering: ...
def _execute(self, parts, expectation=None, format_callback=None)
Really execute a redis command :param list parts: The list of command parts :param mixed expectation: Optional response expectation :rtype: :class:`~tornado.concurrent.Future` :raises: :exc:`~tredis.exceptions.SubscribedError`
4.089996
4.033463
1.014016
LOGGER.debug('_on_cluster_discovery(%r)', future) common.maybe_raise_exception(future) nodes = future.result() for node in nodes: name = '{}:{}'.format(node.ip, node.port) if name in self._cluster: LOGGER.debug('Updating cluster connection...
def _on_cluster_discovery(self, future)
Invoked when the Redis server has responded to the ``CLUSTER_NODES`` command. :param future: The future containing the response from Redis :type future: tornado.concurrent.Future
3.554097
3.484366
1.020012
self._connected.clear() if not self._closing: if self._on_close_callback: self._on_close_callback() else: raise exceptions.ConnectionError('closed')
def _on_closed(self)
Invoked by connections when they are closed.
4.540746
3.887665
1.167988
LOGGER.debug('on_cluster_data_moved(%r, %r, %r)', response, command, future) parts = response.split(' ') name = '{}:{}'.format(*common.split_connection_host_port(parts[2])) LOGGER.debug('Moved to %r', name) if name not in self._cluster: r...
def _on_cluster_data_moved(self, response, command, future)
Process the ``MOVED`` response from a Redis cluster node. :param bytes response: The response from the Redis server :param command: The command that was being executed :type command: tredis.client.Command :param future: The execution future :type future: tornado.concurrent.Futur...
4.511859
4.004797
1.126614
if future.exception(): self._connect_future.set_exception(future.exception()) return conn = future.result() LOGGER.debug('Connected to %s (%r, %r, %r)', conn.name, self._clustering, self._discovery, self._connected) if self._clusteri...
def _on_connected(self, future)
Invoked when connections have been established. If the client is in clustering mode, it will kick of the discovery step if needed. If not, it will select the configured database. :param future: The connection future :type future: tornado.concurrent.Future
3.787464
3.615738
1.047494
failover_future = concurrent.TracebackFuture() def on_replication_info(_): common.maybe_raise_exception(failover_future) LOGGER.debug('Failover closing current read-only connection') self._closing = True database = self._connection.database ...
def _on_read_only_error(self, command, future)
Invoked when a Redis node returns an error indicating it's in read-only mode. It will use the ``INFO REPLICATION`` command to attempt to find the master server and failover to that, reissuing the command to that server. :param command: The command that was being executed :type c...
4.807816
4.488249
1.071201
response = self._reader.gets() if response is not False: if isinstance(response, hiredis.ReplyError): if response.args[0].startswith('MOVED '): self._on_cluster_data_moved(response.args[0], command, ...
def _read(self, command, future)
Invoked when a command is executed to read and parse its results. It will loop on the IOLoop until the response is complete and then set the value of the response in the execution future. :param command: The command that was being executed :type command: tredis.client.Command :p...
3.185399
3.095392
1.029078
crc = crc16.crc16(self._encode_resp(value[1])) % HASH_SLOTS for host in self._cluster.keys(): for slot in self._cluster[host].slots: if slot[0] <= crc <= slot[1]: return self._cluster[host] LOGGER.debug('Host not found for %r, returning fi...
def _pick_cluster_host(self, value)
Selects the Redis cluster host for the specified value. :param mixed value: The value to use when looking for the host :rtype: tredis.client._Connection
5.605134
5.326081
1.052394
separator = None if separator is None else unicode(separator) for line in stream: line = line.rstrip(u'\r\n') row = [interpret_segment(i) for i in line.split(separator)] yield line, row
def parse_lines(stream, separator=None)
Takes each line of a stream, creating a generator that yields tuples of line, row - where row is the line split by separator (or by whitespace if separator is None. :param stream: :param separator: (optional) :return: generator
5.009232
5.356371
0.935191
rows = [] lines = [] for line, row in parse_lines(stream, separator): lines.append(line) rows.append(row) cols = zip(*rows) return { 'rows': rows, 'lines': lines, 'cols': cols, }
def parse_buffer(stream, separator=None)
Returns a dictionary of the lines of a stream, an array of rows of the stream (split by separator), and an array of the columns of the stream (also split by separator) :param stream: :param separator: :return: dict
3.138119
3.069201
1.022455