content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_vcs_link(ireq):
"""
Returns whether an InstallRequirement is a version control link.
"""
return ireq.link is not None and not ireq.link.is_artifact | 04035e09b9bca224bb2f0d7a3b9ffbe0c0bd2528 | 664,552 |
import argparse
import ast
def parse_args():
"""
parse args
"""
parser = argparse.ArgumentParser(description='ternarybert task distill')
parser.add_argument('--device_target', type=str, default='GPU', choices=['Ascend', 'GPU'],
help='Device where the code will be implemente... | 71d51ae8d7cec554b0766a01c87403e796843753 | 664,553 |
def option7(current_person):
"""The children of a person can printed using this function.
Parameters:
current_person:
The current Person object.
Returns:
The current Person object.
"""
ch_lst = current_person.get_children()
if len(ch_lst) == 0:
print(f"No children f... | 34cf67473233f9c79e7f1040fdf27686dd543e38 | 664,554 |
def disp(c, domain=True):
"""
Create a string formatted list of the curve's x-values if domain is True, otherwise y-values.
>>> c = pydvif.span(1, 10)
>>> yvalues = pydvif.disp(c, False)
:param c: The given curve
:type curvelist: Curve
:param domain: if True, display the x-values of the c... | 8bad553c92cd1ea45e341a6382377eb7137bfe99 | 664,555 |
def is_model_class(val) -> bool:
"""Return whether the parameter is a SQLAlchemy model class."""
return hasattr(val, '__base__') and hasattr(val, '__table__') | 2e7cc71a891f1a394d2ba3ff4273bdb5fd4e4995 | 664,557 |
def home_view(request):
"""home view"""
# if request.authenticated_user is not None:
# return HTTPFound(location=request.route_url('portfolio'))
return {} | c2b2462486e30bf2a61ee209e4e3ed283ad59161 | 664,558 |
def get_range(value):
""" Return the range for under or over limit message """
if (value & 4) == 4:
return '80 - 130'
elif (value & 3) == 3:
return '60 - 110'
elif (value & 2) == 2:
return '50 - 100'
elif (value & 1) == 1:
return '30 - 80'
else :
return '... | fc33f45596b88e610b502f2a5d23a8fca5cb6b71 | 664,559 |
import re
def cut_string(text, length):
"""
@summary: 将文本按指定长度拆分
---------
@param text: 文本
@param length: 拆分长度
---------
@result: 返回按指定长度拆分后形成的list
"""
text_list = re.findall(".{%d}" % length, text, re.S)
leave_text = text[len(text_list) * length:]
if leave_text:
t... | 4907b59e990c49f9531b9cf7c6eb3c8bb2b55912 | 664,560 |
import re
def _escape(line):
"""
Escape the syntax-breaking characters.
"""
line = line.replace('[', r'\[').replace(']', r'\]')
line = re.sub('\'', '', line) # ' is unescapable afaik
return line | 8b43b7ddf42af68866eb81fdf91036d28489f897 | 664,561 |
def diff_lists(li1, li2):
"""
Retrieve the difference between two lists
"""
return [list(list(set(li1) - set(li2)) + list(set(li2) - set(li1)))] | 07660e149652d6b0145c36ea9f62413590573816 | 664,562 |
def build_message(attr_name, val1, val2, details=""):
""" Build error message for is_has_traits_almost_equal and
is_val_almost_equal to return.
"""
type1 = type(val1)
type2 = type(val2)
msg = "Different {} {}. Types: {} vs {}. Values: \n{} \nvs \n{}"
msg = msg.format(attr_name, details, type... | e760602531da9fc56ea1619202bfed7af1251558 | 664,563 |
def string_to_number(byte_repr_str):
"""
Args:
byte_repr_str (str): e.g. 100MB, 10Kb; float is not allowed
Returns:
num (int): bytes
"""
is_parsing_unit = False
num = 0
for ch in byte_repr_str:
if ch.isdigit():
assert is_parsing_unit is False
n... | 4f82ba2acf2af5d7611e5448a5f78c7fe48da9cb | 664,564 |
def read_article(file_name):
"""
Reads the Text file, and coverts them into sentences.
:param file_name: Path of text file (line 12)
:return: sentences
"""
file = open(file_name, 'r', encoding="utf-8")
filedata = file.readlines()
article = filedata[0].split(". ")
sentences = []
... | 863bebfdf07e419abeb7be206e88259cc39014f7 | 664,565 |
def subset_sum_squeeze(data, subset={}, sum_dims=None, squeeze=False):
"""
Take an xarray DataArray and apply indexing, summing and squeezing,
to prepare it for analysis.
Parameters
----------
data : xarray DataArray
A Calliope model data variable, either input or output, which has been... | 182c8ddab3642c5fe9bec8520cbc5badb43b8f4e | 664,566 |
import subprocess
def expand_hosts(hostlist):
""" Expand a slurm hostlist like "openhpc-compute-[12-13]" into a list of strs.
Requires `scontrol` to be available.
"""
hostnames = subprocess.check_output(('scontrol', 'show', 'hostnames', hostlist), universal_newlines=True).strip('\n').split('\... | 80cc576a06bc28d5daf1485b1559df378780515f | 664,567 |
import html
def sub_dict(data, keys):
"""
取字典中有用的数据出来
获取字典的子字典可以用字典推导式实现
:param data:字典
:param keys:键值列表
:return:有用的键值组成的字典
"""
return {k: html.unescape(data[k]) for k in data if k in keys} | 9ef17709079f6120a2c4c9200aec26d11107465f | 664,568 |
def makeSearchUrl(whichShow):
"""Return single title/season/episode search url from show object"""
# pattern is TITLE%20S##E##/0/7/0
searchUrl = ''
baseUrl = "http://thepiratebay.se/search/%s%%20S%sE%s/0/7/0"
baseUrl2 = "http://thepiratebay.se/search/%s%%20E%s/0/7/0"
#baseUrl = "http://pi... | 14613ae72221e803add0dbf9fdd0938002906381 | 664,569 |
def find_root_node(program_tree):
"""Find root program."""
return [program for program in program_tree if not program_tree[program]][0] | 5b7cbc9b317d80edaa6082d7ebce3f7e127be200 | 664,570 |
def long_objects(leaf_image_obj, ratio=3):
"""returns list of objects with self.width_length_ration >= ratio"""
return [x.label for x in leaf_image_obj.stomata_objects if x.width_length_ratio() >= ratio ] | 5ea7f7f27e03b2a78e8ae54accf2a61a614ff713 | 664,571 |
def set_bit_k(int_val, k):
"""Sets the bit at offset k"""
return int_val | (1 << k) | 03fbcfd725bc1c4a1f7997541161a8ffbcacfafd | 664,572 |
def create_stream_size_map(stream_indices):
"""
Creates a map from stream name to stream size from the indices table.
:param stream_indices: The stream indices table.
:return: The map.
"""
return {pair[0]: len(pair[1]) for pair in stream_indices} | e8ef75da347d6e509bd6f25b3ccf88492d0260f1 | 664,573 |
import string
import random
def generate_key(key_length: int = 16, key_pattern: str = "x#x#"):
"""
generates a unique activation key with a length and a pattern
key_length: length of the key (default 16)
key_pattern: set of x's and #'s in a string (default "x#x#")
"x": random letter
"#": rando... | 59364ca45c714d9e1e119561e8ec0b8a08e868f7 | 664,574 |
import hashlib
def get_redis_key_for_cli(cli_nonce, server_nonce):
"""Get the redis store from CLI token and user code."""
cli_nonce_hash = hashlib.sha256(cli_nonce.encode()).hexdigest()
return f"cli_{cli_nonce_hash}_{server_nonce}" | 50a6bf3f44a60f7ec4e5ba1e76cdfee94bf0a0cb | 664,575 |
def _is_name_start(css, pos):
"""Return true if the given character is a name-start code point."""
# https://www.w3.org/TR/css-syntax-3/#name-start-code-point
c = css[pos]
return (
c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_' or
ord(c) > 0x7F) | 95fee9bbc2edfe0e61cbd145c1fb3b2a2ff1deef | 664,576 |
import torch
def nearest_neighbor_grad(
averaged_grad,
embedding_matrix,
trigger_token_ids,
tree,
step_size,
increase_loss=False,
num_candidates=1,
):
"""
Takes a small step in the direction of the averaged_grad and finds the nearest
vector in the embedding matrix using a kd-tr... | 6c1c6ab80769a7942fed28c856c3796965a823f4 | 664,578 |
def validate_timestamp(val):
"""
Returns a boolean indication that a field is a valid timestamp - a
floating point number representing the time in seconds since the Epoch (so
called POSIX time, see https://en.wikipedia.org/wiki/Unix_time).
"""
return (isinstance(val, float) and val >= 0.0) | d2a47e448c461437f913abd531bcd84df171b6d5 | 664,579 |
import argparse
import logging
def get_parser():
"""Return the argument parser setup."""
parser = argparse.ArgumentParser(
description='Tag branch based on commit messages')
parser.add_argument('-b', '--branch', type=str, default='master',
help='On what branch to work on. D... | 6212ee09acedc8a09b4210d72cdbd902025f02fb | 664,580 |
def TDict(val):
"""Checks if the given value is a dictionary.
"""
return isinstance(val, dict) | 73675d919a3d6fe192e76768b840495de48a5b25 | 664,581 |
def find_longest_match(s, sub):
"""returns the number of byte to look backward and the length of byte to copy)"""
if sub == "":
return 0, 0
limit = len(s)
dic = s[:]
l = 0
offset = 0
length = 0
first = 0
word = ""
word += sub[l]
pos = dic.rfind(word, 0, limit + 1)
... | 5ab48407d181a57b3e3f40b24ac4df2c16dbd224 | 664,582 |
def list_var_name(list_of_tensors):
"""输入一个Tensor列表,返回一个包含每个tensor名字的列表
"""
return [var.name for var in list_of_tensors] | 90259603f31c60e963eccbf3613a893f7aaa728e | 664,583 |
from typing import OrderedDict
def invert(mapper):
"""Invert a dict of lists preserving the order."""
inverse = OrderedDict()
for k, v in mapper.items():
for i in v:
inverse[i] = k
return inverse | 0cd15a56762b36a774cb91b711f5d893da62de1f | 664,585 |
import importlib
def dotpath_to_obj(dotpath):
"""Loads and returns the object referenced by the string DOTPATH_TO_MODULE.OBJ_NAME"""
*module_path, obj_name = dotpath.split('.')
if len(module_path) > 0:
return getattr(importlib.import_module('.'.join(module_path)), obj_name)
else:
retur... | 3105aaf19e766b16874523bfff7660c5399bf442 | 664,586 |
import socket
import struct
def inet_aton(addr):
"""Convert an IP addr in IPv4 dot notation into an int.
addr IP address as a string
returns integer
"""
b = socket.inet_aton(addr)
return struct.unpack('!I', b)[0] | de8a09f484dae318353198ee4f93d9d8e6b597fe | 664,588 |
def validate_nodes_number(nodes_number: int) -> int:
"""
Check whether a number of nodes is sufficient to detrend the data.
Parameters
----------
nodes_number : int
The number of nodes.
Returns
-------
int
The number of nodes.
Raises
------
ValueError
... | 333b08daba41ef11a18a5ff0dc03af8fc429b99b | 664,590 |
def sum_of_all(list_of_nums: list):
"""adds all numbers in a list together and returns the sum"""
sum_of_nums = 0
for num in list_of_nums:
sum_of_nums += num
print(sum_of_nums)
return sum_of_nums | a91ddda3294eb2d0e90f95d5027397a8bd5ba623 | 664,591 |
def link_topics_and_weightings(topic_words, topic_words_weighting):
"""
Pair every words with their weightings for topics into tuples of (), for each topic.
:param topic_words: a 2D array of shape [topics, top_words]
:param topic_words_weighting: a 2D array of shape [topics, top_words_weightings]
:... | 6b751c92fd36c623946819ddcc24c63adbdb082c | 664,592 |
def clean_caption(caption):
"""Removes unnecessary parts of an Instagram post caption
It removes all the hashtags and converts tags in plain text (@marco97pa --> marco97pa)
Args:
caption: a text
Returns:
the same caption without hashtags and tags
"""
clean = ""
words = capti... | 947cbce981d29a07a1528004dd15f5a574529e3a | 664,593 |
def c_to_f(tempc):
"""
Parameters
Temp (C)
Returns
Temp (F)
"""
tempf = tempc * (9./5.) + 32.
return tempf | 8ac270349ba06b8eaac7b820b5a85f27b26e9a3a | 664,594 |
def getMcbsdValue(grant):
"""Returns the MCBSD (OOBE emission mask) value in dB for a grant.
MCBSD is the CBSD conducted power (in dBm) on the frequency segment,
using the Tx mask of CBSD according to R0-DEV-05(e).
Args:
grant: A |GrantRecord| object as defined in SAS-SAS specification.
"""
return (-1... | 0711ed21b23b43127de3d50af8cf6f1b3e65f593 | 664,595 |
import pickle
def load_goal_set(goal_file_path):
"""
Utility method to load the user goals
# Arguments:
- goal_file_path: the path to the user goals file
"""
# Read all goals
all_goal_set = pickle.load(open(goal_file_path, 'rb'))
# Initialize and create the list of all... | 397980aa15a9135be006ed67ccc7613f385862f1 | 664,596 |
def rec_mergeSort(array):
""" Perform merge sort by recursively splitting array into
halves until all the values are separated
then do a piece wise comparason to fill the array in order
"""
# check if array is none
if len(array) > 1:
# find mid index of list
mid = len(array) // 2... | 102d924305fe9c801f4b3db15f714c66bfe18bbd | 664,597 |
import os
import hashlib
def file_checksum(filepath):
"""Calculate md5 checksum on file
:param filepath: Full path to file (e.g. /home/stack/image.qcow2)
:type filepath: string
"""
if not os.path.isfile(filepath):
raise ValueError("The given file {0} is not a regular "
... | ca6ced1b28e1eef06df9e19447850f4f5f059d1b | 664,599 |
def is_line_continuation(line):
"""Determine whether L{line} has a line continuation marker.
.properties files can be terminated with a backslash (\\) indicating
that the 'value' continues on the next line. Continuation is only
valid if there are an odd number of backslashses (an even number
woul... | fea5d0063c31a82df1dd29b4ad9eea304689fee6 | 664,601 |
def get_skip_initial_samples_min(post_proc_args):
""" Function iterates over a list of arguments of the form
["plot_all_individual_cdfs", "visualise_traceworkload", "skipmins_3"]
searches for "skipmins_3" and returns 3 in this case.
This parameter indicates how many minutes to skip from the ycsb results... | a7fd0007a0ad349a55fd5490fe4baec0c76ab14d | 664,602 |
def duration_to_string(value):
"""Converts the given timedelta into an appropriate ISO-8601 duration format for JSON. Only handles positive
durations correctly. Fractional seconds are rounded.
:param value: The timedelta to convert
:type value: :class:`datetime.timedelta`
:returns: The ISO-8601 dur... | 06bc74c30de00ac223c208db06f0b48cd0cb2ad5 | 664,603 |
import os
def find_doc(docsdir, filename):
"""tries to find the file, if not returns false."""
path = None
if not docsdir:
return
for dirpath in docsdir:
candidate = os.path.join(dirpath, filename)
if not os.path.exists(candidate):
continue
if path is not No... | 63977825274dce3c4ea2f43e4742b9bc3e55a9fb | 664,604 |
import subprocess
def alter_attribute(job_id, attribute):
"""
Change job attribute
:param job_id: int, job id
:param attribute: string, job attribute
:return: if success, return 1, else return 0
"""
try:
parameter = ['qalter']
parameter.extend(attribute)
parameter.a... | 2f9bc1ffd9a44e8cad672e06fb240f7ec70443be | 664,605 |
def lookup_prev_stage_start(stage_boundaries, t):
"""
Returns the previous stage start timestamp from a list/set of stage
boundaries and current time.
"""
return max([0] + [x for x in stage_boundaries if x <= t]) | c897431404533ba07e5e160b6688e6531bedf320 | 664,607 |
import logging
def get_repo_path(ont_obj):
"""
Extract the repository path for the given object
"""
repo_path = None
if 'repository' in ont_obj:
repo_path = ont_obj['repository']
elif 'tracker' in ont_obj:
tracker = ont_obj['tracker']
if tracker is not None and 'github' in tracker:
repo_... | 12c227f862fec91b4483a68328fe882bc778004a | 664,608 |
import logging
import re
def format_taxonomy(tax, taxID):
"""Formatting taxonomy string
"""
logging.info('Taxonomy string provided: {}'.format(tax))
logging.info('TaxID provided: {}'.format(taxID))
try:
taxID = int(float(taxID.strip()))
except ValueError:
msg = 'WARNING: t... | 9a1b96c325194e742ae09708ec0e2a51d2af666f | 664,609 |
import subprocess
import pandas
import io
def export(table, *args, **kwargs):
""" Export table from StanhopeFramers.mdb.
Arguments:
table (str): Name of table to export
Returns:
DataFrame of table.
"""
cmd = ['mdb-export', '/data/StanhopeFramers.mdb', table]
... | 0be860e16ea1476152caf2046126623a5061a872 | 664,611 |
import torch
def sentence_emb(inp_token_embeddings, n=4):
"""
Adds the last n layers of each token and stacks all the input token representations except the first and last ones.
It considers that the first and last tokens are special BERT tokens ([CLS] and [SEP]) and it drops them within the
function
... | 5d625c8e1f0cf26a921e190da7ff8bd9d111ac31 | 664,612 |
import struct
def unpack_int(string):
"""Read an n-byte big-endian integer from a byte string."""
(ret,) = struct.unpack_from('>I', b'\x00' * (4 - len(string)) + string)
return ret | d0d3b14e006977f23c21f1953df0b210a79e2ca4 | 664,613 |
import struct
def timestamp_to_bytes(t):
"""Convert timestamp to 96 bit representation
Bits 0 - 63 are big endian two's complement encoded :attr:`Timestamp.s` and
bits 64 - 95 are big endian two's complement encoded :attr:`Timestamp.us`.
Args:
t (Timestamp): timestamp
Returns:
b... | 1d3c72706ca1216bd611ec323bd624f023de6d6f | 664,614 |
def lookup(stmt, embeddings, dictionary):
"""
Look up a statement's embedded vector in the embedding matrix
:param stmt: statement to be looked up (string)
:param embeddings: embedding matrix
:param dictionary: [keys=statement, values==statement index]
:return: embedded vector
"""
return... | b7dc20092618dbbffb75941c7ab04efdc7af16c7 | 664,615 |
def search_entities(raw_text_string, search):
"""Searches for known entities in a string.
Helper function for construct_entity_conet(). Iterates over a list
of entities and looks to see if they are present in a given text
string. If they are, then it will append the entity to a list for
each te... | 13e1a424154c54099bbd40ad8b9615cde5f0d99b | 664,616 |
def generate_div_matchups(league_structure):
"""
Generate divisional matchups (6 total per team):
2 per team from the same division (2m x 3t)
"""
div_matchups = []
for division in league_structure['divisions']:
for team in division.teams.all():
for rival_team in division.team... | db4231cc23fe6e9fec3920501dd1698db4853ded | 664,618 |
import requests
def send_query(query_string, clean=False):
"""
Send a query/request to a website
:param query_string: string with query content
:param clean: (Default value = False)
"""
response = requests.get(query_string)
if response.ok:
if not clean:
return respon... | 1f12370f4dcbda4c79c048e4e597bcc68308f22b | 664,619 |
def emit_header():
"""
Emits RIB header string
"""
s = ""
s += "# RenderMan RIB-Structure 1.1\n"
s += "# Exported by htol, Houdini to lucille RIB exporter by Syoyo Fujita\n"
s += "Display \"untitled.hdr\" \"framebuffer\" \"rgb\"\n"
return s | 0627d666c16ae3e45187c3423335d92288e816d0 | 664,620 |
def int_list_to_string(intli, sep=''):
"""整数列表转字符串
:param intli:
:param sep:
:return:
>>> int_list_to_string([1,2])
'\\x01\\x02'
"""
return sep.join([chr(n) for n in intli]) | 10fe03ab2ddb1a5602e816dac398e6ce57fca082 | 664,621 |
def typeCounter(tails, typeList=[]):
"""
Takes nest tail list data structure and compares it to a list of types for transcripts. Your own type list can
be provided or it can default to below. It then looks through the type list and counts how many of each type
of transcript it sees. Returns a nested lis... | 6cc033ad3a3df69500b8f23340d0bcbc641340a9 | 664,623 |
def can_partition_dp(nums):
"""
{1, 2, 3, 9}, S=16//2=8
^
0 1 2 3 4 5 6 7 8
{1} 0 1 0 0 0 0 0 0 0
{1,2} 0 1 2 3 0 0 0 0 0
{1,2,3} 0 1 2 3 4 5 6 0 0
{1,2,3,9} 0 1 2 3 4 5 6 0 0
0 1 2 3 4 5 6 7 8
{1} 1 1 0 0 0 0 0 0 0
{1,1} ... | 6032a56a5ec8602c7c5bf9ef1cc4daab16c870ed | 664,624 |
from subprocess import run, PIPE, CalledProcessError
def dump_version(command):
"""
Dump version for GCC/Clang compilers
Parameters
----------
command : str
Compiler command.
Returns
-------
float or None: version if found else None
"""
try:
if (
... | 84c68164ff8cbebcc4da10799f0fcb6a4d2f1b52 | 664,625 |
def sources_and_sinks(
data,
enforce_earliest_start=False
):
"""
Calculates all sources and sinks in a given dataset.
:param list data: a list of :obj:`decitala.search.Extraction` objects.
:param bool enforce_earliest_start: whether to require that all sources begin at the earliest
detected onset.
... | d869db3f0a9b330faa99cf63ddcef8168637fafb | 664,626 |
def check_json_object(obj):
""" Simple check to fill in the map for automatic parameter casting
JSON objects must be represented as dict at this level
"""
assert isinstance(obj, dict), 'Invalid JSON object: {}'.format(obj)
return obj | f468a0bf098689d01567c3762099f4e7ae875162 | 664,627 |
def underscore_to_camelcase(s):
"""
Convert lowercase_with_underscore names to CamelCase.
"""
return ''.join(x.capitalize() or '_' for x in s.split('_')) | 8de189007ac25b53037cb17e267ec4b81ee80f8f | 664,628 |
def pixel_wise_boundary_precision_recall(pred, gt):
"""Evaluate voxel prediction accuracy against a ground truth.
Parameters
----------
pred : np.ndarray of int or bool, arbitrary shape
The voxel-wise discrete prediction. 1 for boundary, 0 for non-boundary.
gt : np.ndarray of int or bool, s... | 9a39bbcfbc8ca8e7838ea8713636cbd8a66b5186 | 664,629 |
import os
import glob
def _getCookieFiles(location, name):
""" Rummages through cookie folder, returns filenames including `name'.
`name' is normally the domain, e.g 'activestate' to get cookies for
activestate.com (also e.g. for activestate.foo.com, but you can
filter out such accidental hits later).... | 2eba31a91fcb54b973a36ee6a9f611ebab39d073 | 664,630 |
def lookup(sym, env):
"""Look up a symbol repeatedly until it is fully resolved."""
try:
return lookup(env.lookup(sym), env)
except:
return sym | 9f3635b4373c335872c40dd83c92d9c051254bf3 | 664,631 |
def cli(ctx, tool_id="", name="", trackster=""):
"""Get all tools, or select a subset by specifying optional arguments for filtering (e.g. a tool name).
Output:
List of tool descriptions.
.. seealso:: bioblend.galaxy.toolshed.get_repositories()
"""
return ctx.gi.tools.get_tools(tool_id=tool_i... | 3c276762a489aa1e851623609df8c63d6b944f9f | 664,632 |
import itertools
def flatten(list_, gen=False):
""" Flatten a list. """
if gen:
return itertools.chain(*list_)
else:
return list(flatten(list_=list_, gen=True)) | b16729ecb0779ce9c3480ea75b8d734c87da65e1 | 664,633 |
import numpy
def binsnD_to_2d(bins, ax1, ax2):
"""Collapse n-D bucketing array to 2-D, merging buckets for other dims.
Take a n-D bucketing array (n>=2), such as returned by bin_nD, and
merge all buckets thus reducing it to 2D, retaining ax1 and ax2.
For examble, binsnD_flatiter(bins, 1, 2) will retu... | 88dada28fbcc9f543df03fb998ea6737743663cd | 664,634 |
import socket
def canonicalize_ipv6(addr):
"""Return canonical form of IPv6 address.
>>> canonicalize_ipv6('ff00:1:02:0:0::3:4')
'ff00:1:2::3:4'
>>> canonicalize_ipv6('::1')
'::1'
"""
return socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6,
... | f6ee7ad4cf55b4d444c0b6cf4747bc16b0549211 | 664,635 |
def JsBoolString(bool_value):
"""Write boolean value as javascript boolean."""
if bool_value:
return "true"
else:
return "false" | 0e2a6d5d005294c8243ab5702374a65a65b100dd | 664,636 |
def split_tracks(midfile):
"""Break file into different tracks and store them separately
:param midfile: MidiFile object
:return: meta messages, instrument messages
"""
meta_messages = []
instrument_messages = []
for i, track in enumerate(midfile.tracks):
temp_meta_messages = []
... | 50ec899161797dffaf8bc9a838efe48beabe43ec | 664,637 |
def strl(a_list):
""" makes each element in a list a string.
"""
return map(str, a_list) | dbdd2e97feb486c5b167ff3a3cf04816cbbbcca4 | 664,638 |
import requests
def get(agent: str, path: str, **kwargs):
"""Get."""
return requests.get(f"{agent}{path}", **kwargs) | c99f36bbabef662cf9b2440a7eebc638479d887a | 664,639 |
import os
import ftplib
import socket
def uploadFile(dir_ftp, filename_ftp, filepath_local, host, port, username, password):
"""
参数说明:
* dir_ftp: 在 ftp 服务器上存储文件的路径;
* filename_ftp: 存储到 ftp 服务器上的文件名;
* filepath_local: 需要上传的本地源文件路径;
* host: ftp 服务器地址(ip/域名);
* port: ftp 服务器端口号,一般是 21;
* ... | 659313990f114573c6047c0aad4d73127ad610ab | 664,641 |
import requests
def get_node(name, api_url, headers, validate_certs=True):
"""Returns a dict containing API results for the node if found.
Returns None if not just one node is found
"""
url = "{}/v3/nodes?name={}".format(api_url, name)
node_search = requests.get(url, headers=headers, verify=valid... | d6df2228d3a49cf82f2f38caff3204a738ea5547 | 664,642 |
import os
import sys
def _from_local_path(path):
"""Convert SFTP path to local path"""
path = os.fsencode(path)
if sys.platform == 'win32': # pragma: no cover
path = path.replace(b'\\', b'/')
if path[:1] != b'/' and path[1:2] == b':':
path = b'/' + path
return path | 99c04520d0873d1b854b0ce5115922619eb52e32 | 664,643 |
import os
def parse_requirements(path: "str | os.PathLike[str]") -> "list[str]":
"""Parse a ``requirements.txt`` file and strip all empty and commented lines."""
ret = []
with open(path, "r", encoding="utf8") as f:
for i in f:
j = i.split("#", 1)[0].strip().rstrip()
if j:
... | 7a511547c19ce1623f262a6e1e80102dd5d05310 | 664,644 |
def get_max_operand_size(operands):
"""
Given the list of named tuples containing the operand value and bit width, determine the largest bit width.
:param operands: list of Operand objects
:return: largest operand width
"""
return max(operand.width for operand in operands) | 876c991b90f70ca349a18230ec74b4fb431af909 | 664,645 |
import argparse
def parse_arg_list():
"""Uses argparse to parse the required parameters
:returns: command line arguments.
"""
parser = argparse.ArgumentParser(
description='Changes permissions of files inside the folder to commenter after deadline.',
formatter_class=argparse.RawTextHe... | 8675e8d4f4927870db61abefd2f7f11fe182a9a8 | 664,646 |
def _read_file_data(filepath):
"""Read file data.
:param filepath: The file path.
:return: The file contents.
"""
data = open(filepath, 'rb').read()
return data | 55481b78b9ab3f9340790458cb33955f2896f273 | 664,647 |
from typing import Optional
from typing import Dict
import json
def load_result_file(eval_file) -> Optional[Dict]:
"""Loads the results data from a submitted file.
If the file cannot be read, returns None.
"""
try:
with open(eval_file, 'r') as f:
result = json.load(f)
... | d8ba0b8bf23763e7a5fe33e2ac8cfd7a0a6d87de | 664,648 |
import sys
def _trychar(char, fallback, asciimode=None):
"""
Logic from IPython timeit to handle terminals that cant show mu
Args:
char (str): character, typically unicode, to try to use
fallback (str): ascii character to use if stdout cannot encode char
asciimode (bool): if True,... | 5ec4e1f5c597c99c02a2c49dd04d897dbc737b3c | 664,649 |
import numpy
def predictions_in_training_range(Y_train, Y_pred):
"""Fraction of predictions in the training data range (for testing regression interpolation vs extrapolation)"""
Y_min = Y_train.min(axis=0)
Y_max = Y_train.max(axis=0)
in_range = (Y_pred <= Y_max[numpy.newaxis, :]) & (Y_pred >= Y_min[n... | 89360903066b589f62c672e24ddfa5bd3b2e5bd4 | 664,650 |
import json
def mock_lockfile_update(path):
"""
This is a mock update. In place of this, you might simply shell out
to a command like `yarn upgrade`.
"""
updated_lockfile_contents = {
'package1': '1.2.0'
}
with open(path, 'w+') as f:
f.write(json.dumps(updated_lockfile_cont... | 9a867b4b351241af60e307e0bce613adb0899add | 664,652 |
def parse_titles(soup):
"""
Takes a list of html codes from Craigslist category search pages and returns
a list of links to individual post pages as 'page_links'.
"""
global keywords
page_links = []
print(len(soup))
for elem in soup:
page_content = []
title_links = elem.f... | a28dc361f1d754f5211faaee7f2bc7affd54656b | 664,653 |
def NSE(y_pred, y_true):
"""
Calculate the Nash-Sutcliffe efficiency coefficient.
"""
return 1 - sum((y_pred - y_true) ** 2) / sum((y_true - y_true.mean()) ** 2) | f4098e3add7228ab999f525724cd1922232ac3b2 | 664,654 |
from typing import Dict
import requests
import os
def get_conll_data() -> Dict[str, str]:
"""
Download and cache a copy of the CoNLL-2003 data set.
:returns: Mapping from fold name to file name
"""
# Download and cache a copy of the data set.
# NOTE: This data set is licensed for research... | 089b5d821c071063bb6aa7b1b20ba7c1eff19ef6 | 664,655 |
def sort_params(model, params):
"""Sort parameters to be consistent with the model's parameter order"""
return [p for p in model.parameters if p in params] | 295e9defae5311b596b53265ddd38fc0b3605c02 | 664,656 |
def known_organisms():
"""
Get the names of organisms that RGD annotates. This will only return 'rat'
currently. While they have annotations for other databases we only process
rat because this is the only organism that they provide chromosomes that we
can extract sequences from. Without that I woul... | 71df27aed75c46d3aee413f028b40c26d43bb7d7 | 664,657 |
def merge_unkown_celltypes(y, unknown_celltypes):
"""
Merge all unknown celltypes together
:param x:
:param y:
:param unknown_celltypes:
:return:
"""
celltypes = list(y['Celltype'])
new_celltypes = ["Unknown" if x in unknown_celltypes else x for x in celltypes]
y['Celltype'] = ne... | f7e0e45d0cd0ebf1b47d3c2e15c0566b0fdf685f | 664,658 |
def widget_type(field):
"""
Return the widget type
"""
if hasattr(field, 'widget'):
return field.widget.__class__.__name__.lower()
elif hasattr(field, 'field'):
return field.field.widget.__class__.__name__.lower()
else:
return None | 7d6a373665324f0b75857878c083e5ca82509e0b | 664,659 |
def ConstructHistogram(doc, name, histogram_dict):
"""Constructs a histogram node based on the |histogram_dict|."""
histogram = doc.createElement('histogram')
# Set histogram node attributes.
histogram.setAttribute('name', name)
if 'enum' in histogram_dict:
histogram.setAttribute('enum', histogram_dict['e... | 6e6393069c6857a6dd90360ddf21f28e07873082 | 664,660 |
import argparse
def init_args():
"""Initialize argument parser"""
parser = argparse.ArgumentParser(description="Submit files to scio")
parser.add_argument("url", metavar="URL", type=str, help="URL of scio submit")
parser.add_argument("files", metavar="FILE", type=str, nargs='+',
... | c97052493a19830ea8e34d48c2584359c6067108 | 664,662 |
def check_args(args):
"""See if we got our minimal set of valid arguments."""
ok = True
message = ""
if not args.output_root :
ok = False
message += "Didn't get directory for output (--output-root) "
return([ok,message]) | ce4c45b146a281057201229d461542d942d6291a | 664,663 |
def unflatten1(flat_list, reverse_list):
"""Rebuilds unflat list from invertible_flatten1
Args:
flat_list (list): the flattened list
reverse_list (list): the list which undoes flattenting
Returns:
unflat_list2: original nested list
SeeAlso:
invertible_flatten1
... | 4f583f0c29db32865403be4a17aabcdecef4e2ce | 664,664 |
import zipfile
def zipFileIsGood(filePath):
"""
Function to test if a ZIP file is good or bad
@param filePath the zip file to be tested
@return True if the ZIP file is good. False otherwise.
"""
ret = True
try:
the_zip_file = zipfile.ZipFile(filePath)
badFile ... | 5f856cd40f0767b44df362c097aab2b09faf637c | 664,665 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.