content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import gzip
import shutil
def compress_manpage(file_to_compress) -> str:
""" Compress given manpage to a .gz file.
Resulting compressed file will be located at the same folder than file_to_compress.
:param file_to_compress: Manpage file to compress.
:return: Resulting compressed file pathn... | 48d0c9c39d69b4c98653a9732a203d7a56a4bd04 | 660,843 |
def bin(s, m=1):
"""Converts the number s into its binary representation (as a string)"""
return str(m*s) if s<=1 else bin(s>>1, m) + str(m*(s&1)) | deed2c5bf2f50302a53df1f01502524894f8b928 | 660,844 |
def icumsaColour (solution_concentration, absorbance_420nm, optical_length):
"""
Function to calculate the ICUMSA colour of the sucrose
"""
ICUMSA_colour = (absorbance_420nm * 1000) / ((solution_concentration / 100) * optical_length)
return ICUMSA_colour | bdd06e290de3274732d81fb6e0757237d7316ddd | 660,845 |
from typing import OrderedDict
def get_des_vars_and_qois(discipline):
"""Method to get the relevant design variables and quantities of interest for a specific subsystem.
:param discipline: name of the discipline (structures, aerodynamics, propulsion)
:type discipline: basestring
:return: ordered dict... | 7c9c8da90ef64e590c317aa422e2f6175520d4a4 | 660,846 |
import uuid
def make_uuid():
""" A utility to generate universally unique ids.
"""
return str(uuid.uuid4()) | 3c232eda508231482e7ffda778510613dc609c4a | 660,847 |
def this_filename():
"""
prints the name of this file
Returns:
filepath: str
absolute path to file
Dependencies:
import os
"""
filename = __file__
return filename | 0bb4e78a0cfa1149834f1ae4f0276a309c060e0a | 660,848 |
def defensive2(user_answer):
"""Makes sure the user input is correct and provieds user friendliness"""
if user_answer != 'Y' and user_answer != 'N':
while True:
user_answer = input("Invalid input!!!\nDo you want to ask another "
"Question? (Y\\N): ")
... | b0d6e992263139ab9e75267dcaaf144130d9893f | 660,849 |
def max_length(tensor):
"""Function that returns the maximum length of any element in a given tensor"""
return max(len(tensor_unit) for tensor_unit in tensor) | 4a41aae65f3cb3955b3a00d7b208499ab17b18eb | 660,850 |
import os
def output_file(ppt_path):
""" 输出图片路径 """
file_name = os.path.basename(ppt_path) # 获取文件名字
if file_name.endswith(('ppt', 'pptx')):
exec_path = os.path.abspath(os.path.dirname(__file__)) # 当前脚本路径
name = file_name.split('.')[0] # 去除后缀,获取名字
image_dir_path = os.path.join(ex... | 6a810e1b7555eed7ddb72fdb38bb961b3b8c379b | 660,851 |
def parse_production_company(movie):
"""
Convert production companies to a dictionnary for dataframe.
Keeping only 3 production companies.
:param movie: movie dictionnary
:return: well-formated dictionnary with production companies
"""
parsed_production_co = {}
top_k = 3
productio... | 67ccdf149ba67cebcfba824a6108edf1b2349d1d | 660,852 |
import numbers
def _multimetric_score(estimator, X_test, y_test, scorers, indices=None):
"""Return a dict of score for multimetric scoring"""
scores = {}
for name, scorer in scorers.items():
if y_test is None:
score = scorer(estimator, X_test)
# **PATCH**
elif indices i... | 53033464db07ba2dedd00b44c17ded044c35216d | 660,853 |
def extract_pheno_beta_df_from_pickle_dict(input_dict, disease=''):
"""Return phenotype and beta dataframes from specified dictionary storing MethylationArray python dictionary.
Parameters
----------
input_dict
Python disctionary storing pheno/beta information.
"""
if disease:
r... | 4766f6e3835b06b1d8df54bdfaef06bccaf5e492 | 660,854 |
def get_lambda_tags(function_name):
"""
Get all tags and values associated with the specified function name.
"""
return { } | 2dd2c84020abb80a43ecce7a5544740756bec30c | 660,855 |
from typing import Callable
from typing import ContextManager
import importlib
import contextlib
def lazy_load(
module: str,
attr: str
) -> Callable[..., ContextManager]:
""" Lazy load a context manager from module, return `contextlib.suppress` (no-op) if loading failed
:param module: Module... | 0117b921a3de15d9a1b3fba80b20d0d1a48d36ad | 660,856 |
def bytearray_builtin():
"""bytearray: Mutable bytes array."""
data = bytearray(b"plain\0ext")
data[5] = ord('t')
return data.decode() | e18c38f0e0a7b344cc4c3095cac3ad3c01719aa9 | 660,857 |
def one_trajectory_vehicle_data():
""" One trajectory vehicle data """
return (
{
"abscissa": 25.0,
"acceleration": 0.0,
"distance": 25.0,
"driven": False,
"elevation": 0.0,
"lane": 1,
"link": "Zone_001",
"or... | 3376515494d549167a40192ae17f6f6203b4aba6 | 660,858 |
def compare_version(a, b):
"""
Compare two version strings
:param a: str
:param b: str
:return: -1 / 0 / 1
"""
def _range(q):
"""
Convert a version string to array of integers:
"1.2.3" -> [1, 2, 3]
:param q: str
:return: List[int]
"""
... | 36e1cb021709c9cc694a36e86967e97d3c7a2ede | 660,859 |
def setLastRun(obj):
"""(Integration only)
Stores given object in the LastRun object
:type obj: ``dict``
:param obj: The object to store
:return: No data returned
:rtype: ``None``
"""
return None | 3519c83e09c76fcceb1c9949069edaa7449b6007 | 660,860 |
def create_quarterly_schedule_details(api, api_exception, day):
""" Creates a ScheduleDetails object for use with a scheduled task for quarterly execution (every 3 months).
:param api: The Deep Security API modules.
:param api_exception: The Deep Security API exception module.
:param day: The day of th... | 5f78608cb4289370222065dd21ab387d42cb074c | 660,861 |
def get_all_attributes(something):
"""获取类下的所有属性和方法
"""
return {
name: getattr(something, name)
for name in dir(something) if name[0] != '_'
} | 7e6f6ea6130afd1421efc484a6553a07ba6a92d9 | 660,862 |
def getNumOrRowsForGrid(num_of_cols_for_rgb_grid, rgb_list):
"""
This is to get a number of rows using a predetermined number of columns.
This is to ensure that the images form a grid, so that multiple rgb images can be viewed at once.
Args:
num_of_cols_for_rgb_grid(integer): The number of co... | c7b0f8b9c3c6df5bccdd852edf780ee8976bea49 | 660,863 |
def is_redirection(status):
"""
检查状态码是否重定向
:param:
* status: http 状态码
:return:
* result: True or False
"""
return 300 <= status <= 399 | 170bf1f0a723816a94be8f89097598a20f1a357a | 660,865 |
def corrL(s):
""" Compute the correlator for this pattern:
↑ ↓
↑ ↑
and symmetry-equivalent patterns
"""
res = 0.0
L = s.shape[-1]
for i in range(L-1):
for j in range(L-1):
res += s[0, i, j] * s[1, i+1, j] * s[1, i, j+1] * s[1, i+1, j+1]
... | cdbf81c3b8a06c50cc9847d1474d926933ac5c23 | 660,866 |
def dashed(word):
"""
This function will turn the character of random word into dash
:param word: str, random word given by the program that have to be guessed by the user
:return: ans(called as old_ans in the program), str, dashed word
"""
ans = ''
for ch in word:
if ch.isalpha():
... | 488a7151b322bcc6cbca5c98a0900c27eea2ad7f | 660,867 |
import json
import sys
def parse_libs():
"""Make libraries list from version.json file"""
_ = []
try:
with open("./version.json", "r", encoding="utf-8") as f:
file_data = json.loads(f.read())
for lib in file_data["libraries"]:
_.append(lib["downloads"]["a... | 796df4da7c0161ae94bfc943838a3e58499acd36 | 660,868 |
def do_nothing(df, inputs):
"""
Does absolutely nothing.
"""
return df | b86cbde1d31d865a1bbaa2fe94432c650aa72e3c | 660,869 |
import re
def _transform_sweep_str(data, parameters):
"""Replace string placeholders with parametric sweep values.
:param str data: The string containing placeholders.
:param list parameters: The sweep values, each value maps
to one of {0}, {1}, .. {n} by index.
"""
# Handle {n} or {n:m} scen... | 3551b469e4a634fdd0351af29f226b14c939eae8 | 660,870 |
def notas(* aluno, sit=False):
"""
:param aluno: Reune as notas dos alunos da classe
:param sit: serve para mostrar se a média da classe ta aprovada ou reprovada
:return: um dicionário com a maior nota, menor nota e a média, e o parâmetro opcional de situação.
"""
maior = menor = soma = 0
fo... | 9547484452461b6a22f777d5280de5e52a461eee | 660,871 |
def wagtail_icon(name=None, classname='', title=None):
"""
Usage: {% wagtail_icon name="cogs" classname="icon--red" title="Settings" %}
First load the tags with {% load wagtailui_tags %}
"""
return {
'name': name,
'classname': classname,
'title': title,
} | 9a0717c3acf6736a4c5852e39a660dfd84b8b167 | 660,872 |
def bfs_path(ADT,start,end):
"""Breadth First Search to find the path from start to end"""
#create a queue with rule of first-in-first-out
queue=[]
queue.append(start)
#pred keeps track of how we get to the current vertex
pred={}
while queue:
#keep tra... | dd4bd96d879a49872e974d4b0fd619b6fbda264a | 660,873 |
def safe_text_gen(model, inputs):
"""A wrapper for model.generate_text() . Makes the output be always in the same format - a list of strings.
The func is necessary because of a quirk of the BIG-bench API:
if the input to model.generate() is a list of len 1, it will return a string, and not a list of string... | 4d0ec52cb31790b5f9232ee2a888ed37ddd05359 | 660,874 |
import torch
def NLLLoss(inputs, targets, device = 'cpu'):
"""
Custom Negative Log Likelihood loss that returns loss per example,
rather than for the entire batch.
Args:
inputs : (batch_size, num_classes) *Log probabilities of each class*
targets: (batch_size) *Tar... | 1d1decf83fa5736b6806d2160f63353617e1b0ca | 660,875 |
def digits(n, base, alphabet=None, pad=0, big_endian=True):
"""
Returns `n` as a sequence of indexes into an alphabet.
Parameters
----------
n : int
The number to convert into a sequence of indexes.
base : int
The desired base of the sequence representation. The base must be
... | ab0c8f560359b903f7853a225c0a7d5256f86c7a | 660,877 |
def version_param(params):
"""Return the value of the HTTP version parameter, or `None` if no
version parameter is supplied.
"""
for k, v in params.items():
if k.lower() == "version":
return v | 61348b87007c253dc6533827de4d8f302779f107 | 660,879 |
def scale_image(arr):
"""
scale_image(arr)
- scales numerical values from scale 0-255 for like an image
- have tried, regular normal/ min-max scaler -> does not work well
"""
## Normal
#arr=(arr-np.mean(arr))/np.std(arr)
## Min-Max
# min_val=arr.min()
# max_val=arr.max()
... | 287fe9483b0ba19c288d7c534238d2f6d53db105 | 660,880 |
import re
def _parse_item(line):
"""For lines like:
- Blah minor
returns tuple (True, 3, 'Blah minor')
for others - (False, 0, None)
"""
match = re.search(r'^[ ]*[*-][ ]+', line)
if match is not None:
ident = len(match.group(0))
return (True, ident, line[ident:])
ret... | 55a74babfc8fe2cf42977d50154a57c36ea45fc0 | 660,881 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Manually check an argument',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-v',
'--val',
help='In... | b833ca1fc7b894d7f7bf80bfaaa0d8850fa7072e | 660,883 |
def get_githost(host: str="github.com") -> str:
"""Returns the git host for GitHub, GitLab, BitBucket.
Parameters:
host (str): {("gh", "github", "github.com"),
("gl", "gitlab", "gitlab.com"),
("bb", "bitbucket", "bitbucket.org")}.
(defa... | 58416910385ad3ee21dcad5e579cf78e94df3b0b | 660,884 |
def add_header(response):
"""
Disables caching for each flair app that uses PyWebView
"""
response.headers['Cache-Control'] = 'no-store'
return response | 23fd006383e311e8c979bfb2cf99566c5ecddb01 | 660,886 |
def fs_state(self):
"""
Запрос статуса ФН.
"""
return self.protocol.command(
0xFF01,
self.admin_password
) | 73c1914bc6e579b020bf98ce2c3cb62ac7559a10 | 660,887 |
import yaml
def parse_ic(fname):
"""Parse the Nalu yaml input file for the initial conditions"""
with open(fname, "r") as stream:
try:
dat = yaml.full_load(stream)
u0 = float(
dat["realms"][0]["initial_conditions"][0]["value"]["velocity"][0]
)
... | 8e7b78a5b54f1fedc4ee4d598c8400fe49791b2e | 660,888 |
from typing import Dict
def format_location_name(location: Dict):
"""Returns a string with a combination of venue name, city
and state, depending on what information is available"""
if not location:
return None
if "venue" not in location and "city" not in location and "state" not in location... | 192542c15c17dde10feb9f8c0b6ec4a1fa65e991 | 660,889 |
def build_files_option(cfg):
"""
builds the "-files" option that is passed as part of the job step
- a comma separated string of files to be copied to each node when the step is executed
- the config object is updated with details of all files and the subset of additional files
:param cfg: the Confi... | 144c6870cd83d7913753a84874478ee0be9babb5 | 660,890 |
def move_telescope_south():
"""Return Lx200 protocol command for "move_telescope_south".
"""
command = b'#:Ms#'
return command | 89990b98a10c6d902043834f48a9efdbd1e6d37f | 660,891 |
def get(iterable, index=None, default=None):
""" Get value of an iterable by index, mainly lists, tuples and sets that don't have a `get` method, works for dict too.
Returns first random value if set, returns default value if not found. """
if isinstance(iterable, set):
try:
return n... | 9e767e454e65c751dbb298b00cd875842026615d | 660,892 |
import os
def getListOfFiles(dirName):
"""Returns single list of the filepath of each of the training image files"""
# source: https://thispointer.com/python-how-to-get-list-of-files-in-directory-and-sub-directories/
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries... | 900d18044a34a1b809d50a795fa58c56f1144d8b | 660,894 |
def mean_of_first_n_matches(df, var, n):
"""Computes for each player the mean of variable var for the first n matches and returns means as a list"""
players = df.groupby('account_id', sort=False)
means = players.apply(lambda x: x[var].head(n).mean()).tolist()
return means | 9c55093338f0c7ff7c08ee5a0c88bea7a99acd78 | 660,895 |
def ConstrainLattice(lattice_class, cell):
"""Constrain cell to fit lattice class x."""
a, b, c, alpha, beta, gamma = cell
if lattice_class == "a":
return (a, b, c, alpha, beta, gamma)
elif lattice_class == "m":
return (a, b, c, 90.0, beta, 90.0)
elif lattice_class == "o":
... | 31338d2901d9a2c025b8d04a61d6f277667d7586 | 660,897 |
import itertools
def possible_pairs(s, mirrors=True):
"""Return possible pairs from a set of values.
Assume `s = ['a', 'b']`. Then return examples for the following calls are:
* `possible_pairs(s)` returns `[('a', 'b'), ('b', 'a')]`
* `possible_pairs(s, mirros=False)` returns `[('a', 'b')]`
... | 146f006f4d9cf7546383319ba30fa4051916a26c | 660,898 |
def read_token_file(filename):
"""
Read a token file and return the oauth token and oauth token secret.
"""
with open(filename) as f:
return f.readline().strip(), f.readline().strip() | 92d73e88dda883712b9bc2f5e1700bc003c1a181 | 660,900 |
import os
def file_exist(files,log):
"""Verify that file exist."""
for file in files:
if not os.path.isfile(file):
log.warning("\n{} file not found".format(file))
return 1
return 0 | acedd2c180865616a3ab9ae4f64213e7b336d880 | 660,901 |
def retime(g, r):
"""
Compute the retimed graph.
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param r: The retiming function :math:`r: V \mapsto Z` to be applied.
:return: The retimed graph.
"""
gr = g.copy()
for e in gr.edges:
gr.edges[e]['weight'] =... | 5a86807d572fefa692c990e38d4b379d7486f42e | 660,902 |
def compute_mallows_insertion_distribution(length, phi):
"""
Helper function for the mallows distro above.
For Phi and a given number of candidates, compute the
insertion probability vectors.
Method mostly implemented from Lu, Tyler, and Craig Boutilier.
"Learning Mallows models with pairwise preferences.... | 7d670ba7fe520032876e9a3e62c16bb753613e6f | 660,903 |
def string_to_int(value):
"""Converts a string to an integer
Args:
value(str): string to convert
Return:
The integer representation of the nummber. Fractions are truncated. Invalid values return None
"""
ival = None
try:
ival = float(value)
ival = int(ival)
e... | d9b251be776d721d25ec35bf7fa558e4e3b68f00 | 660,904 |
import time
def print_checkpoint(
n_frame: int, start_ind: int, end_time: float, sample_save: int = 100
) -> float:
"""Print checkpoint messages indicating frame and fps for inference.
Args:
n_frame (int): Frame number
start_ind (int): Start index
end_time (float): Timing refe... | 5d0d29ec245967c71a74f35629cd604fefb78d79 | 660,906 |
def find_cell (nb, cell_name):
"""
find a named cell within a notebook
"""
for cell in nb.cells:
if ("name" in cell.metadata) and (cell.metadata["name"] == cell_name):
return nb.cells.index(cell), cell
return None, None | ac0e275ce44949086b8b59b0f6b961a2a239342b | 660,908 |
from functools import reduce
def convex_hull(points):
""" Returns points on convex hull in counterclockwise order according to Graham's scan algorithm.
Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8
.. note:: This implementation only works in 2-dimensional space.
:para... | a53a23aa27339968c957fba2f3dd975dcfad18de | 660,909 |
def prod_in_offsets(
backend, offsets, content, mask_rows=None, mask_content=None, dtype=None
):
"""Summary
>>> j = awkward.fromiter([[1.0, 2.0],[3.0, 4.0, 5.0], [6.0, 7.0], [8.0]])
>>> mr = numpy.array([True, True, True, False]) # Disable the last event ([8.0])
>>> mc = numpy.array([True, True, Tr... | 1b8d4f6d3320c0313a385e1503668026fb9734a8 | 660,910 |
from typing import OrderedDict
def skip_nan_tracks(tracks):
"""Filter tracks
Args:
tracks: dictionary or OrderedDict of arrays with ndim >=2 and same second dimension
Returns:
OrderedDict of tracks
"""
if tracks is None:
return tracks
if isinstance(tracks, OrderedDict):
... | 0bfbdccf20ce7f3d4c90391bb13af0dfe3934a5f | 660,911 |
def key_scope(request):
"""scope of the rate_limit 'key scope' can be either 'service' or 'global'"""
return request.param | 4d7b847b7f9ee62e539ab0bc47be8dd3bb099f66 | 660,912 |
import os
def postgres_credentials():
"""Retrieve the postgres credentials"""
env_vars = ["PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD"]
for var in env_vars:
if not os.getenv(var):
raise Exception(
f"Missing env var: {var}. Please look at the .env.example or... | f7115ab1adbc250a9210cf8335b963a23f0a155f | 660,913 |
def delete_file_nokia_sros(ssh_conn, dest_file_system, dest_file):
"""Delete a remote file for a Nokia SR OS device."""
full_file_name = "{}/{}".format(dest_file_system, dest_file)
cmd = "file delete {} force".format(full_file_name)
cmd_prefix = ""
if "@" in ssh_conn.base_prompt:
cmd_prefix ... | ef7a5152ed01640782b30a3509df5d8a9a7cfacf | 660,914 |
def winCheck(board, marker):
"""
Check if someone win
"""
# check lignes
return((board[1] == board[2] == board[3] == marker) or
(board[4] == board[5] == board[6] == marker) or
(board[7] == board[8] == board[9] == marker) or
# check cols
(board[1] == board[4] == board[7] == marker) o... | 756808d5836d38b9d69d852db09ef36dfd767b99 | 660,915 |
import numpy
def BMEOSfitpoly(volumes, energies):
"""Fit energies and volumes to the Birch-Murnaghan equation of state.
Determine:
- total energy at min (E0)
- equilibrium volume (V0) corresponding to E0
- bulk modulus (B0)
- pressure derivative of the bulk modulus (B01)
- residuals from t... | e857084e7662b28e26a9550d28d31b797df8c9be | 660,916 |
from typing import Dict
import math
def length_of_ray_until_intersect(theta: float, line: Dict[str, float]) -> float:
"""Length of ray until intersect."""
return line['intercept'] / (math.sin(theta) - line['slope'] * math.cos(theta)) | 508a375e7ab2f935cc812ec8a8305429d5f85d55 | 660,917 |
def list_to_dict(l):
"""Convert list to dict."""
return {k: v for k, v in (x.split("=") for x in l)} | f806e238f73d6874f8e657c2b87aeb8cd6e44688 | 660,918 |
from datetime import datetime
def pretty_date(date):
"""
*convert date to a relative datetime (e.g. +15m, +2hr, +1w)*
**Key Arguments:**
- ``date`` -- absolute date
**Return:**
- a relative date
"""
################ > IMPORTS ################
################ > VARIABLE ... | b238db25f813ddb110558578d15715cbf5fd87cf | 660,919 |
def filter_credit_score(credit_score, bank_list):
"""Filters the bank list by the mininim allowed credit score set by the bank.
Args:
credit_score (int): The applicant's credit score.
bank_list (list of lists): The available bank loans.
Returns:
A list of qualifying bank loans.
... | 6409756449257b78f78102bb0c15e6460227ae1a | 660,920 |
def sql_compile(dialect, statement, incl_literal_binds=True):
"""Compile a statement for the given dialect."""
return statement.compile(
dialect=dialect,
compile_kwargs={'literal_binds': True} if incl_literal_binds else {}
) | 81a538ede7ffa10b99cd4ceacd520d932196564d | 660,921 |
import requests
from bs4 import BeautifulSoup
def get_political_party(name):
""" Scrapes Wikipedia for the political party of the given person, defaults Independent politicians to their last mainstream political party
Args:
name (string): The name of a politician
Returns:
party (... | bffb955d4f4d678a2a6bb0aad53aa1aace08386f | 660,922 |
def is_string(s):
"""Check if the argument is a string."""
return isinstance(s, str) | 050be89ec88be7a6067464d4ad846acbf560d119 | 660,923 |
import threading
def current_threads_names() -> list[str]:
"""Отдает список имен запущенных потоков."""
return [
thread.name
for thread in threading.enumerate()
] | c3d9c6af072237f225afd1eed51a17d106af9c2a | 660,924 |
def createMutableSerializer(BaseSerializer):
"""
# A MutableSerializer is a generic ModelSerializer that inherits from
# a given BaseSerializer, and allows it to limit the fields that are
# to be serialized.
"""
class MutableSerializer(BaseSerializer):
def __init__(self, *ar... | 404c6471447bbe32e9b2cf9f814916b823840e5f | 660,925 |
from typing import Dict
from typing import Any
def ot3_only(ot3_default: Dict[str, Any]) -> Dict[str, Any]:
"""Structure of SystemConfigurationModel with OT-3 only."""
return {"robot": ot3_default} | 2248f43ddd3434417fb4f1d6f81c04e616014119 | 660,927 |
def find(predicate, iterable, default=None):
"""Return the first item matching `predicate` in `iterable`, or `default` if no match.
If you need all matching items, just use the builtin `filter` or a comprehension;
this is a convenience utility to get the first match only.
"""
return next(filter(pre... | 70d0d4265d7ef70e3ff041794712990b2dfc10c6 | 660,928 |
def parse_request(message):
"""
Accept request from client.
Verify content and return appropriate error or URI.
"""
request_parts = message.split()
if len(request_parts) <= 4:
raise ValueError('400 Bad Request')
if request_parts[0] == 'GET':
if request_parts[2] == 'HTTP/1.1'... | 3bd62a335c87ecaec8c97d483d3e845310aca649 | 660,929 |
def check_image_counter(name):
"""
Note: This method is only ever entered if there actually is a name as well
as there will never be a .fits at the end.
Pre: Takes in an image name as a string and sees if the standard iterator
is on the end of the image name.
Post: Returns a boolean of whether t... | 32ed2eb702009694c9d9b8dd0a6a7f9eeea18881 | 660,930 |
def check_sql(sqlContent):
"""针对多行情况检测sql语句"""
if sqlContent:
return sqlContent.rstrip().endswith(';')
return False | c1bf338ab257e6ea7ced74d89069c1fa253f433e | 660,931 |
def truncate_string(string, length=80, title=True):
"""
Returns a truncated string with '..' at the end if it is longer than the length parameter.
If the title param is true a span with the original string as title (for mouse over) is added.
"""
if string is None:
return '' # pragma: no cov... | 9eaf25dcac23f1bd3c8839e8389e98e598e2b402 | 660,932 |
def accel_set_module(client, module):
"""Set the module for the acceleration framework.
Args:
pmd: 0 = auto-select, 1 = Software, 2 = CBDMA
"""
params = {'module': module}
return client.call('accel_set_module', params) | c99175a2be508e2ae2b9b4d55379cc864bb0909e | 660,933 |
import math
def quicknxs_scaling_factor(ws):
""" FOR COMPATIBILITY WITH QUICKNXS """
run_object = ws.getRun()
peak_min = run_object.getProperty("scatt_peak_min").value
peak_max = run_object.getProperty("scatt_peak_max").value + 1.0
low_res_min = run_object.getProperty("scatt_low_res_min").value
... | 0a71bd0f5626ccf555182ff5c96ea1a0d699e2da | 660,934 |
from typing import List
def get_sentence_segments(words: List[str]):
"""
returns a list of indexes indicating for each word in which sentence it is.
Sentences are determined by '.' tokens. This is a hack, but will do for initial results
"""
segments = []
current_segment = 0
for word in wor... | e357f8abd9d7fe8e74b43414a20048fc50db4448 | 660,935 |
def get_bias_variance(generator, fitter, threshold):
"""Helpful for running experiments
"""
N = generator.N
M = generator.M
generator.get_data()
fitter.get_data()
df = fitter.evaluate(threshold=threshold)
df["Generating_Function"] = generator.model_name
df.drop(columns="Generating Fu... | 7e7aea053508b489b4dfc1bf91c98a382622ba3c | 660,936 |
def gen_data_dict(data, columns):
"""Fill expected data tuple based on columns list
"""
return tuple(data.get(attr, '') for attr in columns) | b43e29a4365a9d9e418aeb7dfe2a3452fbe173d3 | 660,937 |
def validToken(token):
"""
Return True if token is in hex and is 64 characters long, False
otherwise
"""
if len(token) != 64:
return False
try:
token.decode("hex")
except TypeError:
return False
return True | 1fa264acc43dd67ba400ddb50ccf3aaa04f33300 | 660,938 |
def ip_to_num(ip):
"""
Convert an IP string to a number value.
:param ip: IP string to convert
:return: A number representation of the IP address
"""
s = ip[0].split(".")
return int(s[0]) << 24 | int(s[1]) << 16 | int(s[2]) << 8 | int(s[3]) | 1a0136146064c4fc587c51d5d46ec9a47874cc80 | 660,939 |
from pathlib import Path
def get_package_list():
"""Return the list of packages to download/install from the requirements file"""
req_file = Path("../../requirements.txt")
if not req_file.exists():
print(
"run pip-compile first to create a requirements.txt file [pip install pip-tools t... | c998660fdf75bbe92fd7145eae7a5d76da1345a4 | 660,942 |
import os
import pathlib
def get_filename(pth: os.PathLike[str]) -> str:
"""
Convert image path to file name.
:param pth: Absolute path to Image.
:return: Image name with file extension.
"""
file_pth = pathlib.Path
file_pth = pathlib.Path(pth)
return file_pth.name | 65b36e97c651adfc8a71c845528ea44d6289029d | 660,943 |
def count_stats_old(m1, m2, filter_fun):
""" Old function that also compares containment using the names of the methods in the graph.
Not currently used.
"""
res = {}
tot = 0
mins = None
maxs = None
for (g1,pglist) in m1.iteritems():
for pg in pglist:
if not filter... | 4f81c63b897a2bb10b0aa5ef0032f444a1523b5d | 660,944 |
def strip_rule(line):
"""
Sanitize a rule string provided before writing it to the output hosts file.
Some sources put comments around their rules, for accuracy we need
to strip them the comments are preserved in the output hosts file.
Parameters
----------
line : str
The rule prov... | 788bb56aa566bc6089e70fe40aeac4a39aac70ed | 660,945 |
import argparse
def parse_args():
"""Parameters"""
parser = argparse.ArgumentParser('training')
# parser.add_argument('-d', '--data_path', default='data/modelnet40_normal_resampled/', type=str)
parser.add_argument('-c', '--checkpoint', type=str, metavar='PATH',
default="/Users/... | 7a1008865770f4872b1d33e761db68d7246814ee | 660,946 |
def get_key(dictionary, field):
"""Gets an key of an dictionary dynamically from a name"""
return dictionary[field] | 1690b657738a722f4028ea393e9e863eb430e54d | 660,947 |
import os
import sys
def api_path() -> str:
"""
This function returns a string to the EnergyPlus dynamic library. The energyplusapi target in the build system
depends on the Python API build script, so you shouldn't be able to generate the EnergyPlus dynamic library without
these scripts being succes... | d07ce689996e7b90f26c31c230cf8db18c96b4b6 | 660,948 |
def _encode_time(frac):
"""Encode :class:`~schedsi.cpu.time.Time`."""
return {'numerator': int(frac.numerator), 'denominator': int(frac.denominator)} | 92df57549910b7fb5cbcaffd9880a7093262b425 | 660,949 |
import re
def parse_pi(pi, pis):
""" Add a processing instruction to the current state
Will also return the dictionary containing the added instructions
for use in things like ?include instructions
"""
if pi.text:
# Split text in the format 'key="val"'
chunks = re.split(r... | 90618b6e9b776d1d75748ceba801dbb6d70379ca | 660,950 |
import math
def calculate_sum(*pairs):
"""
Computes a derived estimate and its MOE for the aggregation of all
the arguments.
Args:
pairs (list): a list of two-item sequences with a U.S. Census bureau
count estimate and its margin of error.
Returns:
A two-item sequence... | afe05bac060fa61f7d31aa19297af2e48362603d | 660,952 |
def val(section, key):
""" Return value of section[key] in units specified in configspec
Args:
section (:class:`qcobj.qconfigobj.QConfigObj`.Section`): instance
key (string): valid key for `section`
Returns:
values in section[key] converted to units defined in c... | 5b28d7ba9d1abcf42eecaa1af0a3b13f03dd44e6 | 660,953 |
def find_neighbours(value, df):
"""Returns the index in an array which meet the condition that it is close to a certain value.
Parameters
----------
value : float
Float that includes the current step for searching the y-values of the posterior distribution for the uncertainty interval.
df :... | a6614bade8caaebc6d2649bf09eddd8ef7968971 | 660,954 |
from io import StringIO
def print_elastic_ips(ec2, region):
"""
Print a list of UN-attached Elastic IP addresses
:param ec2: The boto3 ec2 client
:param region: The region to search in
:return: The nicely formatted list of EIPs to print
"""
addresses_dict = ec2.describe_addresses()
fo... | 771e9d074472b71aa310ad3ad20b76f57559020f | 660,955 |
def _get_spm_os(swift_os):
"""Maps the Bazel OS value to a suitable SPM OS value.
Args:
bzl_os: A `string` representing the Bazel OS value.
Returns:
A `string` representing the SPM OS value.
"""
# No mapping at this time.
return swift_os | fc59e46304598540b1112f57ef21d05e92668019 | 660,956 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.