code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def parse_tablature(lines):
lines = [parse_line(l) for l in lines]
return Tablature(lines=lines) | Parse a list of lines into a `Tablature`. |
def normalize(v):
if 0 == np.linalg.norm(v):
return v
return v / np.linalg.norm(v) | Normalize a vector based on its 2 norm. |
def stop(self):
if self._progressing:
self._progressing = False
self._thread.join() | Stop the progress bar. |
def scheduled_status_delete(self, id):
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
self.__api_request('DELETE', url) | Deletes a scheduled status. |
def backup(filename):
tmp_file = "/tmp/%s" % filename
with cd("/"):
postgres("pg_dump -Fc %s > %s" % (env.proj_name, tmp_file))
run("cp %s ." % tmp_file)
sudo("rm -f %s" % tmp_file) | Backs up the project database. |
def _can_merge_tail(self):
if len(self.storage) < 2:
return False
return self.storage[-2].w <= self.storage[-1].w * self.rtol | Checks if the two last list elements can be merged |
def _get_n_args(self, args, example, n):
if len(args) != n:
msg = (
'Got unexpected number of arguments, expected {}. '
'(example: "{} config {}")'
).format(n, get_prog(), example)
raise PipError(msg)
if n == 1:
return args[... | Helper to make sure the command got the right number of arguments |
def form_valid(self, forms):
for key, form in forms.items():
setattr(self, '{}_object'.format(key), form.save())
return super(MultipleModelFormMixin, self).form_valid(forms) | If the form is valid, save the associated model. |
def sha1(filename):
filename = unmap_file(filename)
if filename not in file_cache:
cache_file(filename)
if filename not in file_cache:
return None
pass
if file_cache[filename].sha1:
return file_cache[filename].sha1.hexdigest()
sha1 = hashlib.sha1()
for lin... | Return SHA1 of filename. |
def load_template(self, templatename, template_string=None):
if template_string is not None:
return Template(template_string, **self.tmpl_options)
if '/' not in templatename:
templatename = '/' + templatename.replace('.', '/') + '.' +\
self.extension
r... | Loads a template from a file or a string |
def degrees(x):
if isinstance(x, UncertainFunction):
mcpts = np.degrees(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.degrees(x) | Convert radians to degrees |
def _os_dispatch(func, *args, **kwargs):
if __grains__['kernel'] in SUPPORTED_BSD_LIKE:
kernel = 'bsd'
else:
kernel = __grains__['kernel'].lower()
_os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func))
if callable(_os_func):
return _os_func(*args, **kwargs) | Internal, dispatches functions by operating system |
def log_method(log, level=logging.DEBUG):
def decorator(func):
func_name = func.__name__
@six.wraps(func)
def wrapper(self, *args, **kwargs):
if log.isEnabledFor(level):
pretty_args = []
if args:
pretty_args.extend(str(a) for a ... | Logs a method and its arguments when entered. |
def proxy(self):
headers = self.request.headers.filter(self.ignored_request_headers)
qs = self.request.query_string if self.pass_query_string else ''
if (self.request.META.get('CONTENT_LENGTH', None) == '' and
get_django_version() == '1.10'):
del self.request.META['CO... | Retrieve the upstream content and build an HttpResponse. |
def homer_tagdirectory(self):
self.parse_gc_content()
self.parse_re_dist()
self.parse_tagLength_dist()
self.parse_tagInfo_data()
self.parse_FreqDistribution_data()
self.homer_stats_table_tagInfo()
return sum([len(v) for v in self.tagdir_data.values()]) | Find HOMER tagdirectory logs and parse their data |
def _post_init(self, name, container=None):
self.name = name
self.container = container | Called automatically by container after container's class construction. |
def confirms(self, txid):
txid = deserialize.txid(txid)
return self.service.confirms(txid) | Returns number of confirms or None if unpublished. |
def download(query, num_results):
name = quote(query)
name = name.replace(' ','+')
url = 'http://www.google.com/search?q=' + name
if num_results != 10:
url += '&num=' + str(num_results)
req = request.Request(url, headers={
'User-Agent' : choice(user_agents),
})
try:
response = request.urlopen(req)
except... | downloads HTML after google search |
def do_get_aliases(name):
metric_schemas = MetricSchemas()
aliases = metric_schemas.get_aliases(name)
for alias in aliases:
do_print(alias) | Get aliases for given metric name |
def apply(self, func, *args, **kwds):
wrapped = self._wrapped_apply(func, *args, **kwds)
n_repeats = 3
timed = timeit.timeit(wrapped, number=n_repeats)
samp_proc_est = timed / n_repeats
est_apply_duration = samp_proc_est / self._SAMP_SIZE * self._nrows
if est_apply_durati... | Apply the function to the transformed swifter object |
def dt2ts(dt):
assert isinstance(dt, (datetime.datetime, datetime.date))
ret = time.mktime(dt.timetuple())
if isinstance(dt, datetime.datetime):
ret += 1e-6 * dt.microsecond
return ret | Converts to float representing number of seconds since 1970-01-01 GMT. |
def serialize_for_header(key, value):
if key in QUOTE_FIELDS:
return json.dumps(value)
elif isinstance(value, str):
if " " in value or "\t" in value:
return json.dumps(value)
else:
return value
elif isinstance(value, list):
return "[{}]".format(", ".jo... | Serialize value for the given mapping key for a VCF header line |
def match(self, p_todo):
for my_tag in config().hidden_item_tags():
my_values = p_todo.tag_values(my_tag)
for my_value in my_values:
if not my_value in (0, '0', False, 'False'):
return False
return True | Returns True when p_todo doesn't have a tag to mark it as hidden. |
def atmos_worker(srcs, window, ij, args):
src = srcs[0]
rgb = src.read(window=window)
rgb = to_math_type(rgb)
atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"])
return scale_dtype(atmos, args["out_dtype"]) | A simple atmospheric correction user function. |
def _validate_jp2c(self, boxes):
jp2h_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2h']
jp2h_idx = jp2h_lst[0]
jp2c_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2c']
if len(jp2c_lst) == 0:
msg =... | Validate the codestream box in relation to other boxes. |
def blockmix_salsa8(BY, Yi, r):
start = (2 * r - 1) * 16
X = BY[start:start+16]
tmp = [0]*16
for i in xrange(2 * r):
salsa20_8(X, tmp, BY, i * 16, BY, Yi + i*16)
for i in xrange(r):
BY[i * 16:(i * 16)+(16)] = BY[Yi + (i * 2) * 16:(Yi + (i * 2) * 16)+(16)]
BY[(i + r) * 16:((i ... | Blockmix; Used by SMix |
def assert_service_check(self, name, status=None, tags=None, count=None, at_least=1, hostname=None, message=None):
tags = normalize_tags(tags, sort=True)
candidates = []
for sc in self.service_checks(name):
if status is not None and status != sc.status:
continue
... | Assert a service check was processed by this stub |
def energy_data():
cur = db.cursor().execute()
original = TimeSeries()
original.initialize_from_sql_cursor(cur)
original.normalize("day", fusionMethod = "sum")
return itty.Response(json.dumps(original, cls=PycastEncoder), content_type='application/json') | Connects to the database and loads Readings for device 8. |
def _create_peephole_variables(self, dtype):
self._w_f_diag = tf.get_variable(
self.W_F_DIAG,
shape=[self._hidden_size],
dtype=dtype,
initializer=self._initializers.get(self.W_F_DIAG),
partitioner=self._partitioners.get(self.W_F_DIAG),
regularizer=self._regularizers.g... | Initialize the variables used for the peephole connections. |
def stop(self):
self._stop_event.set()
if self._func_stop_event is not None:
self._func_stop_event.set()
self.join(timeout=1)
if self.isAlive():
print('Failed to stop thread') | stop the thread, return after thread stopped |
def detect_output_type(args):
if not args['single'] and not args['multiple']:
if len(args['query']) > 1 or len(args['out']) > 1:
args['multiple'] = True
else:
args['single'] = True | Detect whether to save to a single or multiple files. |
def as_yml(self):
return YmlFileEvent(name=str(self.name),
subfolder=str(self.subfolder)) | Return yml compatible version of self |
def make_vertical_box(cls, children, layout=Layout(), duplicates=False):
"Make a vertical box with `children` and `layout`."
if not duplicates: return widgets.VBox(children, layout=layout)
else: return widgets.VBox([children[0], children[2]], layout=layout) | Make a vertical box with `children` and `layout`. |
def utcnow_ts():
if utcnow.override_time is None:
return int(time.time())
return calendar.timegm(utcnow().timetuple()) | Timestamp version of our utcnow function. |
def rollout(env, acts):
total_rew = 0
env.reset()
steps = 0
for act in acts:
_obs, rew, done, _info = env.step(act)
steps += 1
total_rew += rew
if done:
break
return steps, total_rew | Perform a rollout using a preset collection of actions |
def _compute_softmax(scores):
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.ap... | Compute softmax probability over raw logits. |
def _add_history(self, entry_type, entry):
meta_string = "{time} - {etype} - {entry}".format(
time=self._time(),
etype=entry_type.upper(),
entry=entry)
self._content['history'].insert(0, meta_string)
self.logger(meta_string) | Generic method to add entry as entry_type to the history |
def _get_anelastic_attenuation_term(self, C, rrup):
f_atn = np.zeros(len(rrup))
idx = rrup >= 80.0
f_atn[idx] = (C["c20"] + C["Dc20"]) * (rrup[idx] - 80.0)
return f_atn | Returns the anelastic attenuation term defined in equation 25 |
async def on_message(self, event):
if event.chat_id != self.chat_id:
return
self.message_ids.append(event.id)
if event.out:
text = '>> '
else:
sender = await event.get_sender()
text = '<{}> '.format(sanitize_str(
utils.get_d... | Event handler that will add new messages to the message log. |
def reflected_light_intensity(self):
self._ensure_mode(self.MODE_REFLECT)
return self.value(0) * self._scale('REFLECT') | A measurement of the reflected light intensity, as a percentage. |
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0):
filter_size = int(hidden_size * isemhash_filter_size_multiplier)
x = 0.5 * (x - 1.0)
with tf.variable_scope("isemhash_unbottleneck"):
h1a = tf.layers.dense(x, filter_size, name="hidden1a")
h1b = tf.layers.dense(1.0 - x, filter... | Improved semantic hashing un-bottleneck. |
def make_tls_config(app_config):
if not app_config['DOCKER_TLS']:
return False
cert_path = app_config['DOCKER_TLS_CERT_PATH']
if cert_path:
client_cert = '{0}:{1}'.format(
os.path.join(cert_path, 'cert.pem'),
os.path.join(cert_path, 'key.pem'))
ca_cert = os.pa... | Creates TLS configuration object. |
def uninstall_hook(ctx):
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successfully uninstalled gitlint commit-msg hook from {0}".format(hook_path))
... | Uninstall gitlint commit-msg hook. |
def frontend(ctx, dev, rebuild, no_install, build_type):
install_frontend(instance=ctx.obj['instance'],
forcerebuild=rebuild,
development=dev,
install=not no_install,
build_type=build_type) | Build and install frontend |
def from_name_func(cls, path:PathOrStr, fnames:FilePathList, label_func:Callable, valid_pct:float=0.2, **kwargs):
"Create from list of `fnames` in `path` with `label_func`."
src = ImageList(fnames, path=path).split_by_rand_pct(valid_pct)
return cls.create_from_ll(src.label_from_func(label_func),... | Create from list of `fnames` in `path` with `label_func`. |
def _compute_hidden_activations(self, X):
self._compute_input_activations(X)
acts = self.input_activations_
if (callable(self.activation_func)):
args_dict = self.activation_args if (self.activation_args) else {}
X_new = self.activation_func(acts, **args_dict)
else... | Compute hidden activations given X |
def flushInput(self):
self.buf = ''
saved_timeout = self.timeout
self.timeout = 0.5
self._recv()
self.timeout = saved_timeout
self.buf = ''
self.debug("flushInput") | flush any pending input |
def connections(request, edges):
edge_list, node_list = parse.graph_definition(edges)
data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)}
return render_to_response('miner/connections.html', data) | Plot a force-directed graph based on the edges provided |
def configure_terminal(self):
client = self.guake.settings.general
word_chars = client.get_string('word-chars')
if word_chars:
self.set_word_char_exceptions(word_chars)
self.set_audible_bell(client.get_boolean('use-audible-bell'))
self.set_sensitive(True)
curs... | Sets all customized properties on the terminal |
def _find_image_ext(path, number=None):
if number is not None:
path = path.format(number)
path = os.path.splitext(path)[0]
for ext in _KNOWN_IMG_EXTS:
this_path = '%s.%s' % (path, ext)
if os.path.isfile(this_path):
break
else:
ext = 'png'
return ('%s.%s' %... | Find an image, tolerant of different file extensions. |
def factory(obj, field, source_text, lang, context=""):
obj_classname = obj.__class__.__name__
obj_module = obj.__module__
source_md5 = checksum(source_text)
translation = ""
field_lang = trans_attr(field,lang)
if hasattr(obj,field_lang) and getattr(obj,field_lang)!="":
translation = getattr(obj,field_la... | Static method that constructs a translation based on its contents. |
def library_directories(self) -> typing.List[str]:
def listify(value):
return [value] if isinstance(value, str) else list(value)
is_local_project = not self.is_remote_project
folders = [
f
for f in listify(self.settings.fetch('library_folders', ['libs']))
... | The list of directories to all of the library locations |
def getInterimValue(self, keyword):
interims = filter(lambda item: item["keyword"] == keyword,
self.getInterimFields())
if not interims:
logger.warning("Interim '{}' for analysis '{}' not found"
.format(keyword, self.getKeyword()))
... | Returns the value of an interim of this analysis |
def _interp1d(self):
lines = len(self.hrow_indices)
for num, data in enumerate(self.tie_data):
self.new_data[num] = np.empty((len(self.hrow_indices),
len(self.hcol_indices)),
data.dtype)
for cnt ... | Interpolate in one dimension. |
def make_modules(self, groups, code_opts):
modules = []
for raw_module, raw_funcs in groups:
module = raw_module[0].strip().strip(string.punctuation)
funcs = [func.strip() for func in raw_funcs]
args = [self.database.query_args(func, raw=True)
for ... | Build shellcoding files for the module. |
def xrevrange(self, stream, start='+', stop='-', count=None):
if count is not None:
extra = ['COUNT', count]
else:
extra = []
fut = self.execute(b'XREVRANGE', stream, start, stop, *extra)
return wait_convert(fut, parse_messages) | Retrieve messages from a stream in reverse order. |
def substitute(self, values: Dict[str, Any]) -> str:
return self.template.substitute(values) | generate url with url template |
def as_dict(self):
def conv(v):
if isinstance(v, SerializableAttributesHolder):
return v.as_dict()
elif isinstance(v, list):
return [conv(x) for x in v]
elif isinstance(v, dict):
return {x:conv(y) for (x,y) in v.items()}
... | Returns a JSON-serializeable object representing this tree. |
def clear(self, username, project):
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
token=self.client.api_token... | Clear the cache for given project. |
def get(self, flex_sched_rule_id):
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | Retrieve the information for a flexscheduleRule entity. |
def _exception_free_callback(self, callback, *args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception:
self._logger.exception("An exception occurred while calling a hook! ",exc_info=True)
return None | A wrapper that remove all exceptions raised from hooks |
def _get_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--rom', '-r',
type=str,
help='The path to the ROM to play.',
required=True,
)
parser.add_argument('--mode', '-m',
type=str,
default='human',
choices=['human', 'rand... | Parse arguments from the command line and return them. |
def price_rounding(price, decimals=2):
try:
exponent = D('.' + decimals * '0')
except InvalidOperation:
exponent = D()
return price.quantize(exponent, rounding=ROUND_UP) | Takes a decimal price and rounds to a number of decimal places |
def net_send(out_data, conn):
print('Sending {} bytes'.format(len(out_data)))
conn.send(out_data) | Write pending data from websocket to network. |
def limit_chars(function, *args, **kwargs):
output_chars_limit = args[0].reddit_session.config.output_chars_limit
output_string = function(*args, **kwargs)
if -1 < output_chars_limit < len(output_string):
output_string = output_string[:output_chars_limit - 3] + '...'
return output_string | Truncate the string returned from a function and return the result. |
def reset_group_subscription(self):
if self._user_assignment:
raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
assert self.subscription is not None, 'Subscription required'
self._group_subscription.intersection_update(self.subscription) | Reset the group's subscription to only contain topics subscribed by this consumer. |
def angprofile(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
localpath = NameFactory.angprofile_format.format(**kwargs_copy)
if kwargs.get('fullpath', False):
return self.fullpath(localpath=lo... | return the file name for sun or moon angular profiles |
def info(self):
return (self.start_pc, self.end_pc,
self.handler_pc, self.get_catch_type()) | tuple of the start_pc, end_pc, handler_pc and catch_type_ref |
def process_frames(self, data, sampling_rate, offset=0, last=False, utterance=None, corpus=None):
if offset == 0:
self.steps_sorted = list(nx.algorithms.dag.topological_sort(self.graph))
self._create_buffers()
self._define_output_buffers()
self._update_buffers(None, d... | Execute the processing of this step and all dependent parent steps. |
def filter(self, **kwargs):
keys = self.filter_keys(**kwargs)
return self.keys_to_values(keys) | Filter data according to the given arguments. |
def toposort_classes(classes):
def get_class_topolist(class_name, name_to_class, processed_classes, current_trace):
if class_name in processed_classes:
return []
if class_name in current_trace:
raise AssertionError(
'Encountered self-reference in dependency ch... | Sort class metadatas so that a superclass is always before the subclass |
def solve_sdr(prob, *args, **kwargs):
X = cvx.Semidef(prob.n + 1)
W = prob.f0.homogeneous_form()
rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X)))
rel_constr = [X[-1, -1] == 1]
for f in prob.fs:
W = f.homogeneous_form()
lhs = cvx.sum_entries(cvx.mul_elemwise(W, X))
... | Solve the SDP relaxation. |
def update_entity(self, entity, agent=None, metadata=None):
body = {}
if agent:
body["agent_id"] = utils.get_id(agent)
if metadata:
body["metadata"] = metadata
if body:
uri = "/%s/%s" % (self.uri_base, utils.get_id(entity))
resp, body = sel... | Updates the specified entity's values with the supplied parameters. |
def solve_let(expr, vars):
lhs_value = solve(expr.lhs, vars).value
if not isinstance(lhs_value, structured.IStructured):
raise errors.EfilterTypeError(
root=expr.lhs, query=expr.original,
message="The LHS of 'let' must evaluate to an IStructured. Got %r."
% (lhs_value... | Solves a let-form by calling RHS with nested scope. |
def plot_data(self, proj, ax):
x, y = proj
ax.scatter(self.ig.independent_data[x],
self.ig.dependent_data[y], c='b') | Creates and plots a scatter plot of the original data. |
def run_dexseq(data):
if dd.get_dexseq_gff(data, None):
data = dexseq.bcbio_run(data)
return [[data]] | Quantitate exon-level counts with DEXSeq |
def _run_gvcfgenotyper(data, region, vrn_files, out_file):
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
input_file = "%s-inputs.txt" % utils.splitext_plus(tx_out_file)[0]
with open(input_file, "w") as out_handle:
out_handle... | Run gvcfgenotyper on a single gVCF region in input file. |
def __prepare_bloom(self):
self.__bloom = pybloom_live.ScalableBloomFilter()
columns = [getattr(self.__table.c, key) for key in self.__update_keys]
keys = select(columns).execution_options(stream_results=True).execute()
for key in keys:
self.__bloom.add(tuple(key)) | Prepare bloom for existing checks |
def sinh(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sinh,
(BigFloat._implicit_convert(x),),
context,
) | Return the hyperbolic sine of x. |
def sign_transaction(self, txins: Union[TxOut],
tx: MutableTransaction) -> MutableTransaction:
solver = P2pkhSolver(self._private_key)
return tx.spend(txins, [solver for i in txins]) | sign the parent txn outputs P2PKH |
def debug(self, *args) -> "Err":
error = self._create_err("debug", *args)
print(self._errmsg(error))
return error | Creates a debug message |
def authenticate(self, provider=None, identifier=None):
"Fetch user for a given provider by id."
provider_q = Q(provider__name=provider)
if isinstance(provider, Provider):
provider_q = Q(provider=provider)
try:
access = AccountAccess.objects.filter(
... | Fetch user for a given provider by id. |
def ResidualFeedForward(feature_depth,
feedforward_depth,
dropout,
mode):
return layers.Residual(
layers.LayerNorm(),
layers.Dense(feedforward_depth),
layers.Relu(),
layers.Dropout(rate=dropout, mode=mode),
layers.De... | Residual feed-forward layer with normalization at start. |
def query_instances(session, client=None, **query):
if client is None:
client = session.client('ec2')
p = client.get_paginator('describe_instances')
results = p.paginate(**query)
return list(itertools.chain(
*[r["Instances"] for r in itertools.chain(
*[pp['Reservations'] for ... | Return a list of ec2 instances for the query. |
def _create_consumer(self):
if not self.closed:
try:
self.logger.debug("Creating new kafka consumer using brokers: " +
str(self.settings['KAFKA_HOSTS']) + ' and topic ' +
self.settings['KAFKA_TOPIC_PREFIX'] +
... | Tries to establing the Kafka consumer connection |
def guidance_UV(index):
if 0 < index < 3:
guidance = "Low exposure. No protection required. You can safely stay outside"
elif 2 < index < 6:
guidance = "Moderate exposure. Seek shade during midday hours, cover up and wear sunscreen"
elif 5 < index < 8:
guidance = "High exposure. Seek... | Return Met Office guidance regarding UV exposure based on UV index |
def peek(self):
c = self.connection.cursor()
first_tweet_id = c.execute("SELECT tweet from tweetlist where label='first_tweet'").next()[0]
if first_tweet_id is None:
return None
tweet = c.execute("SELECT message from tweets WHERE id=?", (first_tweet_id,)).next()[0]
c.... | Peeks at the first of the list without removing it. |
def pop_int(self, key: str, default: Any = DEFAULT) -> int:
value = self.pop(key, default)
if value is None:
return None
else:
return int(value) | Performs a pop and coerces to an int. |
def find_farthest(point, hull):
d_start = np.sum((point-hull[0,:])**2)
d_end = np.sum((point-hull[-1,:])**2)
if d_start > d_end:
i = 1
inc = 1
term = hull.shape[0]
d2_max = d_start
else:
i = hull.shape[0]-2
inc = -1
term = -1
d2_max = d_end... | Find the vertex in hull farthest away from a point |
def list(self, prefix='', delimiter=None):
return self.service._list(
bucket=self.name, prefix=prefix, delimiter=delimiter, objects=True
) | Limits a list of Bucket's objects based on prefix and delimiter. |
def add_login_attempt_task(user_agent, ip_address, username,
http_accept, path_info, login_valid):
store_login_attempt(user_agent, ip_address, username,
http_accept, path_info, login_valid) | Create a record for the login attempt |
def fix_quotes(cls, query_string):
if query_string.count('"') % 2 == 0:
return query_string
fields = []
def f(match):
fields.append(match.string[match.start():match.end()])
return ''
terms = re.sub(r'[^\s:]*:("[^"]*"|[^\s]*)', f, query_string)
... | Heuristic attempt to fix unbalanced quotes in query_string. |
def context_list_users(zap_helper, context_name):
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for th... | List the users available for a given context. |
def pt_scale(pt=(0.0, 0.0), f=1.0):
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)]) | Return given point scaled by factor f from origin. |
def policy_get(request, policy_id, **kwargs):
policy = neutronclient(request).show_qos_policy(
policy_id, **kwargs).get('policy')
return QoSPolicy(policy) | Get QoS policy for a given policy id. |
def config_logging(level):
logger = logging.getLogger('')
logger.setLevel(level)
if level < logging.DEBUG:
log_format = "%(asctime)s %(message)s"
else:
log_format = "%(asctime)s %(module)s : %(lineno)d %(message)s"
sh = logging.StreamHandler()
sh.formatter = logging.Formatter(fm... | Configure the logging given the level desired |
def run(self, **kwargs):
try:
loop = IOLoop()
app = self.make_app()
app.listen(self.port)
loop.start()
except socket.error as serr:
if serr.errno != errno.EADDRINUSE:
raise serr
else:
logger.warning('... | Start the tornado server, run forever |
def _HuntOutputPluginStateFromRow(self, row):
plugin_name, plugin_args_bytes, plugin_state_bytes = row
plugin_descriptor = rdf_output_plugin.OutputPluginDescriptor(
plugin_name=plugin_name)
if plugin_args_bytes is not None:
plugin_args_cls = plugin_descriptor.GetPluginArgsClass()
if plug... | Builds OutputPluginState object from a DB row. |
def natural_neighbor(xp, yp, variable, grid_x, grid_y):
return natural_neighbor_to_grid(xp, yp, variable, grid_x, grid_y) | Wrap natural_neighbor_to_grid for deprecated natural_neighbor function. |
def _make_candidate_from_result(self, result):
candidate = Candidate()
candidate.match_addr = result['formatted_address']
candidate.x = result['geometry']['location']['lng']
candidate.y = result['geometry']['location']['lat']
candidate.locator = self.LOCATOR_MAPPING.get(result['g... | Make a Candidate from a Google geocoder results dictionary. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.