content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def reports_home(request):
"""Some default page for reports home page."""
try:
blank_date = '..' * 23
blank_time = '.' * 20
address = 'P.O Box %s' % ('.' * 30)
params, location = {}, '.' * 20
form = CaseLoad(request.user)
if request.method == 'POST':
... | 5,302,800 |
def historical():
"""" Retrieve stored data from datastore. """
return {
'page': 'historical',
} | 5,302,801 |
def run_tests(code, probid, subid, test_name):
"""
Run the code on test cases.
Assume that the code is already compiled to [probid]-[subid].
Return the error code (no_err, runtime_err, or mismatch_err) and extra info.
Note: Does not clean up the files. Need to run cleanup afterwards.
"""
u... | 5,302,802 |
def name_from_cmakelists(cmakelists):
""" Get a project name from a CMakeLists.txt file
"""
if not os.path.exists(cmakelists):
return None
res = None
# capture first word after project(), excluding quotes if any
regexp = re.compile(r'^\s*project\s*\("?(\w+).*"?\)', re.IGNORECASE)
li... | 5,302,803 |
def catch_distribution():
"""抓取行政区域确诊分布数据"""
data = dict()
url = "https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_area_counts&callback=&_=%d" %int(time.time()*1000)
for item in json.loads(requests.get(url=url).json()["data"]):
if item["area"] not in data:
data.update({item["ar... | 5,302,804 |
def create_securityhash(action_tuples):
"""
Create a SHA1 hash based on the KEY and action string
"""
from settings import SECRET_KEY
action_string = "".join(["_%s%s" % a for a in action_tuples])
security_hash = sha1(action_string + SECRET_KEY).hexdigest()
return security_hash | 5,302,805 |
def sync_blocks(rpc_connections, *, wait=1, timeout=60):
"""
Wait until everybody has the same tip.
sync_blocks needs to be called with an rpc_connections set that has least
one node already synced to the latest, stable tip, otherwise there's a
chance it might return before all nodes are stably syn... | 5,302,806 |
def mocked_metrics(swag_app: Flask) -> Dict[str, str]:
"""Mocks out the metrics collectors... And verifies that they are called!"""
counter_metric, latency_metric = reset_metrics(swag_app)
# Each test will populate the expected tags and values that should be present.
# If not present, the test fails.
... | 5,302,807 |
def assert_task_core_call(
task_core: MagicMock,
taskname: str,
doer: DoerType,
*doer_args: Any,
test_guest_logger: Optional[str] = None
) -> None:
"""
Test properties of a mock representing :py:func:`tft.artemis.task.task_core`.
The helper verifies several properties of the mock, assum... | 5,302,808 |
def mae(
original,
prediction,
hinge: float = 0):
"""
Mean Absolute Error (mean over channels and batches)
:param original:
:param prediction:
:param hinge: hinge value
"""
d = tf.abs(original - prediction)
if hinge != 0.0:
d = keras.layers.ReLU(threshold... | 5,302,809 |
def record_to_index(record):
"""Route the given record to the right index and document type."""
def doc_type(alias):
try:
return list(current_search_client.indices.get_alias(index=alias, ignore=[404]).keys())[0]
except:
return alias
if is_deposit(record.model):
... | 5,302,810 |
def build_contextData(version, community, server_config):
"""
create ContextData instance based on the SNMP's version
for SNMP v1/v2c, use the default ContextData with contextName as empty string
for SNMP v3, users can specify contextName, o.w. use empty string as contextName
@params version: str, "... | 5,302,811 |
def get_two_point_vel_corr_roll(ui, x, y, z=None, roll_axis=1, n_bins=None,
x0=None, x1=None, y0=None, y1=None,
z0=None, z1=None,
t0=None, t1=None,
coarse=1.0, coarse2=0.2,
... | 5,302,812 |
def random_year_img(dataset: Dict[str, torch.Tensor],
writer: Union[int, None] = None,
rand: np.random.RandomState = np.random.RandomState(seed=1234),
**kwargs) -> Tuple[torch.Tensor, int]:
"""Compose an image of a valid year."""
return compose_random_... | 5,302,813 |
def registration_ptpln(src, tgt, downsampling_voxelsize=2, toggledebug = False):
"""
registrate two point clouds using global registration + local icp
the correspondence checker for icp is point to plane
:param src:
:param tgt:
:param downsampling_voxelsize:
:param icp_distancethreshold:
... | 5,302,814 |
def encrypt(sk, b, mbits=N):
"""Encrypt a bit into a Q-bit integer based on the provided key."""
# Random N-bit integer with the same parity as b
m = (random.randint(2**(mbits-2), 2**(mbits-1) -1) << 1) + b
# Random Q-bit integer
q = random.randint(2**(Q-1), 2**Q) - 1
return (m + sk*q... | 5,302,815 |
def english_to_french(english_text):
"""Translate eng to french"""
translation = language_translator.translate(
text=english_text,
model_id='en-fr').get_result()
print(json.dumps(translation, indent=2, ensure_ascii=False))
return french_text | 5,302,816 |
def mkdir_p(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
From: http://code.activestate.com/recipes/82465-a-friendly-mkdir/
"""
if os... | 5,302,817 |
def dump(score: Score, fp: TextIO, **kw) -> None:
"""
Dump a Score object into a SUS file.
:param score: The score object to dump.
:param score: The score object to dump.
:param space: Whether to add a space after the tag (with space: "#00010: 00", without: "#00010:00").
"""
fp.write(du... | 5,302,818 |
def rebin_data(x, y, dx_new, method='sum'):
"""Rebin some data to an arbitrary new data resolution. Either sum
the data points in the new bins or average them.
Parameters
----------
x: iterable
The dependent variable with some resolution dx_old = x[1]-x[0]
y: iterable
The inde... | 5,302,819 |
def register():
"""Register new user."""
form = RegisterForm(request.form)
if form.validate_on_submit():
User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True)
flash('Thank you for registering. You can now log in.', 'success')
return... | 5,302,820 |
def CSVReader(fileobj, urlcolumn, site=None, *args, **kwargs):
"""Yield Photo objects for each row of a CSV file."""
reader = csv.DictReader(fileobj, *args, **kwargs)
for line in reader:
yield Photo(line[urlcolumn], line, site=site) | 5,302,821 |
def rnaseq_metrics_df(analysis_dir, num_seps=1, sep="."):
"""
Generates RNA-seq metrics
Args:
analysis_dir: directory to pull information from
num_seps: number of seperators to join back to get the name of the item
sep: seperator to split / join on to get full name
Returns:
"... | 5,302,822 |
def _ParseFioJson(fio_json):
"""Parse fio json output.
Args:
fio_json: string. Json output from fio comomand.
Returns:
A list of sample.Sample object.
"""
samples = []
for job in json.loads(fio_json)['jobs']:
cmd = job['fio_command']
# Get rid of ./fio.
cmd = ' '.join(cmd.split()[1:])
... | 5,302,823 |
def check_confidence_interval_arguments(
alpha: float = 0.05,
n_bootstrap_samples: int = 10000,
random_state: Optional[int] = None,
) -> Optional[ValueError]:
"""Check confidence interval arguments.
Parameters
----------
alpha: float, default=0.05
Significance level.
n_bootstra... | 5,302,824 |
def dedent(text: str, num_spaces: Optional[int] = None) -> str:
"""Wrapper around textwrap.dedent
Dedents at most num_spaces. If num_spaces is not specified, dedents as much as possible.
Args:
text: Text that will be dedented.
num_spaces: Number of spaces that will be used for dede... | 5,302,825 |
def print_table(table, **kwargs):
"""
Provide a list of lists for the table
table = [
[ "row1col1", "row1col2", "row1col3"],
[ "row2col1", "row2col2", "row2col3"],
[ "row3col1", "row3col2", "row3col3"]
]
if HEADER=True then divide the first line from the following lines
if NOTABLE=True then no table, c... | 5,302,826 |
def create_app(config_name):
"""
创建flask的应用对象
:param config_name: str 配置模式的模式的名字 ("develop", "product")
:return:
"""
app = Flask(__name__)
# 根据配置模式的名字获取配置参数的类
config_class = config_map.get(config_name)
app.config.from_object(config_class)
# 使用app初始化db
db.init_app(app)
... | 5,302,827 |
def cyclic_pattern_offset(value, pattern=None):
"""
Search a value if it is a part of cyclic pattern
Args:
- value: value to search for (String/Int)
Returns:
- offset in pattern if found
"""
pattern = pattern or cyclic_pattern().encode()
if isinstance(value, int):
sea... | 5,302,828 |
def test_get_projects_dir():
"""
Only uncomment to test on my system, leave commented out so others can run all the tests.
Once I've verified that it works, I can now use it below to get the projects dir, which will
also include the user's home dir.
"""
# assert path.get_projects_dir() == '/home... | 5,302,829 |
def write_totals_to_influxdb():
"""
Writing total connections for each hosts
"""
for h in data['hosts']:
json_body = [
{
"measurement": "subscribers",
"tags": {
"type": 'sub-' + data['hosts'][h]['ip']
},
... | 5,302,830 |
def lookup_file():
"""Uses listify_ticked and select_file to query the session
database. Returns all file information for all files tagged
with tags selected in Properties prefixed with
'Tags to filter'.
"""
if not session:
no_session_warning()
return None
taglist = ... | 5,302,831 |
def _find_and_set_index(data_frame: TfsDataFrame) -> TfsDataFrame:
"""
Looks for a column with a name starting with the index identifier, and sets it as index if found.
The index identifier will be stripped from the column name first.
Args:
data_frame (TfsDataFrame): the ``TfsDataFrame`` to loo... | 5,302,832 |
def default_adv_xxx_bigram_polarity(bigram, negation=None, prior_polarity_score=False, linear_score=None):
"""Calculates the bigram polarity based on a empirical factor from each adverb group
and SENTIWORDNET word polarity
"""
second_word_polarity = word_polarity(bigram['second_word'],
bigram['second_wor... | 5,302,833 |
def extract_entity_text(text: str, offset: int, length: int) -> str:
"""
Get entity value.
:param text: Full message text
:param offset: Entity offset
:param length: Entity length
:return: Returns required part of the text
"""
if sys.maxunicode == 0xFFFF:
return text[offset : of... | 5,302,834 |
def aims_position(ctx):
"""AMIS 仓位"""
pd.set_option('expand_frame_repr', False) # 当列太多时不换行
# connect db
connect_db(ctx.obj['db_u'], ctx.obj['db_p'], ctx.obj['db_h'], DB_POSITION)
connect_db_env(db_name=DB_POSITION)
selling = list(AIMSPosition.objects.aggregate({
'$addFields': {
... | 5,302,835 |
def test_corr_output_without_audio():
"""Ensure running CorrScope with FFmpeg output, with master audio disabled,
does not crash.
"""
cfg = sine440_config()
cfg.master_audio = None
corr = CorrScope(cfg, Arguments(".", [NULL_FFMPEG_OUTPUT]))
# Should not raise exception.
corr.play() | 5,302,836 |
def convert_examples_to_dualfeatures(examples, label_list, max_seq_length, tokenizer, output_mode):
"""Loads a data file into a list of dual input features."""
'''
output_mode: classification or regression
'''
features = []
for (ex_index, example) in enumerate(tqdm(examples)):
if ex_index % 10000 == 0:
logg... | 5,302,837 |
def _configure_lat_type(spec, loader):
""" configures latitude type """
return _configure_geo_type(spec, loader, -90.0, 90.0, '_lat') | 5,302,838 |
def read_csv_input(csv_file, isotopes):
"""
Read the csv input file creating a pandas dataframe
Use the matches from the light, heavy channel or both based on the user preferences
"""
df = pd.read_csv(csv_file)
# Applies the filter of light/heavy ions specified by the user
if isotopes == 'l... | 5,302,839 |
def _mutual_info(lab1, lab2):
"""Call sklearn's mutual info function."""
return mutual_info_score(lab1, lab2) | 5,302,840 |
def test_get_set_window_tile_info(muffin: Muffin, window_id: int):
"""Tests that tile information can be retrieved / assigned to a window."""
tile_info0 = muffin.get_window_tile_info(window=window_id)
assert not tile_info0
desktop = muffin.get_window_desktop(window=window_id)
height = 10
positi... | 5,302,841 |
def decrypt_in_cbc(ciphertext, key=None, IV=None):
""" Arguments must be bytes strings. """
key = key if key else bytes([0] * 16)
IV = IV if IV else bytes([0] * len(key))
block_size = len(key)
block_count = int(len(ciphertext) / block_size)
cipher = AESEncryption(key, 'ECB')
plaintext = b... | 5,302,842 |
def websocket_to_response(response_dict: Dict[str, Any]) -> Response:
"""Converts a WebSocket API response from the rippled server into a Response object.
Args:
response_dict: A dictionary representing the contents of the WebSocket API
response from the rippled server.
Retur... | 5,302,843 |
def rowFeaturise(row, features, timeSeriesName, wavelet, level):
"""
Input:
- row: pandas Series
The row of the features table that is going to be processed.
- features: pandas DataFrame
Table with pointers to JSON files that is going to have new columns with the extracte... | 5,302,844 |
def raise_if_shared_secret_changed():
"""
Raise exception if the consul shared secret changed.
Checks a couple of times over a couple of seconds.
At any positive result this function will assume OK
to dampen ripples in a sufficiently large cluster.
:return None:
"""
if consul_shared_secr... | 5,302,845 |
def q5_plot_chromatic_num_bounds_by_prob(n, prange, pstep, k=None, clique_finder=greedy_find_clique_number):
"""Plots a graph of number of colours against edge probability, for each of the various lower/upper bounds
of chromatic number"""
probs = np.arange(prange[0], prange[1], pstep)
print("generat... | 5,302,846 |
def reconstructTypeFunctionType(typeFunction, args, kwargs):
"""Reconstruct a type from the values returned by 'isTypeFunctionType'"""
#note that our 'key' objects are dict-in-tuple-form, because dicts are
#not hashable. So to keyword-call with them, we have to convert back to a dict...
return typeFunc... | 5,302,847 |
def draw_bounding_box(img, line, color=(255, 0, 0)):
"""
:param line: (xmin, ymin, xmax, ymax)
"""
img = cv2.line(img, (line[0], line[1]), (line[2], line[1]), color)
img = cv2.line(img, (line[2], line[1]), (line[2], line[3]), color)
img = cv2.line(img, (line[2], line[3]), (line[0], line[3]), col... | 5,302,848 |
def flatnonzero(a):
"""Return indices that are non-zero in the flattened version of a.
This is equivalent to a.ravel().nonzero()[0].
Args:
a (cupy.ndarray): input array
Returns:
cupy.ndarray: Output array,
containing the indices of the elements of a.ravel() that are non-zero.
... | 5,302,849 |
def create_optim_modifier_trainable(project_id: str, optim_id: str):
"""
Route for creating a new trainable modifier for a given project optim.
Raises an HTTPNotFoundError if the project or the optim are not found
in the database.
:param project_id: the id of the project to create a trainable modif... | 5,302,850 |
def get_logger(name=None, level=logging.INFO):
"""
Return a logger with the specific name, creating it if necessary.
If no name is specified, return the root logger.
Args:
name (str, optional): logger name. Defaults to None.
Returns:
Logger : the specified logger.
"""
lev... | 5,302,851 |
def get_request_validators(restApiId=None, position=None, limit=None):
"""
Gets the RequestValidators collection of a given RestApi .
See also: AWS API Documentation
:example: response = client.get_request_validators(
restApiId='string',
position='string',
limit=123
... | 5,302,852 |
def find_data_gateway():
"""
Returns 200 or 404, depending on whether the data-gateway is reachable or not
:return: 200 or 404
"""
try:
socket.gethostbyname('data-gateway')
return jsonify('success'), 200
except socket.gaierror as e:
return jsonify(str(e)), 404 | 5,302,853 |
def str_to_dict(
text: str,
/,
*keys: str,
sep: str = ",",
) -> dict[str, str]:
"""
Parameters
----------
text: str
The text which should be split into multiple values.
keys: str
The keys for the values.
sep: str
The separator for the values.
Returns
... | 5,302,854 |
def get_list_control_ranges(data):
"""Build a list of extended regions around given ranges that doesn't overlap with any given range
Parameters
----------
data: `pd.DataFrame()`
Likely coming from pd.DataFrame() it should contain ["chrom", "start", "end", "dna_string", "score", "bound"]
... | 5,302,855 |
def test_disabledimmingresolvestorelay(FW):
"""
When dimming changes to the value 'disallowed' the crownstone must change from
IGBT mode to relay.
"""
print("##### test_disabledimmingresolvestorelay #####")
result = []
for intensity in [0,50,100]:
result += [test_disabledimmingresol... | 5,302,856 |
def test_cidr_validator(section_dict, expected_message):
"""Verify that cidr behaves as expected when parsed in a config file."""
_validate_and_assert_error(DcvSchema(), section_dict, expected_message)
_validate_and_assert_error(SshSchema(), section_dict, expected_message) | 5,302,857 |
def change_password(client: Client, user_id: str, password: str) -> bool:
"""Changes password for child user account
via the `/users/{user_id}/password` endpoint.
:param client: Client object
:param user_id: The ID of the user account
:param password: New password
:return: `True` if succeeded, ... | 5,302,858 |
def keyset():
"""
Creates a set of numeric keys centered around 0
Provides a comparison function based on numeric closeness of the
keys
"""
class KeySet:
extent = 10
def __init__(self):
self.key = "0"
self.all = [self.key]
for i in range(KeyS... | 5,302,859 |
def enable(include_pyrin=True, include_app=True):
"""
enables locale management for the application.
:param bool include_pyrin: specifies that it should extract pyrin localizable
messages. defaults to True if not provided.
:param bool include_app: specifies that it shoul... | 5,302,860 |
def autoencoder(X, X_test, encoding_dim):
"""
Parameters: X: training data, X_test: testing data, encoding_dim: dimension of most hidden layer
Return hidden layer representions of training and testing data.
"""
# this is our input placeholder
input_X = Input(shape=(36,))
encoded = Dense(24, activation='rel... | 5,302,861 |
def add_point(slug):
"""Create a new point based on get parameters."""
try:
timestamp = None
str_timestamp = request.args.get('time', None)
if str_timestamp:
timestamp = datetime.strptime(str_timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
else:
timestamp = datetime.n... | 5,302,862 |
def test_associations():
"""
Tests that check wether the dython associations are still computed as is expected.
"""
# load test data
real_assoc = pd.read_csv(test_data_folder/'real_associations.csv', index_col='Unnamed: 0')
real_assoc_theil = pd.read_csv(test_data_folder/'real_associations_theil... | 5,302,863 |
def init_server() -> None:
"""
Configure logging and log format.
Spin up the server.
"""
# Log format
log_config["formatters"]["access"][
"fmt"
] = "[%(asctime)s.%(msecs)d] | %(levelname)s | [%(name)s:%(filename)s:%(lineno)d] - %(message)s"
log_config["formatters"]["default"][
... | 5,302,864 |
def sp_conv3x3_block(in_channels,
out_channels):
"""
3x3 version of the SuperPointNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return SPConvBlock(... | 5,302,865 |
def get_diagonals_coord(d: int, n: int) -> Generator[Line_coord, None, None]:
"""
get_diagonals_coord(d: int, n: int) ->
Generator[Line_coord, None, None]:
Calculates the d-agonals coordinates of h(d, n).
Parameters
----------
d
The number of dimensions of the hypercube
... | 5,302,866 |
def copy_src():
"""Duplicate src directory to a new but temp directory named 'src_copy'."""
# source and target directories
src_path = "../src/"
target_path = "src_copy"
# make new directory
mkdir_cmd = "mkdir "+target_path
run_shell_cmd(mkdir_cmd)
# copy contents of src directory
... | 5,302,867 |
def correlation(a: np.ndarray, b: np.ndarray, missing: float, method="pearson"):
""" Calculate correlation similarity between two vectors"""
assert a.shape == b.shape
assert method in CORR_METHODS
threshold = a.shape[0] * missing
values = ~np.logical_or(np.isnan(b), np.isnan(a)) # find missing valu... | 5,302,868 |
def mfa_backup_tokens(backup_secret):
""" Writes MFA secrets encrypted with backup_secret and base64 encoded to stdout. """
tokens = []
for token in list_mfa_tokens():
token_data = mfa_read_token(token)
if token_data['token_secret'].startswith("enc--"):
token_data['token_secret']... | 5,302,869 |
def test_output_from(clear_now_and_after):
"""Testing output_from input function"""
clear_now_and_after([f'a_{i}.txt' for i in range(4)])
clear_now_and_after([f'g_{i}.txt' for i in range(4)])
for wf in ("B", "C", "D", "E", "F", "G", "H"):
execute_workflow(
"""\
[A]
... | 5,302,870 |
def handle_get_authentication_users_db(self, handle, connection, match, data, hdr):
"""
GET /authentication/users_db
Get user database on this runtime
Response status code: OK or INTERNAL_ERROR
Response:
{
"policies": {
<policy-id>: policy in JSON format,
...
... | 5,302,871 |
def create_content():
"""
Generate fake content to populate the email with
Generates textual contents that are randomly generated and defined to include 5 random IPs, 5 random URLs,
5 random sha1 hashes, 5 random sha256 hashes, 5 random md5 hashes, 5 random email addresses, 5 random domains
and 100... | 5,302,872 |
def write_tsv(observation_user, observation_item, path):
"""Write a TSV file where every line is a user, item interaction."""
df = pd.DataFrame(data={'user': observation_user, 'item': observation_item})
df.to_csv(path, index=False, header=False, sep='\t') | 5,302,873 |
def Mresnet(**kwargs):
"""Constructs a modified ResNet model.
"""
model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)
return model | 5,302,874 |
def getschemasbyuuid():
"""Get all schemas by uuid.
:rtype: dict
"""
return _REGISTRY.getschemasbyuuid() | 5,302,875 |
async def test2(connection):
""" Get/set of a hash of 100 items (with _asdict) """
d = { str(i):str(i) for i in range(100) }
await connection.delete(['key'])
await connection.hmset('key', d)
result = await connection.hgetall_asdict('key')
assert result == d | 5,302,876 |
def get_dynamic_db_settings(server_root, username, password, dbname, installed_apps):
"""
Get dynamic database settings. Other apps can use this if they want to change
settings
"""
server = get_server_url(server_root, username, password)
database = "%(server)s/%(database)s" % {"server": server... | 5,302,877 |
def calc_fm_3d_by_density(mult_i, den_i, np, volume, moment_2d, phase_3d):
"""
Calculate magnetic structure factor.
[hkl, points, symmetry]
F_M = V_uc / (Ns * Np) mult_i den_i moment_2d[i, s] * phase_3d[hkl, i, s]
V_uc is volume of unit cell
Ns is the number of symmetry elements
Np is the... | 5,302,878 |
def parse_args(apps: str, tables: str) -> t.List[FixtureConfig]:
"""
Works out which apps and tables the user is referring to.
"""
finder = Finder()
app_names = []
if apps == "all":
app_names = finder.get_sorted_app_names()
elif "," in apps:
app_names = apps.split(",")
e... | 5,302,879 |
def insertEntries(db, cursor, entries):
"""
Inserts a batch of entries.
:param entries: List of entry insert SQLs.
"""
# Get the columns to use in the correct order
columns = ", ".join(sorted(DATA_TO_CSV_COLUMN, key = lambda k: DATA_TO_CSV_COLUMN[k]))
# Create the prepared statement
insertSql = "INSERT INTO ho... | 5,302,880 |
def get_randoms(n, m):
"""Create n random integers out of m."""
if n > m:
n = m
res = []
for i in range(n):
while True:
int = randint(0, m - 1)
if not int in res:
res.append(int)
break
return res | 5,302,881 |
def test_monotonic_alignment_decoder():
"""Test for utils.learning_to_emit_decoder."""
with tf.Session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.contrib.rnn.GRUCell(2)
inp = [tf.constant(0.5, shape=[2, 2])] * 2
enc_outputs, enc_state = tf.co... | 5,302,882 |
def install_compiler(spec: str) -> None:
"""Install a compiler based on a spack specification e.g. gcc@9.3.0"""
run_subprocess('spack', 'compiler', 'find')
stdout, _ = run_subprocess('spack', 'compilers')
for line in stdout:
if spec in line:
return # Found the correct compiler!
... | 5,302,883 |
def stree(
source: List[T], func: Union[Func, QueryFunction] = QueryFunction.SUM
) -> AbstractSegmentTree:
"""
Automatically detects the type of input container, and uses the
fastest possible segment tree implementation.
"""
try:
if C_EXTENSIONS and isinstance(func, QueryFunction):
... | 5,302,884 |
def test_user_insert_many_valid_records(sqlite_conn):
"""Test validating we can insert many valid records into our 'users' table"""
cursor = sqlite_conn.cursor()
input_records = [
('USER1', 20210101, 20210101),
('USER2', 20210102, 20210102),
('USER3', 20210103, 20210103)
]
c... | 5,302,885 |
def deprecated(func):
"""
This function is a decorator, which diplays a deprecation warning.
"""
@wraps(func)
def __inner(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn("{}".format(func.__name__), DeprecationWarning, stacklevel=2)
warnings... | 5,302,886 |
def gobuster_no_port(ip_address, url, wordlist, https, output):
"""
This function is to check for port 80 and 443 if it is open if it is so then it will do gobuster on that specific
port with the choose of the user wordlist.
:param ip_address: the ip of the target
:param url: http or https
:para... | 5,302,887 |
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) co... | 5,302,888 |
def radial_histogram(r, weights=None, nbins=1000):
""" Performs histogramming of the varibale r using non-equally space bins """
r2 = r*r
dr2 = (max(r2)-min(r2))/(nbins-2);
r2_edges = np.linspace(min(r2), max(r2) + 0.5*dr2, nbins);
dr2 = r2_edges[1]-r2_edges[0]
edges = np.sqrt(r2_edges)
... | 5,302,889 |
def dict_to_function(arg_dict):
"""
We need functions for Tensorflow ops, so we will use this function
to dynamically create functions from dictionaries.
"""
def inner_function(lookup, **inner_dict):
return inner_dict[lookup]
new_function = functools.partial(inner_function, **arg_dict)... | 5,302,890 |
def send_notification():
"""
Send adaptive card notification in webex teams to all employees
"""
for e in get_employees():
to = e["email"]
print(to)
api.messages.create(
toPersonEmail=to,
text="Card Message: If you see this your client cannot render cards"... | 5,302,891 |
def resreid_train(images, num_class=751, trainable=True):
"""use resnet50 as backbone, modify the stride of last layer to be 1 for rich person features """
with flow.scope.namespace("base"):
stem = layer0(images, trainable=trainable)
body = resnet_conv_x_body(stem, lambda x: x, trainable=trainab... | 5,302,892 |
def main(args):
"""
This sets up dummy SWF activity data, creates an instance of this activity and runs it only for
testing and debugging. This activity would usually be executed by worker.py
"""
data = {
'id': '00353',
'expanded_folder': '00353.1/9a0f0b0d-1f0b-47c8-88ef-050bd9cdff... | 5,302,893 |
def ambient(*args):
"""Ambient reflection material properties."""
color = _getColor(*args)
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (ctypes.c_float * 4)(*color)) | 5,302,894 |
def _g(rd):
""" See page 3 at http://www.glicko.net/glicko/glicko.pdf """
return 1 / math.sqrt(1 + 3 * (Q ** 2) * (rd ** 2) / (math.pi ** 2)) | 5,302,895 |
def ecdh_reply(p,g,ag):
"""
Generates a random integer b, then computes the shared secred ab*g.
Input:
p A prime number
g An ECPt
ag An ECPt multiple of g
Output:
A tuple (int, ECPt, ECPt) = (b, b*g, ab*g).
Remarks:
This routine... | 5,302,896 |
def get_instance(context, pvm_uuid):
"""Get an instance, if there is one, that corresponds to the PVM UUID
Not finding the instance can be a pretty normal case when handling events.
Don't log exceptions for those cases.
:param pvm_uuid: PowerVM UUID
:return: OpenStack instance or None
"""
... | 5,302,897 |
def f(x, y):
"""
Args:
x
y (int)
""" | 5,302,898 |
def make_background_image():
"""Estimate background image.
See the `KernelBackgroundEstimator` tutorial and
documentation how it works, or the SciNeGHe 2014 proceeding
by Ellis Owen et al.
"""
radius = Angle(0.2, 'deg')
r_in = Angle(0.3, 'deg')
r_out = Angle(0.7, 'deg')
significance... | 5,302,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.