code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not isinstance(fmfile, dict):
raise FMFileError('fmfile must be a <dict>')
method, url = get_URL('file_delete')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'fileid': fmfile.g... | def delete_file(self, fmfile) | Delete file from transfer.
:param fmfile: file data from filemail containing fileid
:type fmfile: ``dict``
:rtype: ``bool`` | 4.411122 | 4.219873 | 1.045321 |
method, url = get_URL('update')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'transferid': self.transfer_id,
}
data = {
'message': message or self.transfer_info.get('... | def update(self,
message=None,
subject=None,
days=None,
downloads=None,
notify=None) | Update properties for a transfer.
:param message: updated message to recipient(s)
:param subject: updated subject for trasfer
:param days: updated amount of days transfer is available
:param downloads: update amount of downloads allowed for transfer
:param notify: update whether... | 2.901974 | 2.808268 | 1.033368 |
if files is None:
files = self.files
elif not isinstance(files, list):
files = [files]
if destination is None:
destination = os.path.expanduser('~')
for f in files:
if not isinstance(f, dict):
raise FMBaseError... | def download(self,
files=None,
destination=None,
overwrite=False,
callback=None) | Download file or files.
:param files: file or files to download
:param destination: destination path (defaults to users home directory)
:param overwrite: replace existing files?
:param callback: callback function that will receive total file size
and written bytes as arguments
... | 3.258174 | 2.872766 | 1.134159 |
fullpath = os.path.join(destination, fmfile.get('filename'))
path, filename = os.path.split(fullpath)
if os.path.exists(fullpath):
msg = 'Skipping existing file: {filename}'
logger.info(msg.format(filename=filename))
return
filesize = fmfil... | def _download(self, fmfile, destination, overwrite, callback) | The actual downloader streaming content from Filemail.
:param fmfile: to download
:param destination: destination path
:param overwrite: replace existing files?
:param callback: callback function that will receive total file size
and written bytes as arguments
:type fmf... | 2.542522 | 2.504595 | 1.015143 |
method, url = get_URL('compress')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'transferid': self.transfer_id
}
res = getattr(self.session, method)(url, params=payload)
... | def compress(self) | Compress files on the server side after transfer complete
and make zip available for download.
:rtype: ``bool`` | 5.885702 | 5.285205 | 1.113619 |
return self.keyword_parse.from_initials_list([self.mnemonic.reality_to_starter('major_system', number)
for number in pin],
timeout) | def from_pin(self, pin, timeout=5) | Generate a sentence from PIN
:param str pin: a string of digits
:param float timeout: total time in seconds
:return dict: {
'sentence': sentence corresponding to the PIN,
'overlap': overlapping positions, starting for 0
}
>>> ToSentence().from_pin('3492'... | 51.132671 | 58.99995 | 0.866656 |
return self.keyword_parse.from_keyword_list(keyword_list, strictness, timeout) | def from_keywords(self, keyword_list, strictness=2, timeout=3) | Generate a sentence from initial_list.
:param list keyword_list: a list of keywords to be included in the sentence.
:param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching
:param float timeout: timeout of this function
:return list of tuple:
... | 4.950644 | 9.006461 | 0.549677 |
option_name = flag_name if required else "--%s" % flag_name
get_context_parser().add_argument(
option_name, default=default_value, help=docstring, type=flagtype) | def _define_helper(flag_name, default_value, docstring, flagtype, required) | Registers 'flag_name' with 'default_value' and 'docstring'. | 3.83779 | 3.826957 | 1.002831 |
def DEFINE_string(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name
_define_helper(flag_name, default_value, docstring, str, required) | Defines a flag of type 'string'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a string.
docstring: A helpful message explaining the use of the flag. | null | null | null | |
def DEFINE_integer(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name
_define_helper(flag_name, default_value, docstring, int, required) | Defines a flag of type 'int'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as an int.
docstring: A helpful message explaining the use of the flag. | null | null | null | |
return bool_str.lower() in ('true', 't', '1')
get_context_parser().add_argument(
'--' + flag_name,
nargs='?',
const=True,
help=docstring,
default=default_value,
type=str2bool)
# Add negated version, stay consistent with argparse with regard to
... | def DEFINE_boolean(flag_name, default_value, docstring): # pylint: disable=invalid-name
# Register a custom function for 'bool' so --flag=True works.
def str2bool(bool_str) | Defines a flag of type 'boolean'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a boolean.
docstring: A helpful message explaining the use of the flag. | 2.953009 | 3.608809 | 0.818278 |
def DEFINE_float(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name
_define_helper(flag_name, default_value, docstring, float, required) | Defines a flag of type 'float'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a float.
docstring: A helpful message explaining the use of the flag. | null | null | null | |
if not self._subparsers:
self._subparsers = self.parser.add_subparsers(dest=dest)
elif self._subparsers.dest != dest:
raise KeyError(
"Subparser names mismatch. You can only create one subcommand.")
return self._subparsers | def _get_subparsers(self, dest) | Get named subparsers. | 3.643791 | 3.308738 | 1.101263 |
if name not in self.children:
# Create the subparser.
subparsers = self._get_subparsers(dest)
parser = subparsers.add_parser(name, **kwargs)
self.children[name] = NamedParser(name, parser)
return self.children[name] | def get_subparser(self, name, dest="subcommand", **kwargs) | Get or create subparser. | 3.018031 | 2.780287 | 1.085511 |
def build_attr_string(attrs, supported=True):
'''Build a string that will turn any ANSI shell output the desired
colour.
attrs should be a list of keys into the term_attributes table.
'''
if not supported:
return ''
if type(attrs) == str:
attrs = [attrs]
result =... | Build a string that will turn any ANSI shell output the desired
colour.
attrs should be a list of keys into the term_attributes table. | null | null | null | |
def get_num_columns_and_rows(widths, gap_width, term_width):
'''Given a list of string widths, a width of the minimum gap to place
between them, and the maximum width of the output (such as a terminal
width), calculate the number of columns and rows, and the width of each
column, for the optimal lay... | Given a list of string widths, a width of the minimum gap to place
between them, and the maximum width of the output (such as a terminal
width), calculate the number of columns and rows, and the width of each
column, for the optimal layout. | null | null | null | |
def get_terminal_size():
'''Finds the width of the terminal, or returns a suitable default value.'''
def read_terminal_size_by_ioctl(fd):
try:
import struct, fcntl, termios
cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ,
... | Finds the width of the terminal, or returns a suitable default value. | null | null | null | |
def dict_to_nvlist(dict):
'''Convert a dictionary into a CORBA namevalue list.'''
result = []
for item in list(dict.keys()):
result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item])))
return result | Convert a dictionary into a CORBA namevalue list. | null | null | null | |
def nvlist_to_dict(nvlist):
'''Convert a CORBA namevalue list into a dictionary.'''
result = {}
for item in nvlist :
result[item.name] = item.value.value()
return result | Convert a CORBA namevalue list into a dictionary. | null | null | null | |
def filtered(path, filter):
'''Check if a path is removed by a filter.
Check if a path is in the provided set of paths, @ref filter. If
none of the paths in filter begin with @ref path, then True is
returned to indicate that the path is filtered out. If @ref path is
longer than the filter, an... | Check if a path is removed by a filter.
Check if a path is in the provided set of paths, @ref filter. If
none of the paths in filter begin with @ref path, then True is
returned to indicate that the path is filtered out. If @ref path is
longer than the filter, and starts with the filter, it is
... | null | null | null | |
def trim_filter(filter, levels=1):
'''Trim @ref levels levels from the front of each path in @filter.'''
trimmed = [f[levels:] for f in filter]
return [f for f in trimmed if f] | Trim @ref levels levels from the front of each path in @filter. | null | null | null | |
bug = self.request(
'bug/%s' % bug_number,
params={"include_fields": self. DEFAULT_SEARCH}
)
return Bug(self, **bug['bugs'][0]) | def get(self, bug_number) | Get a bug from Bugzilla. If there is a login token created during
object initialisation it will be part of the query string passed to
Bugzilla
:param bug_number: Bug Number that will be searched. If found will
return a Bug object.
>>> bugz... | 8.466086 | 10.628638 | 0.796535 |
if not self._have_auth:
raise BugsyException("Unfortunately you can't put bugs in Bugzilla"
" without credentials")
if not isinstance(bug, Bug):
raise BugsyException("Please pass in a Bug object when posting"
... | def put(self, bug) | This method allows you to create or update a bug on Bugzilla. You
will have had to pass in a valid username and password to the
object initialisation and recieved back a token.
:param bug: A Bug object either created by hand or by using get()
If there is no valid token ... | 3.893564 | 3.607081 | 1.079422 |
headers = {} if headers is None else headers.copy()
headers["User-Agent"] = "Bugsy"
kwargs['headers'] = headers
url = '%s/%s' % (self.bugzilla_url, path)
return self._handle_errors(self.session.request(method, url, **kwargs)) | 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. | 3.44711 | 3.658797 | 0.942143 |
dist_mat = dist_mat.copy()
# To ignore i == j distances
dist_mat[np.where(dist_mat == 0)] = np.inf
estimates = []
for i in range(dist_mat.shape[0]):
# Indices of the n closest distances
row = dist_mat[i]
dists = sorted(np.partition(row, n_closest)[:n_closest])
d... | 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 distances which are uninformati... | 4.081357 | 4.027997 | 1.013247 |
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.argmin(fs) + 1 | 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/> | 5.371024 | 5.384045 | 0.997582 |
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: {}'.format(unknown_fields))
return fields | def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str] | Clean lookup fields and check for errors. | 2.365708 | 2.234712 | 1.058619 |
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(fields) & STATUS_FIELDS.keys():
cur = db.cursor().execute... | 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 "lazily" fetch the requested fields as needed. For example,
episodes (which require a separate query per anime) will only be ... | 2.215233 | 2.114166 | 1.047805 |
return next(select(
db,
'aid=?',
(aid,),
fields=fields,
episode_fields=episode_fields,
)) | 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. | 5.081213 | 8.640629 | 0.588061 |
from django.conf import settings
import string
default_ltrs = string.digits + string.ascii_uppercase
default_letters = getattr(settings, 'DEFAULT_ALPHABET', default_ltrs)
if model_admin and hasattr(model_admin, 'DEFAULT_ALPHABET'):
default_letters = model_admin.DEFAULT_ALPHABET
if c... | 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. | 2.186392 | 2.029896 | 1.077095 |
if django.VERSION[1] <= 4:
result = queryset.values(field_name).annotate(
fl=FirstLetter(field_name)
).values('fl').distinct()
return set([res['fl'] for res in result if res['fl'] is not None])
else:
from django.db import connection
qn = connection.ops.qu... | 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. | 2.611701 | 2.587184 | 1.009476 |
if not getattr(cl.model_admin, 'alphabet_filter', False):
return
field_name = cl.model_admin.alphabet_filter
alpha_field = '%s__istartswith' % field_name
alpha_lookup = cl.params.get(alpha_field, '')
letters_used = _get_available_letters(field_name, cl.model.objects.all())
all_lett... | 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. | 3.67316 | 3.410278 | 1.077085 |
bits = token.split_contents()
if len(bits) == 3:
return AlphabetFilterNode(bits[1], bits[2])
elif len(bits) == 4:
if "=" in bits[3]:
key, val = bits[3].split('=')
return AlphabetFilterNode(bits[1], bits[2], strip_params=val)
else:
return Alpha... | 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.html if not
specified | 2.662171 | 2.245719 | 1.185443 |
installed_classes = {}
for entry_point in pkg_resources.iter_entry_points(cls.entry_point):
try:
plugin = entry_point.load()
except ImportError as e:
logger.error(
"Could not load plugin %s: %s", entry_point.name, str(e... | 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. | 2.048949 | 2.006062 | 1.021379 |
installed_classes = cls.get_installed_classes()
if name not in installed_classes:
raise ValueError("Unknown/unavailable %s" % cls.__name__.lower())
pluggable_class = installed_classes[name]
pluggable_class.validate_config(config)
instance = pluggable_clas... | 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. | 3.79123 | 3.356558 | 1.129499 |
name = os.path.basename(event.src_path)
name = name.replace(".yaml", "")
name = name.replace(".yml", "")
return name | def file_name(self, event) | Helper method for determining the basename of the affected file. | 3.45322 | 2.956619 | 1.167962 |
if os.path.isdir(event.src_path):
return
logger.debug("File created: %s", event.src_path)
name = self.file_name(event)
try:
result = self.target_class.from_config(
name, yaml.load(open(event.src_path))
)
except Excep... | 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. | 2.978541 | 2.563208 | 1.162037 |
if os.path.isdir(event.src_path):
return
logger.debug("file modified: %s", event.src_path)
name = self.file_name(event)
try:
config = yaml.load(open(event.src_path))
self.target_class.from_config(name, config)
except Exception:
... | 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. | 3.266182 | 2.827802 | 1.155025 |
logger.debug("file removed: %s", event.src_path)
name = self.file_name(event)
self.on_delete(self.target_class, name) | def on_deleted(self, event) | Deleted config file handler.
Simply fires the on_delete callback with the name of the deleted item. | 7.029455 | 6.209211 | 1.132101 |
self.on_deleted(events.FileDeletedEvent(event.src_path))
self.on_created(events.FileCreatedEvent(event.dest_path)) | def on_moved(self, event) | A move event is just proxied to an on_deleted call followed by
an on_created call. | 3.64661 | 2.592446 | 1.406629 |
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(results... | def command(state, args) | Search AniDB. | 5.406218 | 4.69729 | 1.150923 |
oldhash = self.session_hash
self.new_session_id()
try:
self.rdb.rename(oldhash,self.session_hash)
self.rdb.expire(self.session_hash,self.ttl)
except:
pass | 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 obt... | 5.436083 | 4.50137 | 1.207651 |
retval = self.__getitem__(key)
if not retval:
retval = default
return retval | 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
... | 5.947894 | 8.006509 | 0.742882 |
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 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)] | 4.159696 | 4.850101 | 0.857651 |
all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
return all_keys | def keys(self) | Return a list of all keys in the dictionary.
Returns:
list of str: [key1,key2,...,keyN] | 5.381944 | 6.541951 | 0.822682 |
all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
return all_values | def values(self) | Returns a list of all values in the dictionary.
Returns:
list of str: [value1,value2,...,valueN] | 5.878202 | 6.723538 | 0.874272 |
def sbessely(x, N):
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]
return out | Returns a vector of spherical bessel functions yn:
x: The argument.
N: values of n will run from 0 to N-1. | null | null | null | |
def sbesselj(x, N):
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) > 1e-20):
n = n + 1
u = 1 / (1 ... | Returns a vector of spherical bessel functions jn:
x: The argument.
N: values of n will run from 0 to N-1. | null | null | null | |
def sbesselh1(x, N):
"Spherical Hankel of the first kind"
jn = sbesselj(x, N)
yn = sbessely(x, N)
return jn + 1j * yn | Spherical Hankel of the first kind | null | null | null | |
def sbesselh2(x, N):
"Spherical Hankel of the second kind"
jn = sbesselj(x, N)
yn = sbessely(x, N)
return jn - 1j * yn | Spherical Hankel of the second kind | null | null | null | |
def sbesselj_array(xvec, N):
first_time = True
for x in xvec:
a = sbesselj(x, N)
if first_time:
out = np.array([a])
first_time = False
else:
out = np.concatenate([out, [a]], axis=0)
return out.T | 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() | null | null | null | |
def sbessely_array(xvec, N):
first_time = True
for x in xvec:
a = sbessely(x, N)
if first_time:
out = np.array([a])
first_time = False
else:
out = np.concatenate([out, [a]], axis=0)
return out.T | 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() | null | null | null | |
def sbesselj_sum(z, N):
b = sbesselj(z, N)
vvv = 2.0 * np.array(range(0, N), dtype=np.float64) + 1.0
sm = np.sum(np.sort(vvv * (b ** 2)))
return np.abs((sm - 1.0) / sm) + np.spacing(1) | 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 er... | null | null | null | |
chunks = [args for args in np.array_split(dicts, 20)]
results = parallel(_count, chunks, n_jobs=-1)
return _count(results) | def merge(dicts) | Merges a list of dicts, summing their values.
(Parallelized wrapper around `_count`) | 8.32516 | 5.571337 | 1.494284 |
counts = defaultdict(int)
for d in dicts:
for k, v in d.items():
counts[k] += v
return counts | def _count(dicts) | Merge a list of dicts, summing their values. | 2.128169 | 1.905064 | 1.117112 |
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 _chunks(iterable, n) | Splits an iterable into chunks of size n. | 7.78767 | 7.653318 | 1.017555 |
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)
yield chunk_... | def split_file(path, chunk_size=50000) | Splits the specified file into smaller files. | 2.228387 | 2.261135 | 0.985517 |
with open(path, 'r') as f:
for line in f:
if line.strip():
yield line | def doc_stream(path) | Generator to feed tokenized documents (treating each line as a document). | 2.626269 | 2.601474 | 1.009531 |
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 add_line(self, line) | Adds a given line string to the list of lines, validating the line
first. | 4.215422 | 3.855905 | 1.093238 |
adjusted_line = line.strip().lower()
return any([
adjusted_line.startswith(directive)
for directive in directives_by_section[self.section_name]
]) | 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. | 8.037738 | 5.806974 | 1.384153 |
stop_words = []
for line in open(stop_word_file):
if line.strip()[0:1] != "#":
for word in line.split(): # in case more than one per line
stop_words.append(word)
return stop_words | 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. | 2.931537 | 3.202521 | 0.915384 |
splitter = re.compile('[^a-zA-Z0-9_\\+\\-/]')
words = []
for single_word in splitter.split(text):
current_word = single_word.strip().lower()
#leave numbers in phrase, but don't count as words, since they tend to invalidate scores of their phrases
if len(current_word) > min_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. | 3.848498 | 4.035436 | 0.953676 |
sentence_delimiters = re.compile(u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]')
sentences = sentence_delimiters.split(text)
return sentences | def split_sentences(text) | Utility function to return a list of sentences.
@param text The text that must be split in to sentences. | 4.205394 | 4.697473 | 0.895246 |
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 in params if x != '')
if len(new_params) > 0:
... | def param_redirect(request, viewname, *args) | Redirect and keep URL parameters if any. | 2.936073 | 2.889839 | 1.015999 |
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 in env"
if not release:
release = paths.get_current_release_name(... | def backup_db(release=None, limit=5) | Backup database and associate it with current release | 2.601126 | 2.576214 | 1.00967 |
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 in env"
if not release:
release = paths.get_current_release_name(... | def restore_db(release=None) | Restores backup back to version, uses current version by default. | 2.34413 | 2.302099 | 1.018257 |
'''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:
resu... | 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. | 4.910386 | 3.290015 | 1.492512 |
'''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... | 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. | 5.100266 | 3.298578 | 1.546201 |
'''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.... | def kind(self) | The kind of this execution context. | 5.645111 | 5.121712 | 1.102192 |
'''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 owner_name(self) | The name of the RTObject that owns this context. | 10.218175 | 6.07331 | 1.682472 |
'''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 participant_names(self) | The names of the RTObjects participating in this context. | 14.965105 | 8.144485 | 1.837452 |
return self.create_manager(instance,
self.rating_model._base_manager.__class__) | 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(). | 19.038988 | 15.61791 | 1.219048 |
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.filter(**(self.core_filters))
def add(self... | def create_manager(self, instance, superclass) | Dynamically create a RelatedManager to handle the back side of the (G)FK | 2.196009 | 2.190405 | 1.002559 |
result = 0
for i in range(len(value)):
result += self.seed * result + ord(value[i])
return (self.capacity - 1) % result | 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 | 4.014681 | 3.963935 | 1.012802 |
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)
for h in self.hash_function:
local_hash =... | def is_contains(self, data) | Judge the data whether is already exist if each bit of hash code is 1 then data exist. | 8.062932 | 7.467255 | 1.079772 |
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)
se... | def insert(self, data) | Insert 1 into each bit by local_hash | 8.074769 | 6.774607 | 1.191917 |
now = datetime.datetime.now()
sections = [
Section(
"Auto-generated by Lighthouse (%s)" % now.strftime("%c"),
self.global_stanza,
self.defaults_stanza
)
]
meta_stanzas = [
MetaFrontendStanza(
... | def generate(self, clusters, version=None) | Generates HAProxy config file content based on a given list of
clusters. | 3.759031 | 3.711908 | 1.012695 |
meta_clusters = collections.defaultdict(list)
for cluster in clusters:
if not cluster.meta_cluster:
continue
meta_clusters[cluster.meta_cluster].append(cluster)
unconfigured_meta_clusters = [
name for name in meta_clusters.keys()
... | 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 the mapping... | 2.75334 | 2.444182 | 1.126487 |
render_size = max(size, GenAvatar.MAX_RENDER_SIZE)
image = Image.new('RGB', (render_size, render_size),
cls._background_color(string))
draw = ImageDraw.Draw(image)
font = cls._font(render_size)
text = cls._text(string)
draw.text(
... | 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) | 2.945864 | 3.004305 | 0.980548 |
seed(s)
r = v = b = 255
while r + v + b > 255 * 2:
r = randint(0, 255)
v = randint(0, 255)
b = randint(0, 255)
return (r, v, b) | 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). | 2.558608 | 3.033565 | 0.843433 |
# 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 _font(size) | Returns a PIL ImageFont instance.
:param size: size of the avatar, in pixels | 3.414974 | 3.79682 | 0.89943 |
width, height = font.getsize(text)
left = (size - width) / 2.0
top = (size - height) / 3.0
return left, top | def _text_position(size, text, font) | Returns the left-top point where the text should be positioned. | 2.827411 | 2.493964 | 1.133702 |
if self.Death:
age = self.Death - self.Born
else:
age = datetime.date.today() - self.Born
return age.days | def age(self) | Calculates the animals age, relative to the current date (if alive) or the date of death (if not). | 4.564208 | 3.785524 | 1.2057 |
try:
self.breeding_males.all()[0].Cage
if int(self.breeding_males.all()[0].Cage) == int(self.Cage):
type = "resident-breeder"
else:
type = "non-resident-breeder"
except IndexError:
type = "unknown-br... | 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 to the first breeding cag... | 3.631856 | 3.323936 | 1.092637 |
try:
self.breeding_females.all()[0].Cage
if int(self.breeding_females.all()[0].Cage) == int(self.Cage):
type = "resident-breeder"
else:
type = "non-resident-breeder"
except IndexError:
type = "unknow... | 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 relative to the first breeding c... | 3.499139 | 3.246607 | 1.077783 |
if self.Death:
self.Alive = False
super(Animal, self).save() | 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. | 14.135644 | 3.057373 | 4.623461 |
if self.End:
age = self.End - self.Start
else:
age = datetime.date.today() - self.Start
return age.days | 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. | 4.63781 | 4.850231 | 0.956204 |
return Animal.objects.filter(Breeding=self, Weaned__isnull=True, Alive=True) | def unweaned(self) | This attribute generates a queryset of unweaned animals for this breeding cage. It is filtered for only Alive animals. | 20.605387 | 5.865083 | 3.51323 |
if int(self.Male.all()[0].Cage) == int(self.Cage):
type = "resident breeder"
else:
type = "non-resident breeder"
return type | 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. | 6.841085 | 6.286355 | 1.088244 |
if self.End:
self.Active = False
#if self.Cage:
# if self.Females:
# for female_breeder in self.Females:
# female_breeder.Cage = self.Cage
# female_breeder.save()
# if self.Male:
# ... | 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 B... | 3.165561 | 2.02608 | 1.562407 |
handler = ConfigFileChangeHandler(
self.target_class, on_add, on_update, on_delete
)
for file_name in os.listdir(self.file_path):
if os.path.isdir(os.path.join(self.file_path, file_name)):
continue
if (
not self.target... | 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 missed. | 2.664617 | 2.577156 | 1.033937 |
def matplotlibensure(func):
@wraps(func)
def wrap(*args):
if MPLINSTALLED == False:
raise ImportError(msg)
return func(*args)
return wrap | If matplotlib isn't installed, this decorator alerts the user and
suggests how one might obtain the package. | null | null | null | |
return datetime.datetime(
date.year, date.month, date.day,
tzinfo=datetime.timezone.utc).timestamp() | def to_ts(date: datetime.date) -> float | Convert date to timestamp.
>>> to_ts(datetime.date(2001, 1, 2))
978393600.0 | 3.403236 | 4.054824 | 0.839305 |
return datetime.datetime.fromtimestamp(
ts, tz=datetime.timezone.utc).date() | def to_date(ts: float) -> datetime.date | Convert timestamp to date.
>>> to_date(978393600.0)
datetime.date(2001, 1, 2) | 4.259632 | 5.586312 | 0.762512 |
response = ""
extra = ""
while True:
try:
chunk = sock.recv(buffer_size)
if chunk:
response += chunk
except socket.error as e:
if e.errno not in [errno.EAGAIN, errno.EINTR]:
raise
if not response:
... | 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. | 2.286945 | 2.199088 | 1.039951 |
'''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
... | 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
... | 9.659549 | 1.40123 | 6.893623 |
'''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_component(self, path) | Is the node pointed to by @ref path a component? | 4.959646 | 3.245067 | 1.528365 |
'''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_directory(self, path) | Is the node pointed to by @ref path a directory (name servers and
naming contexts)? | 12.101966 | 2.970522 | 4.07402 |
'''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_manager(self, path) | Is the node pointed to by @ref path a manager? | 5.180839 | 3.190476 | 1.623845 |
'''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_nameserver(self, path) | Is the node pointed to by @ref path a name server (specialisation
of directory nodes)? | 9.021981 | 2.90442 | 3.106294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.