content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hash_bower_component(hash_obj, path):
"""Hash the contents of a bower component directory.
This is a stable hash of a directory downloaded with `bower install`, minus
the .bower.json file, which is autogenerated each time by bower. Used in
lieu of hashing a zipfile of the contents, since zipfiles a... | 1,100 |
def align_jp_and_en_boxes(pd_results) -> pd.DataFrame:
"""boxes are not ordered on the page, so heuristically must match them based on
location on page
"""
japanese_results = pd.DataFrame.copy(
pd_results[pd_results.language == "jp"]).reset_index()
english_results = pd.DataFrame.copy... | 1,101 |
def export_videos(nusc: NuScenes, out_dir: str):
""" Export videos of the images displayed in the images. """
# Load NuScenes class
scene_tokens = [s['token'] for s in nusc.scene]
# Create output directory
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
# Write videos to disk
... | 1,102 |
def productivity_flag():
"""
Real Name: b'Productivity Flag'
Original Eqn: b'1'
Units: b'Dmnl'
Limits: (None, None)
Type: constant
b''
"""
return 1 | 1,103 |
def create_cartpole_network(hidden_layers=2, neurons=56):
"""
Network that can solve gyms 'CartPole-v1' environment.
"""
net = Sequential()
net.add(Dense(
neurons,
input_shape=(4,),
kernel_regularizer=l2(0.001),
kernel_initializer=GlorotNormal(),
activation=... | 1,104 |
def askdelsnat(client, mapping):
"""ask static NAT delete"""
if mapping.proto == 1:
proto = ' udp '
else:
proto = ' tcp '
text = 'nat ' + client.ipv6 + proto + mapping.src + \
' ' + str(mapping.sport)
ask('delete ' + text)
syslog.syslog(syslog.LOG_NOTICE, 'del ' + text) | 1,105 |
def format_as_rfc2822(*args, **kwrags):
"""Alias of ``format_as_rss()``."""
return format_as_rss(*args, **kwrags) | 1,106 |
def train_model_exponentially(train_images, train_labels, parts, exponent):
"""
Trains a model incrementally, using training data partitions that increase exponentially, and exports it.
:param train_images:
:param train_labels:
:param parts:
:param exponent:
:return: The final model
"""
... | 1,107 |
def get_config_of(tests, test_name):
"""
Find generic values of test
"""
for test in tests:
if test.name == test_name:
try:
return test._test_case._run._config # pylint: disable=protected-access
except AttributeError:
return test._run._con... | 1,108 |
def transmit_format(func):
"""Wrapper for dataset transforms that recreate a new Dataset to transmit the format of the original dataset to the new dataset"""
@wraps(func)
def wrapper(*args, **kwargs):
if args:
self: "Dataset" = args[0]
args = args[1:]
else:
... | 1,109 |
def tg_exec_command(update: Update, context: CallbackContext) -> None:
"""Run command in shell"""
if update.message.from_user.username not in settings.get("admins", []):
update.message.reply_text("ERROR: Access denied")
return
proc = subprocess.run(update.message.text.split(' ', 1)[-1], sh... | 1,110 |
def parse_version(version: str) -> Version:
"""Parses version string to Version class."""
parsed = version.split(".")
try:
return Version(int(parsed[0]), int(parsed[1]), int(parsed[2] if len(parsed) > 2 else -1))
except ValueError:
return Version(0, 0, -1) | 1,111 |
def rate_of_change(x, t_Δ=1):
"""
:param x: a series
:param t_Δ: the intervals between each observation (series or constant)
:return: rate of change for x
"""
diffs = np.diff(x) / t_Δ
return diffs | 1,112 |
def draw_cutout(data, title, lower_bound=0, upper_bound=1, is_mobile=False):
""" Draw a cutout data
"""
# Update graph data for stamps
data = np.nan_to_num(data)
data = sigmoid_normalizer(data, lower_bound, upper_bound)
data = data[::-1]
data = convolve(data, smooth=1, kernel='gauss')
... | 1,113 |
def _check_sample(sample_pair: dict):
"""
Controls a sample.
Parameters
----------
sample_pair : dict
Sample must contain image and mask: " "{'image': image, 'mask': mask}
Returns
-------
sample : dict
Sample must contain image and mask: " "{'image': image, 'mask': mask}... | 1,114 |
def reset_deterministic_algorithm():
"""Ensures that torch determinism settings are reset before the next test runs."""
yield
if _TORCH_GREATER_EQUAL_1_8:
torch.use_deterministic_algorithms(False)
elif _TORCH_GREATER_EQUAL_1_7:
torch.set_deterministic(False)
else: # the minimum vers... | 1,115 |
def _make_cls(cls, attrs):
"""Make the custom config class."""
return type(f'Custom{cls.__name__}', (cls, ), attrs, ) | 1,116 |
def get_date(delta):
"""Build a date object with given day offset"""
date = datetime.datetime.now()
if delta is not None:
offset = datetime.timedelta(days=delta)
date = date + offset
date = date.strftime("%A %-m/%-d")
return date | 1,117 |
def mover_alfil(tablero, x_inicial, y_inicial, x_final, y_final):
"""
(list of list, int, int, int, int) -> list of list
:param tablero: list of list que representa el tablero
:param x_inicial: int que representa la posicion inicial en X
:param y_inicial: int que representa la posicion inicial en Y... | 1,118 |
def write_decaytable_entry_calchep(grouped_decays, gambit_model_name,
calchep_pdg_codes, gambit_pdg_codes,
decaybit_dict, calchep_processes):
"""
Writes a DecayBit DecayTable::Entry module function for a given set of
of particle decays.
... | 1,119 |
def test_roc_curve_display_default_labels(
pyplot, roc_auc, estimator_name, expected_label
):
"""Check the default labels used in the display."""
fpr = np.array([0, 0.5, 1])
tpr = np.array([0, 0.5, 1])
disp = RocCurveDisplay(
fpr=fpr, tpr=tpr, roc_auc=roc_auc, estimator_name=estimator_name
... | 1,120 |
def collect_process_name_garbage():
"""
Delete all the process names that point to files that don't exist anymore
(because the work directory was temporary and got cleaned up). This is
known to happen during the tests, which get their own temp directories.
Caller must hold current_process_name_lock... | 1,121 |
def log(ltype, msg, logit = None):
"""
########################################################################################
# print msg and log it if is needed
# log([0 - INFO, 1 = WARRNING and 2 - ERROR], 'log message', 'eny value if you want
# to log in jailog file'
#
"""
logtype = ['INFO', 'WARNIN... | 1,122 |
def interpolate_atmosphere(data, Z, s=0.25):
""" This module generates a 1d array for the model plasma preesure, plasma
density, temperature and mean molecular weight.
"""
from scipy.interpolate import UnivariateSpline
hdata = np.array(u.Quantity(data['Z']).to(u.m))
# interpolate total pressure... | 1,123 |
def merge_vcf_files(infiles, ref_seqs, outfile, threads=1):
"""infiles: list of input VCF file to be merge.
outfile: name of output VCF file.
threads: number of input files to read in parallel"""
vars_dict = vcf_file_read.vcf_files_to_dict_of_vars(
infiles, ref_seqs, threads=threads
)
_d... | 1,124 |
def exponential_coulomb_uniform_correlation_density(
density,
amplitude=constants.EXPONENTIAL_COULOMB_AMPLITUDE,
kappa=constants.EXPONENTIAL_COULOMB_KAPPA):
"""Exchange energy density for uniform gas with exponential coulomb.
Equation 24 in the following paper provides the correlation energy per length... | 1,125 |
def val(model, dataloader, use_gpu):
"""val. the CNN model.
Args:
model (nn.model): CNN model.
dataloader (dataloader): val. dataset.
Returns:
tuple(int, in): average of image acc. and digit acc..
"""
model.eval() # turn model to eval. mode(enable droupout layers... | 1,126 |
def ps(s):
"""Process String: convert a string into a list of lowercased words."""
return s.lower().split() | 1,127 |
def edit_txt(ctx, record_id, name, value, ttl=3600):
"""Edit default TXT record"""
try:
data = {
"name": name,
"value": value,
"ttl": ttl
}
r = ctx.obj['client'].default_record(record_id)
record = r.edit(data)
click.echo(json.dumps(reco... | 1,128 |
def offset_plot_r(offset, az_min, az_max, r_plot, az_plot, logpath=None, outdir=None, shellscript=None):
"""
| IPTA script: /usr/local/GAMMA_SOFTWARE-20180703/ISP/scripts/offset_plot_r
| Copyright 2004, Gamma Remote Sensing, v1.3 17-Jan-2005 clw
| extract range and azimuth offsets for an azimuth window ... | 1,129 |
def _noop_check_fix() -> None:
"""A lambda is not pickleable, this must be a module-level function""" | 1,130 |
def show_table_matrix(cells, colors=None,
cells2=None, colors2=None,
link_matrix=None,
table_font_size=32,
rot_45=True,
return_img=False):
"""Draw a view of two tables together with a row-row association ma... | 1,131 |
def login(username,password):
"""
使用账号(邮箱)和密码,选择“记住我”登录
:param username:
:param password:
:return:
"""
global a
a.get("https://account.fangcloud.com/login")
_token = a.b.find("input",{"name":"_token"})["value"]
_fstate = a.b.find("input",{"name":"_fstate"})["value"]
... | 1,132 |
def rules():
"""Displays a markdown doc describing the predictive modeling contest.
Note ./content/contest/<url calling path>.md must be modified for contest.
"""
file = open('./contest/content/rules.md', 'r')
rawText = file.read()
file.close()
content = Markup(markdown(rawText,
ext... | 1,133 |
def greedy_search(decoder, encoder_outputs, encoder_outputs_mask, debug=False):
""" performs beam search. returns hypotheses with scores."""
batch_size = encoder_outputs.size(0)
encoder_hidden_dim = encoder_outputs.size(2)
assert encoder_hidden_dim == decoder._decoder_hidden_dim
trg_h_t, trg_c_t = ... | 1,134 |
def get(server: t.Union[Server, str], view_or_url: str, view_data: Kwargs = None, session: requests.Session = None,
params: Kwargs = None, **kwargs) -> Response:
"""Sends a GET request."""
return request('get', server, view_or_url, view_data=view_data, session=session, params=params, **kwargs) | 1,135 |
def parse_command_line():
"""
Parses the command line options and prints the errors, if any occur.
"""
if "-h" in sys.argv or "--help" in sys.argv:
terminate(HELP_TEXT, 0)
if "-f" in sys.argv or "--file" in sys.argv:
try:
file_index = sys.argv.index("-f") + 1
... | 1,136 |
def upload_files(
project: str,
paths: Sequence[Union[Path, str]],
target_dir: str,
strip_prefix: str = "",
progress_bar: bool = True,
) -> None:
"""Upload all provided files from the local filesystem into `target_dir` on GCS.
`strip_prefix` is removed from each local filepath and the remain... | 1,137 |
def to_float(dataframe, column):
"""General Function to return floats"""
dataframe[column] = dataframe[column].dropna().astype(float)
dataframe[column] = dataframe[column].where(pandas.notnull(dataframe[column]), None)
return dataframe[column] | 1,138 |
def compute_kv_template(config):
"""Draw from a line template"""
# copy to a new memory, avoid lost info
_i = config['info'].copy()
_d = config['data'].copy()
# fill in the data
if len(_d) < 1:
raise ValueError('A template data is essential!')
config['data'] = []
for log_name in os.listdir(_i['dir... | 1,139 |
def load_qm7(featurizer=None, split='random'):
"""Load qm7 datasets."""
# Featurize qm7 dataset
print("About to featurize qm7 dataset.")
current_dir = os.path.dirname(os.path.realpath(__file__))
dataset_file = os.path.join(current_dir, "./gdb7.sdf")
qm7_tasks = ["u0_atom"]
if featurizer is None:
featu... | 1,140 |
def dadbt(a: torch.Tensor, diag_mat: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""Batched computation of diagonal entries of (A * diag_mat * B^T) where A and B are batches of square matrices and
diag_mat is a batch of diagonal matrices (represented as vectors containing diagonal entries)
:param a: ba... | 1,141 |
def test_get_input(monkeypatch):
"""Check if provided input is return unmodified."""
from tokendito import helpers
monkeypatch.setattr("tokendito.helpers.input", lambda _: "pytest_patched")
assert helpers.get_input() == "pytest_patched" | 1,142 |
def local_minima(image, footprint=None, connectivity=None, indices=False,
allow_borders=True):
"""Find local minima of n-dimensional array.
The local minima are defined as connected sets of pixels with equal gray
level (plateaus) strictly smaller than the gray levels of all pixels in the
... | 1,143 |
def kron(a, b):
"""
Kronecker product of matrices a and b with leading batch dimensions.
Batch dimensions are broadcast. The number of them mush
:type a: torch.Tensor
:type b: torch.Tensor
:rtype: torch.Tensor
"""
siz1 = torch.Size(tensor(a.shape[-2:]) * tensor(b.shape[-2:]))
res = a... | 1,144 |
def process_query(request):
"""the function is called upon "news/" URL. it processes the query and calls the apifunction to fetch news articles
from third party news APIs.
If a query is new, it makes a fresh request to third party APIs and returns the query results and adds the
query and query result... | 1,145 |
def fix_header(params, recipe, infile=None, header=None,
raise_exception=False, **kwargs):
"""
Instrument specific header fixes are define in pseudo_const.py for an
instrument and called here (function in pseudo_const.py is HEADER_FIXES)
:param params:
:param infile:
:return:
... | 1,146 |
def encode(df: pd.DataFrame,
cols: List[str],
drop_first: bool = True) -> pd.DataFrame:
"""Do a dummy encoding for the columsn specified
Args:
df: DataFrame
cols: List of columns to perform dummy encoding on
drop_first: parameter for dummy encoding
"""
dfs ... | 1,147 |
def do_absolute_limits(cs, args):
"""Lists absolute limits for a user."""
limits = cs.limits.get().absolute
columns = ['Name', 'Value']
utils.print_list(limits, columns) | 1,148 |
def binary_search(pool: list, target) -> Optional[int]:
"""Search for a target in a list, using binary search.
Args:
pool (list): a pool of all elements being searched.
target: the target being searched.
Returns:
int: the index of the target.
"""
sorted_pool = sorted(pool)
... | 1,149 |
def load_array(filename):
"""
Given a valid image, load the image and return the pixels as a numpy array
:param filename: The filename as a string
:returns: A numpy array which stores the pixel data from a snowmap
Convention is as follows: pixels that read 0,0,0, 255 are read as snow-free and conta... | 1,150 |
def GenerateParseTreeDecls(concrete_classes,
abstract_classes):
"""Generates parse_tree_decls.h contents containing forward declarations.
Args:
concrete_classes: a list of classes for which to generate declarations
abstract_classes: a list of classes for which to generate declara... | 1,151 |
def test_module_exports(all_names: list[str], cls: Type[object]) -> None:
"""Test that ass_tag_parser.__init__.__all__ includes all defined ASS tags
and draw commands.
"""
assert cls.__name__ in all_names | 1,152 |
def create_anchors_3d_stride(feature_size,
anchor_strides,
sizes=[1.6, 3.9, 1.56],
anchor_offsets=[0, -20, -1], # [0.2, -39.8, -1.78],
rotations=[0, 1.57], # np.pi / 2
dtype... | 1,153 |
def sample_unit(name='oz'):
"""Create and return a sample unit"""
return Unit.objects.create(name=name) | 1,154 |
def CreateBlendCurve2(curve0, t0, reverse0, continuity0, curve1, t1, reverse1, continuity1, multiple=False):
"""
Makes a curve blend between 2 curves at the parameters specified
with the directions and continuities specified
Args:
curve0 (Curve): First curve to blend from
t0 (double): P... | 1,155 |
def fetch_website(url, user_agent, results_location_dir):
"""function to use for website fetch
:param url: url to fetch information from
:param user_agent: user agent string that is used by the minion in making the fetch
:param results_location_dir: the location to where the results are stored
:ret... | 1,156 |
def make_raster_from_images(modeladmin, request, queryset):
"""Make a raster of the selected `ImageMeta`s.
This is an action on `ImageMeta`
"""
imset = make_image_set_from_images(modeladmin, request, queryset)
return _make_raster_from_image_set(imset) | 1,157 |
def is_rotation(first, second):
"""Given two strings, is one a rotation of the other."""
if len(first) != len(second):
return False
double_second = second + second
return first in double_second | 1,158 |
def bin_entities(uri_set, delimiter="/", splitpos=-1):
""" Takes iteratable elemts and splits them according to the position
(splitpos) of the delimiter. The first part is used as a key,
whereas the second appended to a list connected to the former key.
return: dict {key1: [id11, id12, id13... | 1,159 |
def frequency(state_1, state_2):
""" The frequency interval between state_1 and state_2 in GHz.
"""
return 1e-9 * interval(state_1, state_2) / h | 1,160 |
def dac(dns_val=None) -> OrderedDict:
"""
Domain Availability Checker (DNS lookup)
:param _dns: URL string
:return: Availability [True, False]
"""
ip_values = None
avail = False
if dns_val is None:
raise ValueError("Sorry, DNS is needed")
if isinstance(dns_val, str) is Fals... | 1,161 |
def display_timestamp(num_seconds):
"""get a string to conveniently display a timestamp"""
seconds = num_seconds % 60
minutes = int(num_seconds / 60) % 60
hrs = int(num_seconds / 3600)
return "{}:{}:{}".format(hrs, minutes, seconds) | 1,162 |
def get_bloglist(content_dict={}):
"""
输入的指令为-m,则列出博客的文章列表
:param content_dict:
:return:
"""
bloglist = crawlBlog.get_archives(5)
tousername = content_dict["FromUserName"]
fromusername = content_dict["ToUserName"]
return WeixinUtils.make_news(bloglist, tousername, fromusername) | 1,163 |
def cdo_daily_means(path, file_includes):
"""
loops through the given directory and and executes "cdo dayavg *file_includes* file_out"
appends "dayavg" at the end of the filename
"""
for name in os.listdir(path):
if file_includes in name and 'dayavg' not in name:
name_new = f"{''... | 1,164 |
def get_closest(arr, value):
"""
Return the array values closest to the request value, or +/-inf if
the request value is beyond the range of the array
Parameters
----------
arr : sequence
array of values
value : numeric
Returns
-------
2-tuple: largest value in array le... | 1,165 |
def filename(config, key, ext = '.h5', set = ''):
"""
Get the real file name by looking up the key in the config and suffixing.
:param key: key to use in the config
:type key: str
:param ext: extension to use
:type ext: str
:param set: set name
:type set: str
:return: filepath
:... | 1,166 |
def XIRR(
values: func_xltypes.XlArray,
dates: func_xltypes.XlArray,
guess: func_xltypes.XlNumber = 0.1
) -> func_xltypes.XlNumber:
"""Returns the internal rate of return for a schedule of cash flows that
is not necessarily periodic.
https://support.microsoft.com/en-us/office/
... | 1,167 |
def isUp():
""" Whether this docker container is up """
return 'True' | 1,168 |
def main():
"""
Main program.
"""
## Arguments.
# VCF file path.
name_file = sys.argv[1]
## Steps.
# Open VCF file to read.
file_in = open(name_file, 'r')
# Create the lists:
type_variants = []
number_variants = []
# Sum the SNPs and INDELs according to... | 1,169 |
def rand_perm_(img, x, y, x_max, y_max, kernel, flatten):
"""
Applies INPLACE the random permutation defined in `kernel` to the image
`img` on the zone defined by `x`, `y`, `x_max`, `y_max`
:param img: Input image of dimension (B*C*W*H)
:param x: offset on x axis
:param y: offset on y axis
:... | 1,170 |
def test(model, data_loader, use_cuda, loss_func):
"""
The function to evaluate the testing data for the trained classifiers
:param model:
:param data_loader:
:param use_cuda:
:return:
"""
softmax = torch.nn.Softmax(dim=1)
columns = ['participant_id', 'session_id', 'slice_id', 'true... | 1,171 |
def is_fundamental_error(path, error):
"""
Returns True if error is not field related. (So type related, for example.)
"""
return not is_any_field_error(path, error) | 1,172 |
def countdown(i):
"""Count down by 1 from i to 0."""
print(i)
if i <= 0: # Base case
return
else: # Recursive case
countdown(i-1) | 1,173 |
def check_git_modified(clinfo):
"""로컬 git 저장소 변경 여부.
Commit 되지 않거나, Push 되지 않은 내용이 있으면 경고
Returns:
bool: 변경이 없거나, 유저가 확인한 경우 True
"""
nip = _get_ip(
clinfo['instance']['notebook'],
clinfo['profile'].get('private_command')
)
user = clinfo['template']['notebook']['ss... | 1,174 |
def calculate_normalized_fitness(population):
"""
Args:
population (Population):
Returns:
None
"""
# onvert to high and low scores.
scores = population.get("score")
scores = [-s for s in scores]
min_score = np.nanmin(scores)
shifted_scores = [0 if np.isnan(score) e... | 1,175 |
def test_list_id_length_nistxml_sv_iv_list_id_length_1_1(mode, save_output, output_format):
"""
Type list/ID is restricted by facet length with value 5.
"""
assert_bindings(
schema="nistData/list/ID/Schema+Instance/NISTSchema-SV-IV-list-ID-length-1.xsd",
instance="nistData/list/ID/Schema... | 1,176 |
def reset_trigger(trigger_name, delete_jobs):
"""
Reset the trigger to its initial state.
"""
# Validate trigger existance.
TriggerManager.validate_existance(trigger_name)
if delete_jobs:
_delete_trigger_jobs(trigger_name)
TriggerManager.update_action_metadata(trigger_name, {}) | 1,177 |
def migrate_to_latest(json_dict, info):
"""Migrates the STAC JSON to the latest version
Args:
json_dict (dict): The dict of STAC JSON to identify.
info (STACJSONDescription): The info from
:func:`~pystac.serialzation.identify.identify_stac_object` that describes
the STAC... | 1,178 |
def contact_infectivity_symptomatic_20x50():
"""
Real Name: b'contact infectivity symptomatic 20x50'
Original Eqn: b'contacts per person symptomatic 20x50*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_symptomatic_20x... | 1,179 |
def smart_wn_search(wn, query, pos=None, report_file=None, compact=True, lang='eng', with_eng=True):
""" Search synset in WordNet Gloss Corpus by term"""
if report_file is None:
report_file = TextReport() # Default to stdout
report_file.print("Search Wordnet: Query=%s | POS=%s" % (query, pos))
... | 1,180 |
def write_conllulex_formatted_tags_to_file(prediction_file: TextIO,
gold_file: TextIO,
batch_tags: List[str],
batch_gold_tags: List[str],
batch_upos... | 1,181 |
def _parse_integrator(int_method):
"""parse the integrator method to pass to C"""
#Pick integrator
if int_method.lower() == 'rk4_c':
int_method_c= 1
elif int_method.lower() == 'rk6_c':
int_method_c= 2
elif int_method.lower() == 'symplec4_c':
int_method_c= 3
elif int_metho... | 1,182 |
def get_diffusion_features(repo_path, branch):
"""
Function that extracts the first commits diffusion features. It then starts
a number of processes(equal to the number of cores on the computer), and then
distributes the remaining commits to them.
"""
repo = Repository(repo_path)
head = rep... | 1,183 |
def convert_example(example,
tokenizer,
label_list,
max_seq_length=512,
is_test=False):
"""
Builds model inputs from a sequence or a pair of sequence for sequence classification tasks
by concatenating and adding special tokens. ... | 1,184 |
def load_config_file(filepath):
"""
Load a configuration as an options dict.
Format of the file is given with filepath extension.
:param filepath:
:type filepath:
:return:
:rtype:
"""
if filepath.endswith('.json'):
with open(filepath) as config_file_data:
return ... | 1,185 |
def coordinator_setup(start_heart=True):
"""
Sets up the client for the coordination service.
URL examples for connection:
zake://
file:///tmp
redis://username:password@host:port
mysql://username:password@host:port/dbname
"""
url = cfg.CONF.coordination.url
lock_... | 1,186 |
def _to_jraph(example):
"""Converts an example graph to jraph.GraphsTuple."""
example = jax.tree_map(lambda x: x._numpy(), example) # pylint: disable=protected-access
edge_feat = example['edge_feat']
node_feat = example['node_feat']
edge_index = example['edge_index']
labels = example['labels']
num_nodes ... | 1,187 |
def test_cmd_dict_input_with_args():
"""Single command string works with multiple args."""
cmd = get_cmd('tests/testfiles/cmds/args.sh',
r'tests\testfiles\cmds\args.bat')
context = Context({'a': 'one',
'b': 'two two',
'c': 'three',
... | 1,188 |
def get_urls(page_links):
"""Insert page links, return list of url addresses of the json"""
urls = []
for link in page_links:
link1 = link.replace('v3', 'VV')
game_id = ''.join([char for char in link1 if char in list(map(str, list(range(10))))])
json_url = f'http://www.afa.com.ar/dep... | 1,189 |
def game_over(username):
"""When the user have lost the game.
Args:
username: A string representing the username.
"""
print os.linesep + "Game Over!!! " + username + ", I am sorry! Better luck next time! :-)" + os.linesep
if raw_input(username + " would you like to play again? (y/n) ").lo... | 1,190 |
def KK_RC79_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | 1,191 |
def _resampling_from_str(resampling: str) -> Resampling:
"""
Match a rio.warp.Resampling enum from a string representation.
:param resampling: A case-sensitive string matching the resampling enum (e.g. 'cubic_spline')
:raises ValueError: If no matching Resampling enum was found.
:returns: A rio.war... | 1,192 |
def _call_twitter_api(query):
"""helper function to call twitter api
Args:
query (str): query string made by _preprocess_query function
Returns:
generator: response object in generator
"""
return sntwitter.TwitterSearchScraper(query=query).get_items() | 1,193 |
def parse_superfamilies(filepath: str) -> List[Method]:
"""
Parse the CathNames.txt file distributed with CATH-Gene3D releases
:param filepath:
:return:
"""
signatures = []
reg = re.compile(r"^(\d\.\d+\.\d+\.\d+)\s+([a-zA-Z0-9]+)\s+:(.*)$")
with open(filepath, "rt") as fh:
for l... | 1,194 |
def on_click(event):
"""
On left-click (=event) the 'disabled' entry is free, and the placeholder deleted
"""
entry.configure(state=NORMAL)
entry.delete(0, END)
# make the callback only work once
entry.unbind('<Button-1>', click) | 1,195 |
def Weekday(datetime):
"""Returns a weekday for display e.g. Mon."""
return datetime.strftime('%a') | 1,196 |
def test_get_current_week_number_returns_1_on_first_week_of_semester(
current_date: datetime,
):
"""
Assumes a semester ends at week 22 (included), which has been the case so far.
Any date within the first week should return 1, EXCLUDING the following
Sunday, on which day the script updates in advan... | 1,197 |
def ExposeXcresult(xcresult_path, output_path):
"""Exposes the files from xcresult.
The files includes the diagnostics files and attachments files.
Args:
xcresult_path: string, path of xcresult bundle.
output_path: string, path of output directory.
"""
root_result_bundle = _GetResultBundleObject(xcr... | 1,198 |
def host_list(request):
"""List all code hosts
:rtype: json
"""
hosts = Host.objects.all()
serializer = host_serializer(hosts, many=True)
return JsonResponse(serializer.data, safe=False) | 1,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.