content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def w(path):
"""return True if path exists and has write permission (for the current user), else False"""
return os.path.exists(path) and os.access(path, os.W_OK) | 6135144e7f305dfafa44e0080d27b7dd432fd2c6 | 649,589 |
import struct
def bytes_to_value(data):
"""Convert bytes recevied via CAN to float value."""
assert len(data) == 4
# convert bytes to signed int (note: bytes in data are in reversed order)
qval = struct.unpack("<i", data[::-1])[0]
# convert q-value to human-rea... | 18c4bf000ab52a9f3b1631a774f530d6e7437d39 | 649,590 |
import re
def get_assembly_line_pattern(stripped):
"""
Return regexp pattern used for matching regular assembly lines in the file.
Support for stripped and non-stripped versions.
Need to match non-stripped lines:
'0x00007ffff7fbf158 <+120>: and $0xfffffffffffffff8,%r12'
and stripped lines:
... | 527fa2c7f35eae1cfd71fa3a98a85017281ffbb7 | 649,591 |
def active_view(request, view_name):
"""
Sets an HTML class attribute depending on the selection.
:param request: HttpRequest
:param view_name: (str)
:return: (str) HTML class attribute
"""
resolve_view_name = getattr(request.resolver_match, 'view_name', None)
if resolve_view_name is ... | c2773fb42995bb6286605cb49385c2f63bdf2f7a | 649,592 |
import os
def get_all_files_from_path(directory_path,
file_extension=None):
"""
directory_path:
Given path that already exists.
file_extension:
Only return files that have a given extension.
Returns:
Returns back a set a filenames with the provided... | b409b9d1547d2b153431942910a0a3bd35b7da32 | 649,593 |
def iso_format(datetime):
"""
Generates an ISO formatted datetime based on what the LaunchKey API expects.
This is a standard ISO datetime without microseconds.
:param datetime: datetime.datetime object
:return: ISO formatted string IE: 2017-10-03T22:50:15Z
"""
return datetime.strftime("%Y-%... | 8b98ac0d2accbc9c8be2805886c1805f7e77fe9f | 649,595 |
def data_files():
"""
Translates the manifest into the datafiles
"""
# with open(os.path.join(DIR, 'MANIFEST')) as manifest:
# return [line.strip() for line in manifest if line.strip() and '#' not in line]
return [] | 1b0cd2b56eb00a334772995e11df7fbb9f9c4741 | 649,596 |
import time
def epoch_milliseconds(d):
"""Convert a datetime to a number of milliseconds since the epoch."""
return time.mktime(d.timetuple()) * 1000 | 4f66faf9daf425af56c64c875e294c9ef02c7752 | 649,597 |
def robot_wait_for_human_to_tidy(agents, self_state, self_name):
"""
@param agents:
@param self_state:
@param self_name:
@return:
@semantic_name: wait
"""
return agents | 4867183acaae64ff40c6835fe2c2a8f9a6f84047 | 649,598 |
def reconstruct_action_sequence(goal, prev_states_actions):
"""reconstruct action sequence by traversing a previous state/action map"""
action_sequence = []
state = goal
# work our way backwards from the goal state to the start state:
while prev_states_actions[state] is not None:
# where did... | 81749226e6cd6398b605c7a8b47b7e3aec803a01 | 649,599 |
def get_number_alien_rows(game_settings, starship_height, alien_height):
"""Returns the number of alien rows."""
available_space_y = game_settings.screen_height - (3 * alien_height) - 3 * starship_height
number_alien_rows = int(available_space_y / (2 * alien_height))
return number_alien_rows | c99145704a7cf4bfc6474b9ca078f2f1dbf82915 | 649,600 |
def demande_nombre(texte_input):
""" renvoie la réponse à une question Oui/Non
----------------------------
Entrée : le texte de la question
Sortie : int positif donné par l'utilisateur
"""
reponse_user = None
while reponse_user is None:
try:
reponse_user = int(input("(R... | 8387944ac576043e8c04926ed5b0de71f6ef4c35 | 649,601 |
def confirm_delete(profile):
"""Prompt user to enter Y or N (case-insensitive) to continue."""
answer = ""
while answer not in ["y", "n"]:
answer = input("Delete PROFILE '%s' [Y/N]? " % profile).lower()
return answer == "y" | 3df026972ea37775f9bdf0b40d69d65ca64b897a | 649,602 |
def somarNotas(n100,n50,n20,n10,n5,n2,n1):
"""
Esta função realiza o somatório das notas
"""
return n100+n50+n20+n10+n5+n2+n1 | 309571036ad3d2059723fba597ea2d32f412b0ea | 649,603 |
import subprocess
import fnmatch
import sys
def _state_matches(state):
"""Get all states matching a pattern."""
output = subprocess.check_output(
['terraform', 'state', 'list']).decode('utf-8').splitlines()
state_list = fnmatch.filter(output, state)
if not state_list:
print('No state e... | 32113d8329b1588493fe2cc28dc69fd5c0b6e56c | 649,604 |
def TourTypeDayShift_idx_rule(M):
"""
Index is (start window, tour type, shift length, day, week)
:param M: Model
:return: Constraint index (list of tuples)
"""
return [(i, t, k, j, w) for i in M.WINDOWS
for t in M.activeTT
for k in M.tt_length_x[t]
for j in... | a2ebe1390b07ab5590062fb39e84f14f6043e01c | 649,606 |
def Mc_eta_m1_m2(m1, m2):
"""
Computes the symmetric mass-ratio (eta)
and chirp mass (Mc) from the component masses
input: m1, m2
output: Mc, eta
"""
Mc = (m1*m2)**(3./5.)/(m1+m2)**(1./5.)
eta = m1*m2/(m1+m2)**2
return Mc, eta | e57a65d64cb2f44770c76b8ce37e021b7bc21280 | 649,607 |
def is_native(s):
"""Return True for native strings, i.e. for str on Py2 and Py3."""
return isinstance(s, str) | 1bf9a5a60d61096a651d4e73abec980cbb99e5ce | 649,608 |
def do_sample(session, model, data, num_samples):
"""Sampled from the model"""
samples = []
state = session.run(model.initial_state)
fetches = [model.final_state, model.sample]
sample = None
for x in data:
feed_dict = {}
feed_dict[model.input_data] = [[x]]
for layer_num, (c, h) in enumerate(mode... | 35492b0118ed22c01a7f2f29f895a08b46211727 | 649,610 |
def isCacheFile(filePath):
"""Checks if the file is a cache type file without an extension, given:
filePath: The file path (string)
"""
index = filePath.rfind(".")
return index == -1 | 43f3a6da061e33d2823313560b89e9e5196441cd | 649,611 |
import json
def example_json41(example_json_file41):
"""Load the DataCite v4.1 full example into a dict."""
return json.loads(example_json_file41) | bc8abd2cf6f8f6eb765b328f13ed3ccf3941c3d6 | 649,612 |
def add_depend_on(status, name):
"""
Add the names of the packages that depend on the current package.
Parameters
status : dict, main package contents
name : str, current package name
"""
# list for those that dependends on this package
depon = []
for key in status:
# try bl... | 80698e57d530b1f460ee545bf92c5ac74af862a4 | 649,614 |
def StripNonFlags(fs):
"""Please rewrite this: check for desired flags instead of removing unwanted ones."""
if not fs:
return []
non_flag_opts = ('-c', '-o')
non_flag_args = ('-W', '-O', '-f', '-pipe', '-g', '-m')
new_fs = [fs[0]]
is_arg = False
skip_next = False
for f in fs[1:]:
if skip_next:
... | 65ba5e5d45772b17bf738178856412d4cdad58e7 | 649,615 |
def is_a(comp, min_length, max_length, floor, ceiling, min_slope, max_slope):
"""
Return ``True`` if ``comp`` meets the constraints imposed by the
arguments.
.. WARNING::
INTERNAL FUNCTION! DO NOT USE DIRECTLY!
EXAMPLES::
sage: from sage.combinat.integer_list_old import is_a
... | 56ea95709b7d20ea5659f0a3ae17730baf25ea6d | 649,616 |
def quadratic_model ( p, agdd ):
"""A quadratic phenology model. Takes in a lenght 3 vector with parameters
for a quadratic function of AGDD ``agdd``"""
return p[0]*agdd**2 + p[1]*agdd + p[2] | c924b756c18385595faf56275cf126abb641a220 | 649,617 |
def MakeGray(rgbTuple, factor, maskColour):
"""
Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be
changed.
:param `rgbTuple`: a tuple representing a pixel colour;
:param `factor`: a graying-out factor;
:param `maskColour`: a colour mask.
"""
if rgbTuple != mas... | 949e88735522cadc9d7060b630a6b4781c484782 | 649,618 |
def bubble_sort(a):
"""
Sorts the list 'a' using Bubble sort algorithm
>>> from pydsa import bubble_sort
>>> a = [3, 4, 2, 1, 12, 9]
>>> bubble_sort(a)
[1, 2, 3, 4, 9, 12]
"""
for k in range(len(a)):
flag = 0
for i in range(0, len(a)-k-1):
if(a[i] > a[i+1]):... | 4f8597136b2b89d0bd56d15a5c10d1350a8b662b | 649,619 |
async def async_api_reportstate(hass, config, directive, context):
"""Process a ReportState request."""
return directive.response(name="StateReport") | 3ee0b8b8e4ca874a43e9d7cf3aae9b426eda0e43 | 649,621 |
def to_lines(descriptions):
"""
Convert Dictionary to List
:param descriptions: Clean Description
:return: List of all descriptions
"""
all_desc = list()
for key, value in descriptions.keys():
[all_desc.append(d) for d in descriptions[key]]
return all_desc | cf6b9e25d6d6adae82723f5f10c3e2fd10527101 | 649,622 |
import os
def check_epoch_finish(model_dir, epoch):
"""
Check if the epoch training finishes
"""
for root, dirs, files in os.walk(model_dir):
for name in files:
if name.find(str(epoch)+".") != -1:
return True
return False | 75e9c88b7cd8cb13b910d7f6ed47566a5aa6989f | 649,623 |
import codecs
import time
def log_filedate( filename ):
"""return a logfunc which logs date+message to a file (in utf-8)"""
def logfile( message ):
f = codecs.open( filename, 'a', encoding='utf-8' )
f.write( time.strftime("%Y-%m-%d %H:%M:%S ")+message+"\n" )
f.close()
return logfil... | 079acab3000ddd56fe9e41c9ffc40fbbe43e43f5 | 649,624 |
def get_e_type(e_type):
"""Get the file header type."""
if e_type == b'\x00\x00':
return 'ET_NONE'
elif e_type == b'\x01\x00':
return 'ET_REL'
elif e_type == b'\x02\x00':
return 'ET_EXEC'
elif e_type == b'\x03\x00':
return 'ET_DYN'
elif e_type == b'\x04\x00':
... | e3e183325d4caf27cc382bd697af615a9a0508a2 | 649,626 |
def waitForVBL():
"""DEPRECATED: waiting for a VBL is handled by the screen flip
"""
return False | c287fbf7a97b437e258db9797ebae7eb7c9533b2 | 649,627 |
import os
def lookup_filename_to_path(synphot_root, lookup_filename):
"""
Translate a filename from a lookup table into a full
filesystem path.
"""
prefix, other = lookup_filename.split("$")
filename = other.split("[")[0]
return os.path.join(synphot_root, "comp", prefix[2:-4], filename) | 2f406df3b2177b3d2d9c0862b15bd875c6bcf38a | 649,628 |
def rotate_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that the axes are rotated with zdir along
the original z axis. Prepending the axis with a '-' does the
inverse transform, so zdir can be x, -x, y, -y, z or -z
"""
if zdir == 'x':
return ys, zs, xs
elif zdir == '-x':
... | 9e052ba6af47789a50cb55ea2bab8ea2494e5632 | 649,629 |
def CubicIn(start=0.0, finish=1.0):
"""
Cubically increasing, starts very slow : f(x) = x^3
"""
def cubic_in_easing(sprite, delta):
return start + (delta * delta * delta) * (finish - start)
return cubic_in_easing | ff4ce295db2fcb1eac69404a0949eadf38918825 | 649,630 |
def get_message(tweet):
"""
Get the message attribute on a Tweet object.
The attribute available depends on the parameters on the query to Twitter.
"""
try:
message = tweet.full_text
except AttributeError:
message = tweet.text
return message | 7cffb76ee7795095857a48c7780f4362d37869e3 | 649,631 |
import math
def magnitude(v):
"""
Get the magnitude of a vector.
"""
return math.sqrt(sum(v[i] * v[i] for i in range(len(v)))) | 429005042c1794b793c7fd531e406840ec330717 | 649,632 |
import os
def _ignore_import(filename, import_name):
"""
Ignore star-imported names since we can't detect whether they are used.
Ignore imports from __init__.py files since they're commonly used to
collect objects from a package.
"""
return os.path.basename(filename) == "__init__.py" or import... | 288488f6baa820ecdf081c0a8b7161face1a05d3 | 649,633 |
def random_variable_args():
"""Provide arguments for each random variable."""
# Commented out tests are currently failing and will be fixed
_random_variable_args = (
# ("Bernoulli", {"p": 0.5, "sample": 1.0}),
("Beta", {"alpha": 1, "beta": 1}),
# ("Binomial", {"n": 5.0, "p": 0.5, "s... | be4e531a627896e322e5ffa7cb968f27d3a636d8 | 649,634 |
from datetime import datetime
def convert_to_datetime(dte):
"""
Convert a date to a datetime.
Argument:
dte - a dte
"""
dt = datetime(dte.year, dte.month, dte.day)
return dt | 0da79e16f03e318fadf9dc954eadbb0b91a80b4b | 649,636 |
import struct
def long_bits_to_double(bits):
"""
@type bits: long
@param bits: the bit pattern in IEEE 754 layout
@rtype: float
@return: the double-precision floating-point value corresponding
to the given bit pattern C{bits}.
"""
return struct.unpack('d', struct.pack('Q', ... | 8b99d5a9155427a129c1ff1bc265d491f6895861 | 649,637 |
def Normalizer(x):
"""
================================================
Normalizer(x, maxx, minn)
================================================
to normalize values between 0 and 1
Inputs :
1-x:
[List] list of values
Outputs:
1-
[List] list of normal... | e69e6d3003d01a2cefab4de43ed0b5fde62ab7bc | 649,638 |
def find_repeat(start_pattern, function, n_iter=None):
"""
Returns when a NONSPECFIED repeating pattern has been found
Returns steps, pattern
"""
if not n_iter: n_iter = round(10e20)
seen = {start_pattern}
current = start_pattern
for i in range(1,n_iter):
current = functi... | 5f26cf6882b42009e8f2ef47f488dc2988a36086 | 649,639 |
import os
import sys
def gettemp(basename):
"""
Get the path to a temp file previously written by the temp runner.
Useful to compare results between running in interpreter and running frozen.
"""
exec_dir = os.path.dirname(sys.executable)
# onedir mode:
# tmpdir
# ├── python_exe.build
... | cc431bfa962396da6f916fd25451f81d0a20d66b | 649,640 |
def pathFromFileSystem(fspath):
"""
Turn a local filesystem path into a package file path.
(Inside the package metadata, we always store paths in unix format)
"""
return fspath.replace("\\", "/") | 1aedacde20943550591be887cd4641c98e94eab5 | 649,641 |
def preprocess_as_str(lines):
"""
The input python file will be decorated with
indent/dedent so that textX can find the blocks easily.
This function will write the output code in filename_out.
lines: str or list
python code as a string
"""
if type(lines) == str:
ls = lines.s... | f78ebc50f175fb1d549ce524e8d29d769629f5b6 | 649,642 |
def kilometers_to_degrees_lat(kilometres: float) -> float:
"""
Convert kilometres of longitude into degrees
:param degrees:
:return:
"""
return kilometres * 90 * 1000 / 63567523 | d8f4ea5138fc6d1e4e3e7d5ff99a732f7d2dccee | 649,643 |
def dropLabels(collection, feature_type):
"""
Drop labels and return features + labels separately
--args
collection (pandas DF): dataset containing features + labels
feature_type (str): determines which labels to drop
--returns
labels (pandas series): series containing all label names
collection_features (pan... | 1af8c27d2dc58fd99dd0a55a300016f3f3654132 | 649,644 |
from typing import Union
from pathlib import Path
import yaml
def load_config(*args: Union[str, Path]) -> dict:
"""
Load config yaml files from path.
:param args: path(s) of the file(s) containing configuration parameters
"""
config = {}
for filepath in args:
with open(filepath) as fil... | dcb1be810d10731643cb8649a815506387098526 | 649,645 |
def play(board, numbers):
"""
>>> play(BOARD_3, NUMBERS)
(11, 24, 188)
"""
nrows, ncols = len(board), len(board[0])
rowscore = [0] * nrows
colscore = [0] * ncols
position = {}
total = 0
for i in range(nrows):
for j in range(ncols):
position[board[i][j]] = (i, ... | ea39cf0188406a159441d7e62b7340499a9eac4e | 649,647 |
import collections
import json
def seq_length_to_json(df):
"""Convert sequence length distribution to JSON object.
Args:
df: DataFrame containing a subset of sequence length.
Returns:
String: A JSON-formatted string for visualization of sequence length distribution.
"""
json... | 7e81df92f412869013b79067ad976c01cda345d3 | 649,648 |
def candy(ratings):
"""
:type ratings: List[int]
:rtype: int
"""
ans = [1 for x in range(0, len(ratings))]
for x in range(0, len(ratings) - 1):
if ratings[x] < ratings[x + 1]:
ans[x] = 1
if ratings[x] >= ratings[x + 1]:
ans[x + 1] = 1
return sum(ans) | 5a5ed68a46d58fbf73e19a837a028ac24d591f47 | 649,649 |
import platform
import unittest
def _requires_unix_version(sysname, min_version):
"""Decorator raising SkipTest if the OS is `sysname` and the version is less
than `min_version`.
For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
the FreeBSD version is less than 7.2.
"""
... | e7c269e3d1596eed92f4e1bb7e64b6091d1e5428 | 649,650 |
def calc_item_power(m: dict, count : int) -> int:
"""アイテムマスタ m から count 個目のそのアイテムの生産力を計算する"""
a = m['power1']
b = m['power2']
c = m['power3']
d = m['power4']
return (c * count + 1) * (d ** (a * count + b)) | 92370f7507af2079ea5fcfe78e4436deadb16170 | 649,651 |
def codegen_reload_data():
"""
Parameters required reload codegen for the fn_aws package
"""
return {
"package": u"fn_aws",
"message_destinations": [u"fn_aws"],
"functions": [u"aws_ec2_describe_instance", u"aws_delete_key_pair", u"aws_change_instance_status", u"aws_ec2_modify_sec... | 08a62ae5db31061a7a83b282401524bc0b11fe7b | 649,652 |
def write_packets(queue, traffic_writer, sconf, fd_result):
"""
Packets are written out interleaved (round-robin) from
each stream until the batch is complete, or there are no more packets
to write. This helps defeat locality in that packets from a single
stream (assuming some strea... | 14b4b323d24fd0bfe64903df65e4ac23d8d5382d | 649,653 |
def take_while(predicate, collection):
"""Returns a list corresponding to the longest prefix
of the original list for which all the values when
tested against the given predicate return True
>>> take_while(lambda x: x<=10, range(10000))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""
payload = []
... | 9562ddc3295fb94547c26592c3a3ca96ce5dc39d | 649,654 |
def _scaleRep(reportData):
"""
Scales reports of different sets of terms.
Using the percent change with the 1 month overlap should take care of the
variation in time of a single report. However, if, at the same moment in
time, a secondary report contains a term which is larger than the constant
term and so causes... | 0719ab92dadf91fe7fcdaaffa2ca26c928d47bac | 649,655 |
def base_account(assets, prepare_account):
""" Factory to generate random account with pre-defined balances
"""
def func():
account = prepare_account({'BASEA': 10000, 'QUOTEA': 100, 'BASEB': 10000, 'QUOTEB': 100, 'TEST': 1000})
return account
return func | 692e98ca3c11285a98ffed0a3c5d4c28eb776648 | 649,656 |
def indentation(level, word):
"""
Returns a string formed by word repeated n times.
"""
return ''.join([level * word]) | b4d500767329b06e43803bf95e8c9306bfc870df | 649,657 |
def find_elements_that_sum_to_2020(input: list[int]) -> tuple[int, int]:
"""Find elements of the input that sum to 2020."""
for value in input:
remainder = 2020 - value
if remainder in input:
return value, remainder
raise ValueError("unable to find 2 elements that sum to 202... | c6e5264720cd1ac69df289f81f5d9bce26d3875c | 649,658 |
def validate_strings(*args):
"""
Checks that all given arguments have a string type (e.g. str, basestring,
unicode etc)
Args:
*args: values to be validated.
Returns:
bool: True if all arguments are of a string type. False otherwise.
"""
for arg in args:
if not isins... | 9b7688c2e9cda14405b3f911c123ec54165ce061 | 649,660 |
def forceIterable(x):
"""Forces a non iterable object into a list, otherwise returns itself
:param list x: the object
:return: object as a list
:rtype: list"""
if not getattr(x, '__iter__', False):
return list([x])
else:
return x | c3bfa94fd02502eb4f86a43799cd3c2e638260bf | 649,661 |
import math
def euclidean_distance(pts):
"""
straightline distance between two points.
return euclidean distance between two lists """
if len(pts) <= 1:
return 0
return math.sqrt(sum(pow(a-b,2) for a, b in pts)) | b345bcb56baf85a099337ee2b87d68e2391a8dde | 649,662 |
def max_no_repeat(s):
"""
Returns the first longest substring of s containing no repeated characters.
"""
max_start = -1
max_end = -1
max_len = -1
char_set = set() # {} initializes an empty dict instead of an empty set.
curr_start = 0
for curr_end in range(len(s)):
char = s[... | 0e553bacdc2df16e94c26decf2b991ecd2ac384e | 649,664 |
import random
import os
def random_bolt(img_path='/workspace/web_server/static/small_bolt'):
"""
Pull a random image out of the small bolt dataset
:param savePath: the path to save the file to. If None, file is not saved
:return 0: file selected
:return 1: label selelcted
"""
random_dir = random.choice... | d578a5db8e0f28680fbad047133b7aa27f85d1d3 | 649,666 |
def strip_html(response):
"""
Strips HTML header/footer from a response.
This is useful when trying to embed HTML into
an existing page through use of an external API.
"""
return (
response.content.decode("utf-8")
.replace("<!DOCTYPE html>\n\n<html>", "")
.replace("</html... | 7016f8d365d6843a2399af068ccadb54d3c5a114 | 649,667 |
import torch
def scatter(tensor, devices, chunk_sizes=None, dim=0, streams=None):
"""Scatters tensor across multiple GPUs.
Arguments:
tensor (Tensor): tensor to scatter.
devices (Iterable[int]): iterable of ints, specifying among which
devices the tensor should be scattered.
... | e3b1260b3fe199ccdbab75d52a05f6991a623554 | 649,668 |
def pop_named(self, name):
""" Remove and return holidays by-name. Returns a list of dates removed. """
to_pop = self.get_named(name)
if not to_pop:
raise KeyError(name)
to_return = []
for key in to_pop:
self.pop(key)
return to_pop | 8aac598e412378cc3b09e213d23a861614392120 | 649,669 |
import argparse
def build_parser():
"""Build argument parser."""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--in_path", "-i", required=True,
... | 25e2168ef1fcdb7ee9b6edbc2bc29640fdfbd69c | 649,670 |
def region(lat, lon):
""" Return the SRTM3 region name of a given lat, lon.
Map of regions:
http://dds.cr.usgs.gov/srtm/version2_1/Documentation/Continent_def.gif
"""
if 15 <= lat and lat < 61 and -170 <= lon and lon < -40:
return 'North_America'
raise ValueError('Unkno... | 0aed4b118d3340cf91ba98f21b45a181922eafe0 | 649,671 |
from typing import Tuple
def calculate_unmatched_exposure(ub: list, ul: list) -> Tuple:
"""Calculates worse-case exposure based on list
of (price, size)
returns the tuple (profit_if_win, profit_if_lose)
The worst case profit_if_win arises if all lay bets are matched and the selection wins.
The wo... | abf5379785c46bfd95b968e0e78c4bfde0e3f955 | 649,672 |
def prob22(f='names.txt'):
"""
Using names.txt, a 46K text file containing over five-thousand first names,
begin by sorting it into alphabetical order. Then working out the
alphabetical value for each name, multiply this value by its alphabetical
position in the list to obtain a name score.
For... | ba715c932f7cb7c589fbc395cc9ada33ccd5ac03 | 649,673 |
import hashlib
def alternative_hash(value):
"""Quick way of doing a hash.
This used to be hash(), but in Python 3 it is seeded and returns
different values.
Security is not an issue here so md5 is used as its cheap.
"""
return hashlib.md5(repr(value).encode('utf-8')).hexdigest() | 0aea265ba8eba124ca8e50143fc74c2865f0977d | 649,674 |
import numpy
def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:
"""
Standard rotation of a 2D vector with a rotation matrix
(see https://en.wikipedia.org/wiki/Rotation_matrix )
>>> rotate(numpy.array([1, 0]), 60)
array([0.5 , 0.8660254])
>>> rotate(numpy.array([1... | 8637477e2bf1dfca3f184ca4b3e8a3cd3cdba0a7 | 649,675 |
import os
def normpath(path):
"""os.path.normpath() that keeps trailing slash."""
out = os.path.normpath(path)
if path.endswith(('/', os.path.sep)):
out += os.path.sep
return out | ecbb3c936fd6aa04911e0129e301921d703d9c3d | 649,676 |
def dame_datos(latitud,longitud,ds):
"""
Devuelve los datos del dataset en las coordenadas pasadas
Parametros:
latitud -- latitud
longitud -- longitud
ds -- dataset del que extraer los valores
"""
return ds.sel({'latitude':latitud,'longitude': longitud},method= 'nearest') | 03c4972320efb2cc8fec5448cd5aee43bd9160b0 | 649,679 |
import argparse
def parse_args():
"""Arg parser"""
parser = argparse.ArgumentParser(description="DNN curve training")
parser.add_argument("--dir",
type=str,
default="/tmp/curve/",
metavar="DIR",
help="training ... | 77194ec2670ec4376d9b4790ddc306baf0dc7474 | 649,680 |
def recall_powerlaw_fits_to_full_models():
"""fits may be recomputed by evaluating the .ipynb associated with fitting powerlaws to the full models.
here, w=M*q**m, and Delta_X is the maximum disagreement one could expect to observe with 95% confidence.
here, we observe Delta_X concerns disagreements between... | a8debffe07588f49e210b319e9418e55fa6c89e2 | 649,681 |
from typing import Callable
import click
def base_vwq_url_option(command: Callable[..., None]) -> Callable[..., None]:
"""
An option decorator for choosing the base VWQ URL.
"""
click_option_function = click.option(
'--base-vwq-url',
type=click.STRING,
default='https://cloudrec... | bc77fc116ef302a447a2e88db48f30217df41504 | 649,683 |
from string import punctuation
import re
def make_artist_regex(artist_name):
"""Returns regex string of artist name for storage in DB."""
PUNC_RE = re.compile(
'[{}]'.format(punctuation),
flags=re.I|re.M|re.DOTALL
)
no_punc = re.sub(PUNC_RE, r'.?', artist_name)
no_end = re.sub(r... | c76b7bf4c4d281e80df938c993654cf905d70acb | 649,684 |
import getpass
def handle_credentials(email,password,prompt="Password: "):
"""
Sort out email and password for accessing Galaxy
Arguments:
email (str): Galaxy e-mail address corresponding to the user
password (str): password of Galaxy account corresponding to
email address; if None th... | bc0d309b9d72ed201c0a641c456439bca0d3992b | 649,686 |
import re
def get_valid_filename(input_filename):
"""Summary:
--------
Return valid filename by removing empty space and special characters
-------
input_filename (str): input filename
Returns:
--------
str: valid filename
"""
input_filename = input_filename.strip().... | cddd7121054a63a1c26393ce75f09b47ecce10d8 | 649,688 |
def get_port_ether(port_name):
"""
Get Host port Ethernet Address.
Input:
- The name of the port (e.g, as shown in ifconfig)
"""
return "ifconfig {} | grep \"ether \" | xargs | cut -d \' \' -f 2".format(port_name) | 2b1740130fbbae7846901b7de1adc63b80af0de3 | 649,689 |
import smtplib
def get_server_reference(
username, smtp_password, aws_smtp_endpoint, aws_smtp_port, **kwargs):
"""
Returns smtplib.smtp reference using the specified parameters.
Call sendmail on the returned reference to send emails.
See the example configuration file for explanations on wher... | 878080608a513887fce905ba036940acbc2d15d8 | 649,690 |
def model_name(model):
"""
Sample usage:
{{model|model_name}}
"""
return model._meta.model_name | 8ce8be360f3cb943f1511cbffb71f59473f57669 | 649,692 |
import os
def _env_variable_exists(env_variable):
"""This function checks to see if an environment variable is already defined.
.. versionadded:: 2.2.0
:param env_variable: The name of the environment variable for which to check
:type env_variable: str
:returns: Boolean value indicating if the e... | fb8695d0bc820a6af4e62676812e2046db018a7c | 649,693 |
from typing import Iterable
from typing import AnyStr
from typing import Set
def prepare_selected_fields(fields: Iterable[AnyStr], default: Set[AnyStr]) -> Set[AnyStr]:
"""Check for selected fields of the query.
:param fields: Iterable object with all field names that should be selected by the query
:par... | 2ac71b9fe59a3bede6a7c95847a4e54635d979da | 649,694 |
def scalar_assign(node):
"""
convert scalar to various array types
"""
# left-hand-side and right-hand-side
lhs, rhs = node
if lhs.mem < rhs.mem:
node.warning("Type reduction from %s to %s" % (rhs.type, lhs.type))
# matrix suround are ignored
if rhs.cls == "Matrix":
rhs = ... | 2c7efb00e379a4cebec2537c988db619c94c7710 | 649,696 |
def mask_crop_ndvi(all_bands, crop_bound, pixel_qa, vals):
"""Compute normalized difference vegetation index (NDVI) from given landsat bands. Crop the NDVI layer and the pixel qa layer to the boundary as specified by a given crop_bound file.
Parameters
-----------
all_bands : list
A list conta... | aacdd506368cfa3db3eca5868903c3d212883b56 | 649,698 |
import numpy
def xyz2xy(vec):
"""Calculate the (x,y) chromaticity coordinates from an XYZ triplet."""
assert(isinstance(vec, numpy.ndarray))
assert(len(vec) == 3)
return vec[0:2] / float(numpy.sum(vec)) | bfb062e2b200f118a3b12f4ad55faf72ddd08b73 | 649,699 |
import sys
def lookup_individual_index(options, ind_name):
"""Gets the index of individual that is used
to lookup information in the genotype and haplotype tables"""
sys.stderr.write("reading list of individuals from %s\n" %
options.samples)
f = open(options.samples, "rt")
... | 552c09d61cef22545ed94a9487db4c2da9e33e07 | 649,700 |
from pathlib import Path
def args_to_pathlist(nodelist, directory, recurse):
"""Process optional list of files."""
if nodelist == (): # empty nodelist
if directory:
pathlist = [Path(".")]
else:
pathlist = [p for p in Path(".").glob("*") if p.is_file()]
else:
... | 47449ebcb26057fdae7834d21cc59c8d3fee8ec3 | 649,701 |
def qualified_name(object_instance):
"""Return the fully qualified type name of an object.
:param object_instance: Object instance.
:return: Fully qualified name string.
"""
if hasattr(object_instance, '__module__'):
return object_instance.__module__ + '.' + type(object_instance).__na... | f3b909b08603391c1661c05fa2ba34e848483a6a | 649,702 |
import argparse
def get_parser():
"""Parse data for main function."""
parser = argparse.ArgumentParser(description='Testing 3D conv network.')
parser.add_argument("--config_file",
type=str, nargs=1, required=True, help='config file')
parser.add_argument("--output_directory_name... | dbdcf3143eeae57eb70cec6309e442bc4af7b591 | 649,703 |
def scaleto99(value: int | None) -> int:
"""Scale the input value from 0-255 to 0-99."""
if value is None:
return 0
# Make sure a low but non-zero value is not rounded down to zero
if 0 < value < 3:
return 1
return min(round(value / 2.55), 99) | 22dac0906cb2146857f9e4c809f87a6229369513 | 649,704 |
import time
def get_time(func):
""" 関数処理時間計測用デコレータ
"""
def wrapper(*args, **kwargs):
t0 = time.time()
func(*args, **kwargs)
delta = time.time() - t0
print(f"Time[{func.__name__}]: {delta}s")
return wrapper | 56e1f86d5daa98338aa8781a026d5ebe5ef65eae | 649,705 |
import hashlib, base64
def get_hashing(string_repr, length=None):
"""Get the hashing of a string."""
hashing = base64.b64encode(hashlib.md5(string_repr.encode('utf-8')).digest()).decode().replace("/", "a")[:-2]
if length is not None:
hashing = hashing[:length]
return hashing | 93e35f706087a1d4dfc0842797d65e8863b0b818 | 649,706 |
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits
... | d4c9a218049334d5535b01337c83085a88efdf8b | 649,707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.