code
stringlengths
1
18.2k
bug.id: result = self.request('bug', 'POST', json=bug.to_dict()) if 'error' not in result: bug._bug['id'] = result['id'] bug._bugsy = self try: bug._bug.pop('comment') except Exception: # If we don't have a `comment` we will error so let's just # swallow it. pass else: raise BugsyException(result['message']) else: resu...
def request(self, path, method='GET', headers=None, **kwargs): """Perform a HTTP request. Given a relative Bugzilla URL path, an optional request method, and arguments suitable for requests.Request(), perform a HTTP request. """ headers = {} if headers is None else headers.copy() headers["User-Agent"] = "Bugsy" kwargs[...
def estimate_eps(dist_mat, n_closest=5): """ Estimates possible eps values (to be used with DBSCAN) for a given distance matrix by looking at the largest distance "jumps" amongst the `n_closest` distances for each item. Tip: the value for `n_closest` is important - set it too large and you may only get really large dis...
= sorted(np.partition(row, n_closest)[:n_closest]) difs = [(x, y, (y - x)) for x, y in zip(dists, dists[1:])] eps_candidate, _, jump = max(difs, key=lambda x: x[2]) estimates.append(eps_candidate) return sorted(estimates)
def estimate_k(X, max_k): """ Estimate k for K-Means. Adapted from <https://datasciencelab.wordpress.com/2014/01/21/selection-of-k-in-k-means-clustering-reloaded/> """ ks = range(1, max_k) fs = np.zeros(len(ks)) # Special case K=1 fs[0], Sk = _fK(1) # Rest of Ks for k in ks[1:]: fs[k-1], Sk = _fK(k, Skm1=Sk) return np....
def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str]: """Clean lookup fields and check for errors.""" if fields == ALL: fields = allowed_fields.keys() else: fields = tuple(fields) unknown_fields = set(fields) - allowed_fields.keys() if unknown_fields: raise ValueError('Unknown fields: {}'.forma...
def select( db, where_query: str, where_params: SQLParams, fields: FieldsParam = ALL, episode_fields: FieldsParam = (), ) -> Iterator[Anime]: """Perform an arbitrary SQL SELECT WHERE on the anime table. By nature of "arbitrary query", this is vulnerable to injection, use only trusted values for `where_query`. This will...
to get episodes. :param bool force_status: whether to force status calculation. :returns: iterator of Anime """ logger.debug( 'select(%r, %r, %r, %r, %r)', db, where_query, where_params, fields, episode_fields) fields = _clean_fields(ANIME_FIELDS, fields) if not fields: raise ValueError('Fields cannot be empty') if set...
value in zip(episode_fields, row)}) for row in episode_rows] anime.episodes = episodes yield anime
def lookup( db, aid: int, fields: FieldsParam = ALL, episode_fields: FieldsParam = (), ) -> Anime: """Look up information for a single anime. :param fields: anime fields to get. If ``None``, get all fields. :param episode_fields: episode fields to get. If ``None``, get all fields. If empty, don't get episodes. """ retu...
def _get_default_letters(model_admin=None): """ Returns the set of letters defined in the configuration variable DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or list and returns a set. If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET attribute and use it instead. """ from dja...
def _get_available_letters(field_name, queryset): """ Makes a query to the database to return the first character of each value of the field and table passed in. Returns a set that represents the letters that exist in the database. """ if django.VERSION[1] <= 4: result = queryset.values(field_name).annotate( fl=FirstLe...
def alphabet(cl): """ The inclusion tag that renders the admin/alphabet.html template in the admin. Accepts a ChangeList object, which is custom to the admin. """ if not getattr(cl.model_admin, 'alphabet_filter', False): return field_name = cl.model_admin.alphabet_filter alpha_field = '%s__istartswith' % field_name alp...
def qs_alphabet_filter(parser, token): """ The parser/tokenizer for the queryset alphabet filter. {% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %} {% qs_alphabet_filter objects lastname myapp/template.html %} The template name is optional and uses alphafilter/alphabet.h...
def get_installed_classes(cls): """ Iterates over installed plugins associated with the `entry_point` and returns a dictionary of viable ones keyed off of their names. A viable installed plugin is one that is both loadable *and* a subclass of the Pluggable subclass in question. """ installed_classes = {} for entry_poin...
def from_config(cls, name, config): """ Behaves like the base Configurable class's `from_config()` except this makes sure that the `Pluggable` subclass with the given name is actually a properly installed plugin first. """ installed_classes = cls.get_installed_classes() if name not in installed_classes: raise ValueErro...
def file_name(self, event): """ Helper method for determining the basename of the affected file. """ name = os.path.basename(event.src_path) name = name.replace(".yaml", "") name = name.replace(".yml", "") return name
def on_created(self, event): """ Newly created config file handler. Parses the file's yaml contents and creates a new instance of the target_class with the results. Fires the on_add callback with the new instance. """ if os.path.isdir(event.src_path): return logger.debug("File created: %s", event.src_path) name = self....
def on_modified(self, event): """ Modified config file handler. If a config file is modified, the yaml contents are parsed and the new results are validated by the target class. Once validated, the new config is passed to the on_update callback. """ if os.path.isdir(event.src_path): return logger.debug("file modified: ...
def on_deleted(self, event): """ Deleted config file handler. Simply fires the on_delete callback with the name of the deleted item. """ logger.debug("file removed: %s", event.src_path) name = self.file_name(event) self.on_delete(self.target_class, name)
def on_moved(self, event): """ A move event is just proxied to an on_deleted call followed by an on_created call. """ self.on_deleted(events.FileDeletedEvent(event.src_path)) self.on_created(events.FileCreatedEvent(event.dest_path))
def command(state, args): """Search AniDB.""" args = parser.parse_args(args[1:]) if not args.query: print('Must supply query.') return search_query = _compile_re_query(args.query) results = state.titles.search(search_query) results = [(anime.aid, anime.main_title) for anime in results] state.results['anidb'].set(result...
def regenerate(self): """Regenerate the session id. This function creates a new session id and stores all information associated with the current id in that new id. It then destroys the old session id. This is useful for preventing session fixation attacks and should be done whenever someone uses a login to obtain addi...
def get(self,key,default=None): """Get a value from the dictionary. Args: key (str): The dictionary key. default (any): The default to return if the key is not in the dictionary. Defaults to None. Returns: str or any: The dictionary value or the default if the key is not in the dictionary. """ retval = self.__getitem__...
def items(self): """Return a list of all the key, value pair tuples in the dictionary. Returns: list of tuples: [(key1,value1),(key2,value2),...,(keyN,valueN)] """ all_items = [(k.decode('utf-8'),v.decode('utf-8')) for k,v in self.rdb.hgetall(self.session_hash).items()] return all_items
def keys(self): """Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN] """ all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_keys
def values(self): """Returns a list of all values in the dictionary. Returns: list of str: [value1,value2,...,valueN] """ all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_values
def sbessely(x, N): """Returns a vector of spherical bessel functions yn: x: The argument. N: values of n will run from 0 to N-1. """ out = np.zeros(N, dtype=np.float64) out[0] = -np.cos(x) / x out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x for n in xrange(2, N): out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2]...
def sbesselj(x, N): """Returns a vector of spherical bessel functions jn: x: The argument. N: values of n will run from 0 to N-1. """ nmax = N - 1; out = np.zeros(N, dtype=np.float64) z = x ** 2 out[0] = np.sin(x) / x j1 = np.sin(x) / z - np.cos(x) / x u = 1 v = x / (2.0 * nmax + 1.0) w = v n = nmax while(np.abs(v / w)...
- out[n + 1]) if(np.abs(out[0]) >= np.abs(j1)): out[1] *= out[0] else: out[1] = j1 for n in xrange(1, nmax): out[n + 1] *= out[n] return out
def sbesselh1(x, N): "Spherical Hankel of the first kind" jn = sbesselj(x, N) yn = sbessely(x, N) return jn + 1j * yn
def sbesselh2(x, N): "Spherical Hankel of the second kind" jn = sbesselj(x, N) yn = sbessely(x, N) return jn - 1j * yn
def sbesselj_array(xvec, N): """Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) show() """ first_time = True for x in xvec: a = sbesselj(x, N) if first_time: out...
def sbessely_array(xvec, N): """Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) ylim((-.4,.4)) show() """ first_time = True for x in xvec: a = sbessely(x, N) if ...
def sbesselj_sum(z, N): """Tests the Spherical Bessel function jn using the sum: Inf sum (2*n+1) * jn(z)**2 = 1 n=0 z: The argument. N: Large N value that the sum runs too. Note that the sum only converges to 1 for large N value (i.e. N >> z). The routine returns the relative error of the assumption. """ b = sbesselj(z...
def merge(dicts): """ Merges a list of dicts, summing their values. (Parallelized wrapper around `_count`) """ chunks = [args for args in np.array_split(dicts, 20)] results = parallel(_count, chunks, n_jobs=-1) return _count(results)
def _count(dicts): """ Merge a list of dicts, summing their values. """ counts = defaultdict(int) for d in dicts: for k, v in d.items(): counts[k] += v return counts
def _chunks(iterable, n): """ Splits an iterable into chunks of size n. """ iterable = iter(iterable) while True: # store one line in memory, # chain it to an iterator on the rest of the chunk yield chain([next(iterable)], islice(iterable, n-1))
def split_file(path, chunk_size=50000): """ Splits the specified file into smaller files. """ with open(path) as f: for i, lines in enumerate(_chunks(f, chunk_size)): file_split = '{}.{}'.format(os.path.basename(path), i) chunk_path = os.path.join('/tmp', file_split) with open(chunk_path, 'w') as f: f.writelines(lines)...
def doc_stream(path): """ Generator to feed tokenized documents (treating each line as a document). """ with open(path, 'r') as f: for line in f: if line.strip(): yield line
def add_line(self, line): """ Adds a given line string to the list of lines, validating the line first. """ if not self.is_valid_line(line): logger.warn( "Invalid line for %s section: '%s'", self.section_name, line ) return self.lines.append(line)
def is_valid_line(self, line): """ Validates a given line against the associated "section" (e.g. 'global' or 'frontend', etc.) of a stanza. If a line represents a directive that shouldn't be within the stanza it is rejected. See the `directives.json` file for a condensed look at valid directives based on section. """ a...
def load_stop_words(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words. """ stop_words = [] for line in open(stop_word_file): if line.strip()[0:1] != "#": for word ...
def separate_words(text, min_word_return_size): """ Utility function to return a list of all words that are have a length greater than a specified number of characters. @param text The text that must be split in to words. @param min_word_return_size The minimum no of characters a word must have to be included. """ spli...
def split_sentences(text): """ Utility function to return a list of sentences. @param text The text that must be split in to sentences. """ sentence_delimiters = re.compile(u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]') sentences = sentence_delimiters.split(text) return sentences
def param_redirect(request, viewname, *args): """ Redirect and keep URL parameters if any. """ url = reverse(viewname, PARAMS_URL_CONF, args) params = request.GET.urlencode().split('&') if hasattr(request, 'cparam'): for k, v in request.cparam.items(): params.append('{0}={1}'.format(k, v)) new_params = '&'.join(x for x...
def backup_db(release=None, limit=5): """ Backup database and associate it with current release """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_db" in env, "Missing mysql_db ...
def restore_db(release=None): """ Restores backup back to version, uses current version by default. """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_db" in env, "Missing mysql...
def kind_as_string(self, add_colour=True): '''Get the type of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing the kind of execution context this is. ''' with self._mutex: if self.kind == self.PERIODIC: result = 'Periodic', ['reset'] ...
def running_as_string(self, add_colour=True): '''Get the state of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing this context's running state. ''' with self._mutex: if self.running: result = 'Running', ['bold', 'green'] else: result...
def kind(self): '''The kind of this execution context.''' with self._mutex: kind = self._obj.get_kind() if kind == RTC.PERIODIC: return self.PERIODIC elif kind == RTC.EVENT_DRIVEN: return self.EVENT_DRIVEN else: return self.OTHER
def owner_name(self): '''The name of the RTObject that owns this context.''' with self._mutex: if self._owner: return self._owner.get_component_profile().instance_name else: return ''
def participant_names(self): '''The names of the RTObjects participating in this context.''' with self._mutex: return [obj.get_component_profile().instance_name \ for obj in self._participants]
def delete_manager(self, instance): """ Returns a queryset based on the related model's base manager (rather than the default manager, as returned by __get__). Used by Model.delete(). """ return self.create_manager(instance, self.rating_model._base_manager.__class__)
def create_manager(self, instance, superclass): """ Dynamically create a RelatedManager to handle the back side of the (G)FK """ rel_model = self.rating_model rated_model = self.rated_model class RelatedManager(superclass): def get_query_set(self): qs = RatingsQuerySet(rel_model, rated_model=rated_model) return qs.filt...
def rate(self, user, score): rating, created = self.get_or_create(user=user) if created or score != rating.score: rating.score = score rating.save() return rating def unrate(self, user): return self.filter(user=user, **rel_model.lookup_kwargs(instance) ).delete() def perform_aggregation(self, aggregator): score = self....
def hash(self, value): """ function hash() implement to acquire hash value that use simply method that weighted sum. Parameters: ----------- value: string the value is param of need acquire hash Returns: -------- result hash code for value """ result = 0 for i in range(len(value)): result += self.seed * result + ord(va...
def is_contains(self, data): """ Judge the data whether is already exist if each bit of hash code is 1 then data exist. """ if not data: return False data = self._compress_by_md5(data) result = True # cut the first two place,route to different block by block_num name = self.key + str(int(data[0:2], 16) % self.block_num...
def insert(self, data): """ Insert 1 into each bit by local_hash """ if not data: return data = self._compress_by_md5(data) # cut the first two place,route to different block by block_num name = self.key + str(int(data[0:2], 16) % self.block_num) for h in self.hash_function: local_hash = h.hash(data) self.server.setbit...
def generate(self, clusters, version=None): """ Generates HAProxy config file content based on a given list of clusters. """ now = datetime.datetime.now() sections = [ Section( "Auto-generated by Lighthouse (%s)" % now.strftime("%c"), self.global_stanza, self.defaults_stanza ) ] meta_stanzas = [ MetaFrontendStanza( nam...
"\n\n\n".join([str(section) for section in sections]) + "\n"
def get_meta_clusters(self, clusters): """ Returns a dictionary keyed off of meta cluster names, where the values are lists of clusters associated with the meta cluster name. If a meta cluster name doesn't have a port defined in the `meta_cluster_ports` attribute an error is given and the meta cluster is removed from t...
def generate(cls, size, string, filetype="JPEG"): """ Generates a squared avatar with random background color. :param size: size of the avatar, in pixels :param string: string to be used to print text and seed the random :param filetype: the file format of the image (i.e. JPEG, PNG) """ render_size = max(size, GenAvata...
def _background_color(s): """ Generate a random background color. Brighter colors are dropped, because the text is white. :param s: Seed used by the random generator (same seed will produce the same color). """ seed(s) r = v = b = 255 while r + v + b > 255 * 2: r = randint(0, 255) v = randint(0, 255) b = randint(0, 255...
def _font(size): """ Returns a PIL ImageFont instance. :param size: size of the avatar, in pixels """ # path = '/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc' path = os.path.join( os.path.dirname(__file__), 'data', "wqy-microhei.ttc") return ImageFont.truetype(path, size=int(0.65 * size), index=0)
def _text_position(size, text, font): """ Returns the left-top point where the text should be positioned. """ width, height = font.getsize(text) left = (size - width) / 2.0 top = (size - height) / 3.0 return left, top
def age(self): """Calculates the animals age, relative to the current date (if alive) or the date of death (if not).""" if self.Death: age = self.Death - self.Born else: age = datetime.date.today() - self.Born return age.days
def breeding_male_location_type(self): """This attribute defines whether a male's current location is the same as the breeding cage to which it belongs. This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified. The location is relative ...
def breeding_female_location_type(self): """This attribute defines whether a female's current location is the same as the breeding cage to which it belongs. This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified. The location is relat...
def save(self): """The save method for Animal class is over-ridden to set Alive=False when a Death date is entered. This is not the case for a cause of death.""" if self.Death: self.Alive = False super(Animal, self).save()
def duration(self): """Calculates the breeding cage's duration. This is relative to the current date (if alive) or the date of inactivation (if not). The duration is formatted in days.""" if self.End: age = self.End - self.Start else: age = datetime.date.today() - self.Start return age.days
def unweaned(self): """This attribute generates a queryset of unweaned animals for this breeding cage. It is filtered for only Alive animals.""" return Animal.objects.filter(Breeding=self, Weaned__isnull=True, Alive=True)
def male_breeding_location_type(self): """This attribute defines whether a breeding male's current location is the same as the breeding cage. This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.""" if int(self.Male.all()[0].Cage) =...
def save(self): """The save function for a breeding cage has to automatic over-rides, Active and the Cage for the Breeder. In the case of Active, if an End field is specified, then the Active field is set to False. In the case of Cage, if a Cage is provided, and animals are specified under Male or Females for a Breedin...
def start(self, on_add, on_update, on_delete): """ Starts monitoring the file path, passing along on_(add|update|delete) callbacks to a watchdog observer. Iterates over the files in the target path before starting the observer and calls the on_created callback before starting the observer, so that existing files aren't...
def matplotlibensure(func): """If matplotlib isn't installed, this decorator alerts the user and suggests how one might obtain the package.""" @wraps(func) def wrap(*args): if MPLINSTALLED == False: raise ImportError(msg) return func(*args) return wrap
def to_ts(date: datetime.date) -> float: """Convert date to timestamp. >>> to_ts(datetime.date(2001, 1, 2)) 978393600.0 """ return datetime.datetime( date.year, date.month, date.day, tzinfo=datetime.timezone.utc).timestamp()
def to_date(ts: float) -> datetime.date: """Convert timestamp to date. >>> to_date(978393600.0) datetime.date(2001, 1, 2) """ return datetime.datetime.fromtimestamp( ts, tz=datetime.timezone.utc).date()
def get_response(sock, buffer_size=4096): """ Helper method for retrieving a response from a given socket. Returns two values in a tuple, the first is the reponse line and the second is any extra data after the newline. """ response = "" extra = "" while True: try: chunk = sock.recv(buffer_size) if chunk: response += c...
def add_name_server(self, server, filter=[], dynamic=None): '''Parse a name server, adding its contents to the tree. @param server The address of the name server, in standard address format. e.g. 'localhost', 'localhost:2809', '59.7.0.1'. @param filter Restrict the parsed objects to only those in this path. For example...
def is_component(self, path): '''Is the node pointed to by @ref path a component?''' node = self.get_node(path) if not node: return False return node.is_component
def is_directory(self, path): '''Is the node pointed to by @ref path a directory (name servers and naming contexts)? ''' node = self.get_node(path) if not node: return False return node.is_directory
def is_manager(self, path): '''Is the node pointed to by @ref path a manager?''' node = self.get_node(path) if not node: return False return node.is_manager
def is_nameserver(self, path): '''Is the node pointed to by @ref path a name server (specialisation of directory nodes)? ''' node = self.get_node(path) if not node: return False return node.is_nameserver
def is_unknown(self, path): '''Is the node pointed to by @ref path an unknown object?''' node = self.get_node(path) if not node: return True return node.is_unknown
def is_zombie(self, path): '''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
def iterate(self, func, args=None, filter=[]): '''Call a function on the root node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref args. @...
to @ref func in a list. ''' return self._root.iterate(func, args, filter)
def load_servers_from_env(self, filter=[], dynamic=None): '''Load the name servers environment variable and parse each server in the list. @param filter Restrict the parsed objects to only those in this path. For example, setting filter to [['/', 'localhost', 'host.cxt', 'comp1.rtc']] will prevent 'comp2.rtc' in the sa...
def parse_port(port_obj, owner): '''Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a Component object or None. @return The created port...
def connect(self, dests=[], name=None, id='', props={}): '''Connect this port to other ports. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the c...
in [x.strip() for x in self.properties[prop].split(',')] and \ 'any' not in self.properties[prop].lower(): # Invalid property selected raise exceptions.IncompatibleDataPortConnectionPropsError for d in dests: if prop in d.properties: if props[prop] not in [x.strip() for x in d.properties[prop].split(',')] and \ 'any' n...
def disconnect_all(self): '''Disconnect all connections to this port.''' with self._mutex: for conn in self.connections: self.object.disconnect(conn.id) self.reparse_connections()
def get_connection_by_dest(self, dest): '''DEPRECATED. Search for a connection between this and another port.''' with self._mutex: for conn in self.connections: if conn.has_port(self) and conn.has_port(dest): return conn return None
def get_connections_by_dest(self, dest): '''Search for all connections between this and another port.''' with self._mutex: res = [] for c in self.connections: if c.has_port(self) and c.has_port(dest): res.append(c) return res
def get_connections_by_dests(self, dests): '''Search for all connections involving this and all other ports.''' with self._mutex: res = [] for c in self.connections: if not c.has_port(self): continue has_dest = False for d in dests: if c.has_port(d): has_dest = True break if has_dest: res.append(c) return res
def get_connection_by_id(self, id): '''Search for a connection on this port by its ID.''' with self._mutex: for conn in self.connections: if conn.id == id: return conn return None
def get_connection_by_name(self, name): '''Search for a connection to or from this port by name.''' with self._mutex: for conn in self.connections: if conn.name == name: return conn return None
def connections(self): '''A list of connections to or from this port. This list will be created at the first reference to this property. This means that the first reference may be delayed by CORBA calls, but others will return quickly (unless a delayed reparse has been triggered). ''' with self._mutex: if not self._con...
def connect(self, dests=[], name=None, id='', props={}): '''Connect this port to other DataPorts. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of t...