content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_charges_single_serial(path_to_cif, create_cif=False, path_to_output_dir='.', add_string='_charged',
use_default_model=True, path_to_pickle_obj='dummy_string'):
""" Description
Computes the partial charges for a single CIF file and returns an ASE atoms object updated with the e... | 5,330,900 |
def matchlist(page=1):
"""Respond with view for paginated match list."""
query = Match.query.order_by(Match.id.desc())
paginatedMatches = query.paginate(page, current_app.config['MATCHES_PER_PAGE'], False)
return render_template('matchlist.html', matches=paginatedMatches.items, pagination=paginatedMatch... | 5,330,901 |
def post_page_files(current_user, pid):
""" Изменение файлов страницы"""
try:
page = SitePages.query.get(pid)
if request.files.getlist('file[]'):
page_files = request.files.getlist('file[]')
na_files = []
for pfile in page_files:
fsize_b = ge... | 5,330,902 |
def get_data(filename: str) -> pd.DataFrame:
""" Create a dataframe out of south_sudan_data.csv """
df = pd.read_csv(filename)
return df | 5,330,903 |
def train(
net: Net,
trainset: Fer2013Dataset,
testset: Fer2013Dataset,
pretrained_model: dict={}):
"""Main training loop and optimization setup."""
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=32, shuffle=True)
criterion = nn.CrossEntropyLoss()
... | 5,330,904 |
def test_biblary_file_get(get_bibliography, client):
"""Test the :class:`biblary.views:BiblaryFileView` view ``GET`` method."""
with get_bibliography() as bibliography:
content = b'some-content'
file_type = FileType.MANUSCRIPT
entry = list(bibliography.values())[0]
url_kwargs = ... | 5,330,905 |
def add_contact_annotation(annotations, matches):
"""
Converts matches to TextContactAnnotation objects and adds them to the
annotations array specified.
"""
for match in matches:
annotations.append(TextContactAnnotation(
start=int(match['start']),
length=int(match['e... | 5,330,906 |
def digital_PCR( primer_mappings ):
"""
Makes a "digital" PCR by looking at the mappings of primers and
predict which will produce products, and more important multiple
products
"""
primer_names = sorted(primer_mappings.keys())
nr_primer_names = len( primer_names )
mappings = {}
p... | 5,330,907 |
def database_find_user_salt(username:str)->str:
"""
Finds a users salt from there username
Parameter:
username (str): username selected by the user
Returns:
salt (str): The users salt from the database
Example:
>>> username = 'andrew'
>>> database_find_user... | 5,330,908 |
def createSimulate(netParams=None, simConfig=None, output=False):
"""
Function for/to <short description of `netpyne.sim.wrappers.createSimulate`>
Parameters
----------
netParams : <``None``?>
<Short description of netParams>
**Default:** ``None``
**Options:** ``<option>`` <... | 5,330,909 |
def lang_add(cursor, lang, trust):
"""Adds language for db"""
if trust:
query = 'CREATE TRUSTED LANGUAGE "%s"' % lang
else:
query = 'CREATE LANGUAGE "%s"' % lang
cursor.execute(query)
return True | 5,330,910 |
def interpolate(
a_x, a_q2, padded_x, s_x, padded_q2, s_q2, actual_padded,
):
"""
Basic Bicubic Interpolation inside the subgrid
Four Neighbour Knots selects grid knots around each query point to
make the interpolation: 4 knots on the x axis and 4 knots on the q2
axis are needed for each point, ... | 5,330,911 |
def sobel_mag_thresh(img, ksize, min_thresh, max_thresh):
"""
Apply Sobel filter along x-axis, y-axis and calculate the magnitude,
and returns a binary image according to the given thresholds.
""" | 5,330,912 |
def setting():
""" SMS settings for the messaging framework """
tablename = "%s_%s" % (module, resourcename)
table = s3db[tablename]
table.outgoing_sms_handler.label = T("Outgoing SMS handler")
table.outgoing_sms_handler.comment = DIV(DIV(_class="tooltip",
_title="%s|%s" % (T("Outgoing SMS... | 5,330,913 |
def shutdown(proceed: bool = False) -> None:
"""Gets confirmation and turns off the machine.
Args:
proceed: Boolean value whether or not to get confirmation.
"""
if not proceed:
speaker.say(f"{choice(confirmation)} turn off the machine?")
speaker.runAndWait()
converted =... | 5,330,914 |
def strip_path():
"""
pre routing hook to make "/x/y/z/" the same as "/x/y/z"
"""
request.environ['PATH_INFO'] = request.environ['PATH_INFO'].rstrip('/') | 5,330,915 |
def _cachegetter(
attr: str,
cachefactory: Callable[[], _CacheT] = WeakKeyDictionary, # WeakKewDict best for properties
) -> Callable[[_CIT], _CacheT]:
"""Returns a safer attrgetter which constructs the missing object with cachefactory
May be used for normal methods, classmethods and propertie... | 5,330,916 |
def __gt__(x1: array, x2: array, /) -> array:
"""
Note: __gt__ is a method of the array object.
"""
pass | 5,330,917 |
def change_db_path(new_path: Path, cfg: TodoConfig) -> ErrMsg:
"""new_path 是一个不存在的文件或一个已存在的文件夹,不能是一个已存在的文件"""
new_path = new_path.resolve()
if new_path.is_dir():
new_path = new_path.joinpath(todo_db_name)
if new_path.exists():
return f"{new_path} already exists."
old_path = cfg["db_p... | 5,330,918 |
def format_time(time):
""" It formats a datetime to print it
Args:
time: datetime
Returns:
a formatted string representing time
"""
m, s = divmod(time, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
return ('{:02d}d {:02d}h {:02d}m {:02d}s').format(int(d), int(h), int(m), int(s)) | 5,330,919 |
def egarch_recursion_python(
parameters: Float64Array,
resids: Float64Array,
sigma2: Float64Array,
p: int,
o: int,
q: int,
nobs: int,
backcast: float,
var_bounds: Float64Array,
lnsigma2: Float64Array,
std_resids: Float64Array,
abs_std_resids: Float64Array,
) -> Float64Arr... | 5,330,920 |
def watermark(start_img, argument, filename):
"""
Watermarks `start_img` with the logo and position specified in `argument`, if any is specified.
Default is colors and bottom right corner.
Then saves the resulting image to `filename` in the same folder the script runs from.
"""
white_bg = Image.... | 5,330,921 |
def polpair_tuple2int(polpair, x_orientation=None):
"""
Convert a tuple pair of polarization strings/integers into
an pol-pair integer.
The polpair integer is formed by adding 20 to each standardized
polarization integer (see polstr2num and AIPS memo 117) and
then concatenating them. For exampl... | 5,330,922 |
def compute_features(df):
"""Compute ReScore features."""
preds_dict = df_to_dict(df)
rescore_features = []
spec_ids = []
charges = []
feature_names = [
"spec_pearson_norm",
"ionb_pearson_norm",
"iony_pearson_norm",
"spec_mse_norm",
"ionb_mse_norm",
... | 5,330,923 |
def collection_basic(commodities) -> CommodityCollection:
"""Returns a simple collection of commodities side effects testing."""
keys = ["9999_80_1", "9999.10_80_2", "9999.20_80_2"]
return create_collection(commodities, keys) | 5,330,924 |
def do_js_minimization(test_function, get_temp_file, data, deadline, threads,
cleanup_interval, delete_temp_files):
"""Javascript minimization strategy."""
# Start by using a generic line minimizer on the test.
# Do two line minimizations to make up for the fact that minimzations on bots
... | 5,330,925 |
def printMessage(output_format, message):
"""
Prints the message in specified output format
"""
if output_format == "xml":
print(cli_xml.createMessage(message))
else:
print(message) | 5,330,926 |
def percent_list(part_list, whole_list):
"""return percent of the part"""
w = len(whole_list)
if not w:
return (w,0)
p = 100 * float(len(part_list))/float(w)
return (w,round(100-p, 2)) | 5,330,927 |
def test_graphs():
"""Verify all devices have the correct number of qubits with each degree."""
test_edges = compute_edges(TestDevice._interaction_patterns)
assert degree(test_edges, 0) == 2
assert degree(test_edges, 1) == 2
assert degree(test_edges, 2) == 2
aspen_edges = compute_edges(Aspen._i... | 5,330,928 |
def corr_heatmap(df):
"""
The function corr_heatmap() is to show a correlation heatmap for all features in the dataframe.
:param df: an pandas dataframe
:return: null
"""
# correlation heatmap
plt.figure(figsize=(16, 16))
sns.heatmap(df.corr())
plt.show() | 5,330,929 |
def disp_calc_helper_NB(adata, min_cells_detected):
"""
Parameters
----------
adata
min_cells_detected
Returns
-------
"""
rounded = adata.raw.astype('int') if adata.raw is not None else adata.X
lowerDetectedLimit = adata.uns['lowerDetectedLimit'] if 'lowerDetectedLimit' in ad... | 5,330,930 |
def prGreen(skk):
"""Prints Green Text to Console"""
print("\033[92m{} \033[00m" .format(skk)) | 5,330,931 |
def update_dependency_options(value):
"""Handle Node dependencies
The default value is created upton instantiation of a ZnTrackOption,
if a new class is created via Instance.load() it does not automatically load
the default_value Nodes, so we must to this manually here and call update_options.
"""
... | 5,330,932 |
def print_results(request):
"""Renders the results url, which is a placeholder copy of the root url of
query interface, where any results are rendered alongside the table headers.
"""
if request.method == "POST":
form = MetadataForm(request.POST)
if form.is_valid():
query_res... | 5,330,933 |
def capacity_rule(mod, g, p):
"""
The capacity of projects of the *gen_ret_bin* capacity type is a
pre-specified number for each of the project's operational periods
multiplied with 1 minus the binary retirement variable.
"""
return mod.gen_ret_bin_capacity_mw[g, p] \
* (1 - mod.GenRetBi... | 5,330,934 |
def tag_evidence_subtype(
evidence: Evidence,
) -> Tuple[str, Optional[str]]:
"""Returns the type and subtype of an evidence object as a string,
typically the extraction rule or database from which the statement
was generated.
For biopax, this is just the database name.
Parameters
--------... | 5,330,935 |
def block_deconv_k4s2p1_BN_RELU(in_channel_size, out_channel_size, leaky = 0):
"""
>>> block_deconv_k4s2p1_BN_RELU(13, 17, 0.02)
Sequential(
(0): ConvTranspose2d(13, 17, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): BatchNorm2d(17, eps=1e-05, momentum=0.1, affine=True, trac... | 5,330,936 |
def get_one_organization_by_name(ctx, org_name):
"""Get one Atlas Organization by name. Prints "None" if no organization
bearing the given name exists."""
pprint(cmd.get_one_organization_by_name(
client=ctx.obj.client, organization_name=org_name)) | 5,330,937 |
def main(
scope: str,
secret_name: str,
secret_value: str
):
"""
Run main function.
Parameters
----------
scope : str
Scope to use
secret_name : str
Name of the secret
secret_value : str
Value of the secret
"""
configuration = Configuration(file_l... | 5,330,938 |
def demo_super_fast_representative_crop(image, crop_size=64000, display: bool = True):
"""
Demo for self-supervised denoising using camera image with synthetic noise
"""
Log.enable_output = True
Log.set_log_max_depth(5)
image = normalise(image.astype(numpy.float32))
image += 0.1 * normal(si... | 5,330,939 |
async def start_response(writer, content_type='text/html', status=None,
headers={}, exception=None):
"""
Low level HTTP response.
Writes HTTP response.
"""
if exception and status is None:
status = exception.status
elif status is None:
status = 200
w... | 5,330,940 |
def encrypt_uid(user):
"""Encrypts the User id for plain
"""
uid_xor = htk_setting('HTK_USER_ID_XOR')
crypt_uid = int_to_base36(user.id ^ uid_xor)
return crypt_uid | 5,330,941 |
def createNewVarName(varType):
"""An helper function that returns a new name for creating fresh variables.
"""
createNewVarName.counter += 1
# return "v_{}_{}".format(varType.lower(), createNewVarName.counter)
return "v_{}".format(createNewVarName.counter) | 5,330,942 |
def initialize_parameters(n_a, n_x, n_y):
"""
Initialize parameters with small random values
Returns:
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Waa -- Weight matrix multiplying the hidde... | 5,330,943 |
def enable_console_log():
"""Enable console logging for all the new loggers and add console
handlers to all the existing loggers."""
# pylint: disable=global-statement
global LOG_TO_CONSOLE
LOG_TO_CONSOLE = True
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.... | 5,330,944 |
def test_getPeakPositions():
"""
test getPeakPositions function that returns a pandas
dataframe. Check for shape of dataframe and column names
"""
chroms = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8',
'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', '... | 5,330,945 |
def secure_request(request, ssl: bool):
"""
:param ssl:
:param request:
:return:
"""
# request.headers['Content-Security-Policy'] = "script-src 'self' cdnjs.cloudflare.com ; "
request.headers['Feature-Policy'] = "geolocation 'none'; microphone 'none'; camera 'self'"
request.headers['Ref... | 5,330,946 |
def mock_invalid_login_data():
"""Mock invalid login data."""
path = "homeassistant.components.yessssms.notify.YesssSMS.login_data_valid"
with patch(path, return_value=False):
yield | 5,330,947 |
def f_mean(data: pd.DataFrame, tags=None, batch_col=None, phase_col=None):
"""
Feature: mean
The arithmetic mean for the given tags in ``tags``,
for each unique batch in the ``batch_col`` indicator column, and
within each unique phase, per batch, of the ``phase_col`` column.
"""
base_nam... | 5,330,948 |
def AtariConvInit(kernel_shape, rng, dtype=jnp.float32):
"""The standard init for Conv laters and Atari."""
filter_height, filter_width, fan_in, _ = kernel_shape
std = 1 / jnp.sqrt(fan_in * filter_height * filter_width)
return random.uniform(rng, kernel_shape, dtype, minval=-std, maxval=std) | 5,330,949 |
def extract_fields_from_nest(nest):
"""Extract fields and the corresponding values from a nest if it's either
a ``namedtuple`` or ``dict``.
Args:
nest (nest): a nested structure
Returns:
Iterable: an iterator that generates ``(field, value)`` pairs. The fields
are sorted before b... | 5,330,950 |
def masked_equal(x: numpy.ndarray, value: int):
"""
usage.dask: 5
usage.scipy: 4
"""
... | 5,330,951 |
def scrape(url):
"""
Scrapes a url and returns the html using the proper User Agent
"""
UA = 'Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.2.9) Gecko/20100913 Firefox/3.6.9'
urllib.quote(url.encode('utf-8'))
req = urllib2.Request(url=url,
headers={'User-Agent': UA})... | 5,330,952 |
def _get_prefixed_values(data, prefix):
"""Collect lines which start with prefix; with trimming"""
matches = []
for line in data.splitlines():
line = line.strip()
if line.startswith(prefix):
match = line[len(prefix):]
match = match.strip()
matches.append(m... | 5,330,953 |
def build_k5_graph():
"""Makes a new K5 graph.
Ref: http://mathworld.wolfram.com/Pentatope.html"""
graph = UndirectedGraph()
# K5 has 5 nodes
for _ in range(5):
graph.new_node()
# K5 has 10 edges
# --Edge: a
graph.new_edge(1, 2)
# --Edge: b
graph.new_edge(2, 3)
#... | 5,330,954 |
def bytes_to_msg(seq, standard="utf-8"):
"""Decode bytes to text."""
return seq.decode(standard) | 5,330,955 |
def test_parses(article):
"""Verify we can parse the document."""
assert 'id="readabilityBody"' in article.readable | 5,330,956 |
def cross_validate(
estimator,
input_relation: Union[str, vDataFrame],
X: list,
y: str,
metric: Union[str, list] = "all",
cv: int = 3,
pos_label: Union[int, float, str] = None,
cutoff: float = -1,
show_time: bool = True,
training_score: bool = False,
**kwargs,
):
"""
----... | 5,330,957 |
def plot_tsne(embedding, labels, phase="train"):
"""Function to plot tsne
Args:
embedding (float Tensor): Embedding of data. Batch Size x Embedding Size
labels (int): Ground truth.
phase (str, optional): Is the plot for train data or validation data or test data? Defaults to "train".
... | 5,330,958 |
def bonferroni_correction(pvals):
"""
Bonferroni correction.
Reference: http://en.wikipedia.org/wiki/Bonferroni_correction
"""
n = len(pvals)
return [min(x * n , 1.0) for x in pvals] | 5,330,959 |
def to_r4(fhir_json: JsonObj, opts: Namespace, ifn: str) -> JsonObj:
"""
Convert the FHIR Resource in "o" into the R4 value notation
:param fhir_json: FHIR resource
:param opts: command line parser arguments
:param ifn: input file name
:return: reference to "o" with changes applied. Warning: o... | 5,330,960 |
def make_fib():
"""Returns a function that returns the next Fibonacci number
every time it is called.
>>> fib = make_fib()
>>> fib()
0
>>> fib()
1
>>> fib()
1
>>> fib()
2
>>> fib()
3
>>> fib2 = make_fib()
>>> fib() + sum([fib2() for _ in range(5)])
12
... | 5,330,961 |
def find_issue(case):
"""
Find the issue sentence for a given case.
"""
if ".txt" not in case:
case += ".txt"
f = codecs.open(os.path.join(BASE_DIR, case), encoding="utf-8", errors="replace")
issue, switch = "", False
for line in f.readlines():
if line.startswith("THE ISSUE... | 5,330,962 |
def render_injected(http_resp, extra_html):
"""
render_injected(http_resp, extra_html) -> HttpResponse
Inject the extra html into the content of the http_resp.
``extra_html`` can be a string or an object with an ``html`` method/field.
"""
assert isinstance(http_resp, HttpResponse)
if 'text/html' not in h... | 5,330,963 |
def prepare_image_folders(args):
"""
Prepares directory structure given below.
data/
prepared/ -> 1400
train/ -> 896 total
bear/ -> 224
elephant/ -> 224
leopard/ -> 224
zebra/ -> 224
test/ ... | 5,330,964 |
def _extract_username(filename):
"""Return username (if found) from the credentials"""
if not os.path.exists(filename):
logger.warning("Cifs credentials file %s does not exist", filename)
return
for line in open(filename):
if ("username" in line) and ("=" in line):
userna... | 5,330,965 |
def check_call(*popenargs, **kwargs):
"""Call a process and check result code.
Note: This catches the error, and makes it nicer, and an error
exit. So this is for tooling only.
Note: We use same name as in Python stdlib, violating our rules to
make it more recognizable what this does.
"""
... | 5,330,966 |
def wait_for_tasks_to_complete(
table_service, batch_client, entity_pk, entity_rk, job_id):
"""
Returns when all tasks in the specified job reach the Completed state.
"""
while True:
entity = table_service.get_entity(
'AnalysisEntity', entity_pk, entity_rk)
tasks = ... | 5,330,967 |
def mock_gitlab_api_projects(save=None, mergerequests_list=None):
"""A pseudo mock"""
def get(*args, **kwargs):
project = Mock('gitlab.v4.objects.Project')
project.save = save
project.mergerequests = \
Mock('gitlab.v4.objects.ProjectMergeRequestManager')
project.merge... | 5,330,968 |
def main():
"""See module docstring at the top of this file."""
# initialize blob detector
params = cv2.SimpleBlobDetector_Params()
params.filterByColor = False
params.filterByConvexity = False
params.filterByInertia = False
params.maxArea = 50000.0
params.minThreshold = 1
params.ma... | 5,330,969 |
def safety(session: Session) -> None:
"""Scan PROD dependencies for insecure packages."""
packages = ["safety"]
install_with_constraints(
session, include_dev=False, callback=safety_check, packages=packages
) | 5,330,970 |
def text_in_bytes(text, binary_data, encoding="utf-8"):
"""Return True of the text can be found in the decoded binary data"""
return text in binary_data.decode(encoding) | 5,330,971 |
def RASGeo2Shp(RAS_geo_file, output_folder):
"""
extracts centerline and cross-sections from HEC-RAS geometry file to shapefile
Parameters
----------
RAS_geo_file : TYPE
DESCRIPTION.
output_folder : TYPE
DESCRIPTION.
Returns
-------
Two shapefiles, one containing ce... | 5,330,972 |
def make_auth(sub, tenant=None):
"""
Prepare an almost-valid JWT token header, suitable for consumption by our identity middleware (needs sub and optionally mender.tenant claims).
The token contains valid base64-encoded payload, but the header/signature are bogus.
This is enough for the ide... | 5,330,973 |
def available_mem(cores, mem, fmtstring=True):
"""Calculate available memory for a process
Params:
cores (int): number of cores
mem (str): set memory as string with conversion (M, G, g)
fmtstring (bool): return memory as formatted string
"""
prefix = "G"
m = re.match("[0-9]+([a-zA-Z... | 5,330,974 |
def normalize_v(v):
""" Normalize velocity to [-1, 1].
Ref: https://github.com/microsoft/AirSim-Drone-Racing-VAE-Imitation/blob/e651be52ff8274c9f595e88b13fe42d51302403d/racing_utils/dataset_utils.py#L20 """
# normalization of velocities from whatever to [-1, 1] range
v_x_range = [-1, 7]
v_y_ran... | 5,330,975 |
def test_sftp_fetcher_load_system_keys_fails(tmp_trestle_dir: pathlib.Path, monkeypatch: MonkeyPatch) -> None:
"""Test the sftp fetcher when SSHClient loading of system host keys fails."""
def ssh_load_system_host_keys_mock():
raise OSError('stuff')
uri = 'sftp://username:password@some.host/path/t... | 5,330,976 |
def volume_restricted_metadata_delete(context, volume_id, key):
"""Delete the given restricted metadata item."""
IMPL.volume_restricted_metadata_delete(context, volume_id, key) | 5,330,977 |
def allele_counts_dataframe(read_evidence_generator):
"""
Creates a DataFrame containing number of reads supporting the
ref vs. alt alleles for each variant.
"""
return dataframe_from_generator(
element_class=ReadEvidence,
variant_and_elements_generator=read_evidence_generator,
... | 5,330,978 |
def validate_rule_paths(sched: schedule.Schedule) -> schedule.Schedule:
"""A validator to be run after schedule creation to ensure
each path contains at least one rule with an expression or value.
A ValueError is raised when this check fails."""
for path in sched.unfold():
if path.is_final and ... | 5,330,979 |
def update_template(src):
"""
Updates existing templates
"""
# remove
template_name = os.path.basename(src)
remove(template_name)
# add
add_template(src) | 5,330,980 |
def spiralcontrolpointsvert(
x: int, y: int,
step: int,
growthfactor: float,
turns: int):
"""Returns a list[(int, int)]
of 2D vertices along a path
defined by a square spiral
Args:
x, y: int centerpoint
coordinates
st... | 5,330,981 |
def determine_current_taxid(given_taxid):
"""Determine NCBI's current taxonomic ID given an (old) taxonomic ID
Args:
given_taxid: previously used NCBI taxonomic ID
Returns:
most current NCBI taxonomic ID
"""
taxid = given_taxid
aka_taxid_in_xml = None
redirects = 0
# S... | 5,330,982 |
def validate_dependencies():
"""Validate external dependencies.
This function does NOT have to exist. If it does exist the runtime will call and execute it during api
initialization. The purpose of this function is to verify that external dependencies required to auto-generate
a problem are properly in... | 5,330,983 |
def find_closest_vertex(desired_hop, available_vertices):
""" Find the closest downstream (greater than or equal) vertex
in availbale vertices. If nothing exists, then return -1.
Keyword arguments:
desired_hop -- float representing the desired hop location
available_location -- np array of avai... | 5,330,984 |
def second_smallest(numbers):
"""Find second smallest element of numbers."""
m1, m2 = float('inf'), float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2 | 5,330,985 |
def calc_sft_ccs_by_dictionary(dict_crystal, dict_in_out, flag_use_precalculated_data: bool = False):
"""Calculate structure factor tensor in CCS (X||a*, Z||c) based on the information given in dictionary.
Output information is written in the same dictionary.
"""
dict_crystal_keys = dict_crystal.keys()... | 5,330,986 |
def main():
"""Main"""
text = 'Scrolling ASCII text in console.'
font = ImageFont.load_default()
# font = ImageFont.truetype('arial.ttf', 16)
# get size of space char
space_width = get_text_size(font, ' ')[0]
# get size of text
text_height = get_text_size(font, text)[1]
# resize ... | 5,330,987 |
def normalize_mesh(mesh, in_place=True):
"""Rescales vertex positions to lie inside unit cube."""
scale = 1.0 / np.max(mesh.bounds[1, :] - mesh.bounds[0, :])
centroid = mesh.centroid
scaled_vertices = (mesh.vertices - centroid) * scale
if in_place:
scaled_mesh = mesh
scaled_mesh.vertices = scaled_vert... | 5,330,988 |
def assert_almost_equal(
actual: numpy.float64, desired: numpy.float64, err_msg: Literal["orth.laguerre(1)"]
):
"""
usage.scipy: 1
"""
... | 5,330,989 |
def basic(stocks):
"""
basic report of stocks
"""
# Get basic info from stocks
basics = pd.DataFrame([get_basic_info(code) for code in stocks])
basics.set_index(['股票代码'], inplace=True)
year_yoy_list = []
quarter_yoy_list = []
quarter_qoq_list = []
for code in stocks:
# g... | 5,330,990 |
def test_file_long_format(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file long format"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
msg = 'This is a message... | 5,330,991 |
def test_roundtrip(tmpdir: Path):
"""
Check that we can write DL1+DL2 info to files and read them back
Parameters
----------
tmpdir :
temp directory fixture
"""
output_path = Path(tmpdir / "events.DL1DL2.h5")
source = EventSource(
get_dataset_path("gamma_LaPalma_baselin... | 5,330,992 |
def _updateKeyword(key,inhdr,outhdr,default='UNKNOWN'):
""" Safely updates keyword key in outhdr from value in inhdr.
Uses value given by 'default' if keyword is not found in
input header.
"""
try:
_keyw = inhdr[key]
except KeyError:
_keyw = default
outhdr[key] = _key... | 5,330,993 |
def get_run_name():
""" A unique name for each run """
return datetime.now().strftime(
'%b%d-%H-%M-%S') + '_' + socket.gethostname() | 5,330,994 |
def process_request(identifier, browser, document_type='Annual Return', num_doc=1, status_df=None):
"""
Search ICRIS for the passed identifier, analyze the returned documents,
and cart the documents depending on whether we purchased
the document before.
Parameters
----------
identifier :... | 5,330,995 |
def create_blackboard():
"""
Create a blackboard with a few variables.
Fill with as many different types as we need to get full coverage on
pretty printing blackboard tests.
"""
Blackboard.clear()
blackboard = Client(name="Tester")
for key in {"foo", "some_tuple", "nested", "nothing"}:
... | 5,330,996 |
def adminRoomDelete(*args, **kwargs):
""" 删除房间 """
params = kwargs['params']
filters = {
Room.room_uuid == params['room_uuid']
}
Room().delete(filters)
filters = {
UserRoomRelation.room_uuid == params['room_uuid']
}
UserRoomRelation().delete(filters)
return BaseContro... | 5,330,997 |
def test_representation(target, expected_str):
"""Ensure ``MigrationNotInPlan`` has expected string representation."""
assert str(exceptions.MigrationNotInPlan(target)) == expected_str | 5,330,998 |
def who_is_it(image_path, database, model):
"""
Arguments:
image_path -- path to an image
database -- database containing image encodings along with the name of the person on the image
model -- your Inception model instance in Keras
Returns:
min_dist -- the minimum distance between image_pa... | 5,330,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.