content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
from typing import Mapping
def UpdateDict( target, override ):
"""Apply the updates in |override| to the dict |target|. This is like
dict.update, but recursive. i.e. if the existing element is a dict, then
override elements of the sub-dict rather than wholesale replacing.
e.g.
UpdateDict(
{
'outer': { 'inner': { 'key': 'oldValue', 'existingKey': True } }
},
{
'outer': { 'inner': { 'key': 'newValue' } },
'newKey': { 'newDict': True },
}
)
yields:
{
'outer': {
'inner': {
'key': 'newValue',
'existingKey': True
}
},
'newKey': { newDict: True }
}
"""
for key, value in override.items():
current_value = target.get( key )
if not isinstance( current_value, Mapping ):
target[ key ] = value
elif isinstance( value, Mapping ):
target[ key ] = UpdateDict( current_value, value )
else:
target[ key ] = value
return target | a07a3d7989e227ff1759271248777e167b7e5467 | 699,096 |
def dss_target(request):
"""
This is a parameterized fixture. Its value will be set with the different DSS target (DSS7, DSS8 ...) that are specified in the configuration file.
It returns the value of the considered DSS target for the test. Here it is only used by other fixtures, but one could use it
as a test function parameter to access its value inside the test function.
Args:
request: The object to introspect the “requesting” test function, class or module context
Returns:
The string corresponding to the considered DSS target for the test to be executed
"""
return request.param | 0aa9f85160280032dfdea872b7c9a147a5717523 | 699,098 |
def gym_size(gym):
"""Returns the size of the gym."""
return len(gym) | b31a46a7b56e973da8dfa0cac9950fad14b48622 | 699,101 |
def is_call_id_in_video_state(log, ad, call_id, video_state):
"""Return is the call_id is in expected video_state
Args:
log: logger object
ad: android_device object
call_id: call id
video_state: valid VIDEO_STATE
Returns:
True is call_id in expected video_state; False if not.
"""
return video_state == ad.droid.telecomCallVideoGetState(call_id) | d0da323a21a23d461fc2aec06ac5d0bebac7cbef | 699,103 |
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):
"""
Extract spots detected outside foci, in a specific cell.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
spots_out_foci : np.ndarray, np.int64
Coordinate of the spots detected outside foci, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a
default index (-1 for mRNAs spotted outside a foci).
Returns
-------
spots_out_foci_cell : np.ndarray, np.int64
Coordinate of the spots detected outside foci in the cell, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the
index of the foci.
"""
# get coordinates of rna outside foci
mask_spots_to_keep = cell_cyt_mask[spots_out_foci[:, 1],
spots_out_foci[:, 2]]
spots_out_foci_cell = spots_out_foci[mask_spots_to_keep]
return spots_out_foci_cell | d4e06d9ad14ced3b8984b71c32d9d3b1e0cebaae | 699,104 |
def extract_image_number(filename: str, from_file: bool) -> int:
"""
finds the number of the image from the original images of LITIV 2014 dataset.
:param filename: name of the image file.
:param from_file: filename is read from a ground-truth file or not.
:return: number.
"""
number = filename[-8:-4]
if from_file:
number = filename[-9:-5]
if not number.isdigit():
number = number[-3:]
if not number.isdigit():
number = number[-2:]
return int(number) | e55431beffb02959907106a01596310812ba7363 | 699,107 |
def calculateNetIncome(gross, state):
"""
Calculate the net income after federal and state tax
:param gross: Gross Income
:param state: State Name
:return: Net Income
"""
state_tax = {'LA': 10, 'SA': 0, 'NY': 9}
# Calculate net income after federal tax
net = gross - (gross * .10)
# Calculate net income after state tax
if state in state_tax:
net = net - (gross * state_tax[state]/100)
print("Your net income after all the heavy taxes is: " + str(net))
return net
else:
print("State not in the list")
return None | 915528d8bfd15c18003eaeb8f6b3f1e8ad5565a0 | 699,110 |
def field_size(field_label):
"""
Helper function to determine the size of a binary
table field
Parameters
----------
field_label : PVLModule
The field label
Returns
-------
int :
The size of the one entry in bytes
"""
data_sizes = {
'Integer' : 4,
'Double' : 8,
'Real' : 4,
'Text' : 1
}
return data_sizes[field_label['Type']] * field_label['Size'] | afaff70bc18d4d9d023fb7c89d45560f1a691bcf | 699,111 |
def leading_by(agents, player):
"""Determine difference between player's score and closest opponent."""
scores = [a.score() for a in agents]
player_score = scores[player]
scores.sort()
if player_score == scores[-1]:
return player_score - scores[-2]
else:
return player_score - scores[-1] | e97aa0a1109bb2ba5f276f34030ea1f93022046f | 699,113 |
def mk_seealso(
function_name: str,
role: str = "func",
prefix: str = "\n\n",
module_location: str = ".",
) -> str:
"""
Returns a sphinx `seealso` pointing to a function.
Intended to be used for building custom fitting model docstrings.
.. admonition:: Usage example for a custom fitting model
:class: dropdown, tip
See the usage example at the end of the :class:`~ResonatorModel` source-code:
.. literalinclude:: ../quantify_core/analysis/fitting_models.py
:pyobject: ResonatorModel
Parameters
----------
function_name
name of the function to point to
role
a sphinx role, e.g. :code:`"func"`
prefix
string preceding the `seealso`
module_location
can be used to indicate a function outside this module, e.g.,
:code:`my_module.submodule` which contains the function.
Returns
-------
:
resulting string
"""
return f"{prefix}.. seealso:: :{role}:`~{module_location}{function_name}`\n" | 0165599829e8edd3f75adcda9402069066a0381a | 699,115 |
def mock_xibo_api(mocker):
"""Return a mock XiboApi."""
return mocker.MagicMock() | 8c2ad1566ad716d9fb4dd680a624e59f89950a0a | 699,117 |
def get_corpus_archive_name(cycle: int) -> str:
"""Returns a corpus archive name given a cycle."""
return 'corpus-archive-%04d.tar.gz' % cycle | 3068ce88bd85f2c21819da697a2b1147f547c509 | 699,118 |
import re
def extract_airlines_from_flight_text(flight_text):
"""
:param flight_text: Raw flight text string, e.g.,
"3:45 PM – 8:15 PM+1\nUnited\n13h 30m\nSFO–PVG\nNonstop\n$4,823",
"12:51 PM – 4:50 PM+1\nDelta\nChina Southern\n12h 59m\nSEA–PVG\nNonstop\n$4,197",
"2:10 AM – 1:25 PM+1\nSeparate tickets booked together\nEVA Air, Spring\n20h 15m\nSEA–PVG\n1 stop\n6h 15m TPE\n$1,194"
:return: A list of airlines, e.g., ["United"], ["Delta", "China Southern"], ["EVA Air", "Spring"]
"""
airlines = []
# We escape flight_text.split("\n")[0] which indicates flight time range.
for airline_candidate in flight_text.split("\n")[1:]:
if airline_candidate == "Separate tickets booked together":
continue
if re.match(r"(\d+h )?\d+m", airline_candidate):
# The flight time length indicates the end of airline info.
break
airlines.extend(airline_candidate.split(","))
return airlines | 188f040c15e62f4eace72cb90ef74825c4b803fc | 699,120 |
def get_inputs(inputs, mask=None):
"""Extract and normalize the arrays from inputs"""
gmax = inputs[0][:,:,1].max()
o = inputs[0][:,:,0]/gmax
n = inputs[1][:,:,0]/gmax
return o,n | 329dfce70d65dec8d5f177239b7f88c977519867 | 699,121 |
def formatTime(t):
"""Check if hour, minute, second variable has format hh, mm or ss if not change format.
:param t: string time hh, mm or ss
:return: string time in correct format eg. hh=02 instead of hh=2
"""
if len(t) < 2:
t = "0" + t
return t | 8011fc25a001964af1f1e0b0cb4e54f7d7aec721 | 699,123 |
def remove_signature(message):
"""Remove the 3 Letter signature and the '/' found at the beginning of a valid message"""
return message[1:] | a802dc5abfea09e05fad51936dd76e17719900e7 | 699,126 |
import textwrap
def get_comment_from_location(location):
"""Return comment text from location.
Args:
location: descriptor_pb2.SourceCodeInfo.Location instance to get
comment from.
Returns:
Comment as string.
"""
return textwrap.dedent(location.leading_comments or
location.trailing_comments) | d86213ddee50128c8363d2a31a740c5677244612 | 699,128 |
def get_name(test):
"""Gets the name of a test.
PARAMETERS:
test -- dict; test cases for a question. Expected to contain a key
'name', which either maps to a string or a iterable of
strings (in which case the first string will be used)
RETURNS:
str; the name of the test
"""
if type(test['name']) == str:
return test['name']
return test['name'][0] | e9d5a5013b062077c499e0351786819c9bd6bd90 | 699,131 |
def check_if_points_escape_box(u, box_boundaries):
"""
Determine if points u in 2D plane have escaped from box_boundaries limits.
Parameters
----------
u : ndarray, shape(n, 2),
Points in plane.
box_boundaries : list of 2 tuples of floats,
Values are interpreted as [[x_min,x_max], [y_min, y_max]].
Returns
-------
u_indices : ndarray of bools, shape(n, 2),
True/False for points inside/outside the box_boundaries respectively.
"""
x, y = u.T
# Escape condition
box_x_min, box_x_max = box_boundaries[0]
box_y_min, box_y_max = box_boundaries[1]
u_indices = (x >= box_x_min) & (x <= box_x_max) & (y >= box_y_min) & (y <= box_y_max)
return u_indices | 41b04b72821bc39f387c7557be1b11f14e65c71d | 699,132 |
from typing import Any
import random
def assign_new_ids(items: dict[str, Any]) -> list[str]:
"""
Assigns new IDs to any item ID that starts with "NEW:" or is an empty
string. Will modify the dict in place. Will return a list of new item IDs
assigned.
"""
new_items = []
for item_id in items:
if item_id in ('', 'NEW') or item_id.startswith('NEW:'):
new_items.append(item_id)
for i, item_id in enumerate(new_items):
item_range = (10 ** (max(len(str(len(items))), 5) + 1)) - 1
item_range_l = len(str(item_range))
new_id: str = ''
while not new_id or new_id in items:
new_id = str(random.randint(0, item_range)).zfill(item_range_l)
items[new_id] = items.pop(item_id)
new_items[i] = new_id
return new_items | 4fb3466566f0fd9981e1c99cb429da629c843dab | 699,133 |
def isatty(stream):
"""Check if a stream is attached to a console.
Args:
stream (:obj:`io.IOBase`):
Stream to check.
Returns:
:obj:`bool`
"""
return stream.isatty() if hasattr(stream, "isatty") else False | 4ec38e35413f0f8af76da5e2681f5502acf3d61e | 699,134 |
def egcd(a, b):
"""
Calculate the extended Euclidean algorithm. ax + by = gcd(a,b)
Args:
a (int): An integer.
b (int): Another integer.
Returns:
int: Greatest common denominator.
int: x coefficient of Bezout's identity.
int: y coefficient of Bezout's identity.
"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) | 87b35ff4e28529d1de2a6fb0063b69cee5dfec74 | 699,137 |
def old(sym):
""" Return the "old" version of symbol "sym", that is, the one
representing "sym" in the pre_state.
"""
return sym.prefix('old_') | 4cc24bd0448195ee1c373106679177ce428e5937 | 699,139 |
def _remove_stopwords(line, nlp):
""" Helper function for removing stopwords from the given text line. """
line_nlp = nlp(line)
line_tokens = [tok.text for tok in line_nlp]
filtered_line = list()
# Filter
for tok in line_tokens:
lexeme = nlp.vocab[tok]
if not lexeme.is_stop:
filtered_line.append(tok)
return ' '.join(filtered_line) | 58932dc254874ea7a9e93e7e8d7fbf9f306f740b | 699,144 |
from typing import Dict
def dict_from_text_file(fpath: str) -> Dict[str, float]:
"""Parse a two-column CSV file into a dictionary of string keys and float values.
Will fail an assertion if the second column contains values which are not valid floats.
Args:
fpath (str): Path to file to parse.
Returns:
Dict[str, float]: Dictionary of string keys and float values.
"""
out_dict: Dict[str, float] = {}
with open(fpath, "r") as fp:
for line in fp:
comps = list(map(lambda elem: elem.strip(), line.strip().split(",")))
assert(len(comps) == 2)
key = comps[0]
val = comps[1]
out_dict[key] = float(val)
return out_dict | 5baf29832e0a44c8131a97168cde796757c05bfa | 699,146 |
import posixpath
def get_fuzzer_benchmark_covered_regions_filestore_path(
fuzzer: str, benchmark: str, exp_filestore_path: str) -> str:
"""Returns the path to the covered regions json file in the |filestore| for
|fuzzer| and |benchmark|."""
return posixpath.join(exp_filestore_path, 'coverage', 'data', benchmark,
fuzzer, 'covered_regions.json') | f999a81c53d961a2ed38a7941d7dd6912dae9621 | 699,148 |
def breakdown(data):
"""Break down each row into context-utterance pairs.
Each pair is labeled to indicate truth (1.0) vs distraction (0.0).
Output is a native array with format : [context, utterance, label]"""
output = []
for row in data:
context = row[0]
ground_truth_utterance = row[1]
output.append([list(context), ground_truth_utterance, 1.0])
for i in range(2,11):
output.append([list(context), row[i], 0.0])
return output | 613cc8ca3d65d8eb22631114a88a934f67f37867 | 699,149 |
def string_escape(text: str) -> str:
"""Escape values special to javascript in strings.
With this we should be able to use something like:
elem.evaluateJavaScript("this.value='{}'".format(string_escape(...)))
And all values should work.
"""
# This is a list of tuples because order matters, and using OrderedDict
# makes no sense because we don't actually need dict-like properties.
replacements = (
('\\', r'\\'), # First escape all literal \ signs as \\.
("'", r"\'"), # Then escape ' and " as \' and \".
('"', r'\"'), # (note it won't hurt when we escape the wrong one).
('\n', r'\n'), # We also need to escape newlines for some reason.
('\r', r'\r'),
('\x00', r'\x00'),
('\ufeff', r'\ufeff'),
# https://stackoverflow.com/questions/2965293/
('\u2028', r'\u2028'),
('\u2029', r'\u2029'),
)
for orig, repl in replacements:
text = text.replace(orig, repl)
return text | f85d02527f3a9fdb9373f2359c2fce86b86a5a89 | 699,150 |
def check_permutation(str1, str2):
""" 1.2 Check Permutation: Given two strings, write a method to decide if
one is a permutation of the other.
Complexity: O(n) time, O(n) space
"""
h = {}
for c in str1:
if c not in h:
h[c] = 0
h[c] += 1
for c in str2:
if c not in h:
return False
h[c] -= 1
for (_, count) in h.items():
if count != 0:
return False
return True | 4da48752e963c05115b3255b03749e8579a9f8ff | 699,151 |
def climb_stairs(n: int) -> int:
"""
Args:
n: number of steps of staircase
Returns:
Distinct ways to climb a n step staircase
Raises:
AssertionError: n not positive integer
"""
fmt = "n needs to be positive integer, your input {}"
assert isinstance(n, int) and n > 0, fmt.format(n)
if n == 1:
return 1
dp = [0] * (n + 1)
dp[0], dp[1] = (1, 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n] | 71ac88a1f475e8fe2da8e525f7924e289dbf28e4 | 699,152 |
import codecs
def raw_buffered_line_counter(path, encoding="utf-8", buffer_size=1024 * 1024):
"""
Fast way to count the number of lines in a file.
:param Path path: Path to file.
:param str encoding: Encoding used in file.
:param int buffer_size: Size of buffer for loading.
:return: int
"""
# Open file
f = codecs.open(str(path), encoding=encoding, mode="r")
# Reader generator
def _reader_generator(reader):
b = reader(buffer_size)
while b:
yield b
b = reader(buffer_size)
# Reader used
file_read = f.raw.read
# Count lines
line_count = sum(buf.count(b'\n') for buf in _reader_generator(file_read)) + 1
return line_count | 700135dc1a5b5bf4a807469e34f56213d7b1265a | 699,155 |
def consider_trip_number(trip_strategy, total_trips, trip_num):
"""Determines if the vehicle should charge given trip strategy and current trip
:param int trip_strategy: a toggle that determines if should charge on any trip or only after last trip (1-anytrip number, 2-last trip)
:param int total_trips: total trips that the vehicle makes
:param int trip_num: the trip number of the current trip
:return: (*bool*) -- boolean that represents if the vehicle should charge
"""
if trip_strategy == 1:
return True
elif trip_strategy == 2:
return total_trips == trip_num | b2fe3a43b95fead4ebf65981cfba39857d1bee3c | 699,157 |
import pathlib
def as_pathlib(path):
"""
Converts the supplied path to an pathlib.Path object
:param path: The path to convert
:return: The path converted to pathlib.Path
"""
return pathlib.Path(path) | 88129771be8c3277320c813502efbcfee6abdc84 | 699,158 |
import re
def remove_non_alpha_numeric(input_string):
"""
return string by removing non alpha numric characters from it
"""
return re.sub(r'\W+', '', input_string) | fc7b203e4937a7a5a80f0d3dc9a2d7bca5de6b45 | 699,159 |
def extract_text(tweet):
"""Gets the full text from a tweet if it's short or long (extended)."""
def get_available_text(t):
if t['truncated'] and 'extended_tweet' in t:
# if a tweet is retreived in 'compatible' mode, it may be
# truncated _without_ the associated extended_tweet
#eprint('#%s' % t['id_str'])
return t['extended_tweet']['full_text']
else:
return t['full_text'] if 'full_text' in t else t['text']
if 'retweeted_status' in tweet:
rt = tweet['retweeted_status']
return 'RT @%s: %s' % (rt['user']['screen_name'], extract_text(rt))
if 'quoted_status' in tweet:
qt = tweet['quoted_status']
return get_available_text(tweet) + " --> " + extract_text(qt)
return get_available_text(tweet) | 41660b71e3b020bc25309821b46471e88d79aa49 | 699,163 |
def search_linearf(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
for i in range(len(a)):
if a[i] == x:
return i
return None | 949cb93218381a1a45002be03c6b8ca4d00092bf | 699,164 |
def gamma_corr(clip, gamma):
""" Gamma-correction of a video clip """
def fl(im):
corrected = 255 * (1.0 * im / 255) ** gamma
return corrected.astype("uint8")
return clip.fl_image(fl) | d98d411c63d932b068d80bef63d42289cb0d8468 | 699,166 |
def connected_components(graph):
"""
Given an undirected graph (a 2d array of indices), return a set of
connected components, each connected component being an (arbitrarily
ordered) array of indices which are connected either directly or indirectly.
"""
def add_neighbors(el, seen=[]):
'''
Find all elements which are connected to el. Return an array which
includes these elements and el itself.
'''
#seen stores already-visited indices
if seen == []: seen = [el]
#iterate through the neighbors (x) of el
for x in graph[el]:
if x not in seen:
seen.append(x)
#Recursively find neighbors of x
add_neighbors(x, seen)
return seen
#Create a list of indices to iterate through
unseen = list(range(len(graph)))
sets = []
i = 0
while (unseen != []):
#x is the index we are finding the connected component of
x = unseen.pop()
sets.append([])
#Add neighbors of x to the current connected component
for y in add_neighbors(x):
sets[i].append(y)
#Remove indices which have already been found
if y in unseen: unseen.remove(y)
i += 1
return sets | e8299cc024dd27414a287ee0afa302ea64c18b68 | 699,167 |
import math
import torch
def loglinspace(a, b, n=100, **kwargs):
"""Like :meth:`torch.linspace`, but spread the values out in log space,
instead of linear space. Different from :meth:`torch.logspace`"""
return math.e**torch.linspace(math.log(a), math.log(b), n, **kwargs) | ea456462a0d029f1ada1c4a9e40c9377b86e815d | 699,170 |
def _query_pkey(query, args):
"""Append 'query' and 'args' into a string for use as a primary key
to represent the query. No risk of SQL injection as memo_dict will
simply store memo_dict['malicious_query'] = None.
"""
return query + '.' + str(args) | d524697af247879f6aca5fa3918d80199b6148d5 | 699,177 |
from typing import Dict
def alias(alias: str) -> Dict[str, str]:
"""Select a single alias."""
return {"alias": alias} | 9321f00118658dc74fbc9704f1ea0e4a33e1f7aa | 699,181 |
def max_digits(x):
"""
Return the maximum integer that has at most ``x`` digits:
>>> max_digits(4)
9999
>>> max_digits(0)
0
"""
return (10 ** x) - 1 | 3f0ffdfbbb3fdaec8e77889b3bfa14c9b9829b2e | 699,184 |
def to_numpy(t):
"""
If t is a Tensor, convert it to a NumPy array; otherwise do nothing
"""
try:
return t.numpy()
except:
return t | 3ac3ef0efd9851959f602d42e7f38bdd7e5da21a | 699,185 |
import json
def _jsonToDict(json_file):
"""Reads in a JSON file and converts it into a dictionary.
Args:
json_file (str): path to the input file.
Returns:
(dict) a dictionary containing the data from the input JSON file.
"""
with open(json_file, 'r') as fid:
dout = json.loads(fid.read())
return dout | 6e4b5996d6aaf2982012c6c2f135d7876ee5b3ca | 699,195 |
def _matches_app_id(app_id, pkg_info):
"""
:param app_id: the application id
:type app_id: str
:param pkg_info: the package description
:type pkg_info: dict
:returns: True if the app id is not defined or the package matches that app
id; False otherwise
:rtype: bool
"""
return app_id is None or app_id in pkg_info.get('apps') | 4d6cd0d652a2751b7a378fd17d5ef7403cfdc075 | 699,196 |
def quad_pvinfo(tao, ele):
"""
Returns dict of PV information for use in a DataMap
"""
head = tao.ele_head(ele)
attrs = tao.ele_gen_attribs(ele)
device = head['alias']
d = {}
d['bmad_name'] = ele
d['pvname_rbv'] = device+':BACT'
d['pvname'] = device+':BDES'
d['bmad_factor'] = -1/attrs['L']/10
d['bmad_attribute'] = 'b1_gradient'
return d | b35e04d78d419673afbc0711f9d454e01bc1dd5d | 699,198 |
from typing import Callable
from typing import Set
from typing import Type
def is_quorum(is_slice_contained: Callable[[Set[Type], Type], bool], nodes_subset: set):
"""
Check whether nodes_subset is a quorum in FBAS F (implicitly is_slice_contained method).
"""
return all([
is_slice_contained(nodes_subset, v)
for v in nodes_subset
]) | 4a4af3af8ca5a3f969570ef3537ae75c17a8015c | 699,202 |
from re import match
def extrakey(key):
"""Return True if key is not a boring standard FITS keyword.
To make the data model more human readable, we don't overwhelm the output
with required keywords which are required by the FITS standard anyway, or
cases where the number of headers might change over time.
This list isn't exhaustive.
Parameters
----------
key : :class:`str`
A FITS keyword.
Returns
-------
:class:`bool`
``True`` if the keyword is not boring.
Examples
--------
>>> extrakey('SIMPLE')
False
>>> extrakey('DEPNAM01')
False
>>> extrakey('BZERO')
True
"""
# don't drop NAXIS1 and NAXIS2 since we want to document which is which
if key in ('BITPIX', 'NAXIS', 'PCOUNT', 'GCOUNT', 'TFIELDS', 'XTENSION',
'SIMPLE', 'EXTEND', 'COMMENT', 'HISTORY', 'EXTNAME', ''):
return False
# Table-specific keywords
if match(r'T(TYPE|FORM|UNIT|COMM|DIM)\d+', key) is not None:
return False
# Compression-specific keywords
if match(r'Z(IMAGE|TENSION|BITPIX|NAXIS|NAXIS1|NAXIS2|PCOUNT|GCOUNT|TILE1|TILE2|CMPTYPE|NAME1|VAL1|NAME2|VAL2|HECKSUM|DATASUM)', key) is not None:
return False
# Dependency list
if match(r'DEP(NAM|VER)\d+', key) is not None:
return False
return True | d4c36c3a5408d7056e55d5e67ebebe0b960e5b72 | 699,206 |
def P(N_c, N_cb, e_t, t, A, N_bb):
"""
Returns the points :math:`P_1`, :math:`P_2` and :math:`P_3`.
Parameters
----------
N_c : numeric
Surround chromatic induction factor :math:`N_{c}`.
N_cb : numeric
Chromatic induction factor :math:`N_{cb}`.
e_t : numeric
Eccentricity factor :math:`e_t`.
t : numeric
Temporary magnitude quantity :math:`t`.
A : numeric
Achromatic response :math:`A` for the stimulus.
N_bb : numeric
Chromatic induction factor :math:`N_{bb}`.
Returns
-------
tuple
Points :math:`P`.
Examples
--------
>>> N_c = 1.0
>>> N_cb = 1.00030400456
>>> e_t = 1.1740054728519145
>>> t = 0.149746202921
>>> A = 23.9394809667
>>> N_bb = 1.00030400456
>>> P(N_c, N_cb, e_t, t, A, N_bb) # doctest: +ELLIPSIS
(30162.8908154..., 24.2372054..., 1.05)
"""
P_1 = ((50000 / 13) * N_c * N_cb * e_t) / t
P_2 = A / N_bb + 0.305
P_3 = 21 / 20
return P_1, P_2, P_3 | 82e444ca0e7563f061b69daedd82ff3fc771f190 | 699,208 |
import re
def trim_http(url :str) -> str:
"""
Discard the "http://" or "https://" prefix from an url.
Args:
url: A str containing an URL.
Returns:
The str corresponding to the trimmed URL.
"""
return re.sub("https?://", "", url, flags = re.IGNORECASE) | 472e71a646de94a1ad9b84f46fc576ed5eb5a889 | 699,214 |
def remove_recorders(osi):
"""Removes all recorders"""
return osi.to_process('remove', ['recorders']) | c63f23a031a5c957fd8667fc5be87fbd96b26a1e | 699,221 |
from typing import Match
def gen_ruby_html(match: Match) -> str:
"""Convert matched ruby tex code into plain text for bbs usage
\ruby{A}{B} -> <ruby><rb>A</rb><rp>(</rp><rt>B</rt><rp>)</rp></ruby>
Also support | split ruby
\ruby{椎名|真昼}{しいな|まひる} ->
<ruby><rb>椎名</rb><rp>(</rp><rt>しいな</rt><rp>)</rp><rb>真昼</rb><rp>(</rp><rt>まひる</rt><rp>)</rp></ruby>
"""
return ''.join('<ruby><rb>{}</rb><rp>(</rp><rt>{}</rt><rp>)</rp></ruby>'.format(*pair) for pair in
zip(match['word'].split('|'), match['ruby'].split('|'))) | bd603b67a61812152f7714f3a13f48cac41db277 | 699,224 |
import random
import string
def randomstring(size=20):
"""Create a random string.
Args:
None
Returns:
result
"""
# Return
result = ''.join(
random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for _ in range(size))
return result | 64ecd935130f6308367d02a5d699ea05c906cbb2 | 699,228 |
def has_seven(k):
"""Returns True if at least one of the digits of k is a 7, False otherwise.
>>> has_seven(3)
False
>>> has_seven(7)
True
>>> has_seven(2734)
True
>>> has_seven(2634)
False
>>> has_seven(734)
True
>>> has_seven(7777)
True
"""
if k % 10 == 7:
return True
elif k < 10:
return False
else:
return has_seven(k // 10) | 8c0b7b02e36247b3685a6a0142ebd81dd63e220c | 699,229 |
def get_grid_size(grid):
"""Return grid edge size."""
if not grid:
return 0
pos = grid.find('\n')
if pos < 0:
return 1
return pos | 9ff60184bb0eed7e197d015d8b330dcf615b4008 | 699,233 |
def index() -> str:
"""
Static string home page
"""
return "Hello, Python!!!" | 7bf6b684e8404d0b2d52bb7578e1f44e37bdf565 | 699,236 |
def get_unique_coords(df, lat_field, lon_field):
"""
Takes in a dataframe and extract unique fields for plotting.
Uses dataframe group by to reduce the number of rows that need to
be plotted, returns the lat and lon fields
"""
unique = df.groupby([lat_field, lon_field]).size().reset_index()
lat, lon= unique[lat_field].values, unique[lon_field].values
return lat, lon | 3914e59a9263e07a18833135b0d30a3e5b1d4ce6 | 699,237 |
def unhex(value):
"""Converts a string representation of a hexadecimal number to its equivalent integer value."""
return int(value, 16) | 0a8c297a93f484c8a1143511ef8511521c887a78 | 699,239 |
def filter_errors(seq, errors):
"""Helper for filter_keys.
Return singleton list of error term if only errors are in sequence; else
return all non-error items in sequence.
Args
seq: list of strings
errors: dict representing error values
Returns
List of filtered items.
"""
key_err, val_err = errors['key'], errors['val']
key_err_str, val_err_str = errors['key_str'], errors['val_str']
return ([key_err_str] if set(seq) == set([key_err]) else
[val_err_str] if set(seq) == set([val_err]) else
[s for s in seq if s not in (key_err, val_err)]) | 93f44cd933e48974c393da253b7f37057ea7de19 | 699,244 |
def _offset(x, y, xoffset=0, yoffset=0):
"""Return x + xoffset, y + yoffset."""
return x + xoffset, y + yoffset | a6c88b2ee3172e52f7a538d42247c0fdc16352f8 | 699,245 |
def filter_to_be_staged(position):
"""Position filter for Experiment.filter() to include only worms that still need to be
stage-annotated fully."""
stages = [timepoint.annotations.get('stage') for timepoint in position]
# NB: all(stages) below is True iff there is a non-None, non-empty-string
# annotation for each stage.
return not all(stages) or stages[-1] != 'dead' | df771b0856c91c8663ad06cacf86bf3389df04c5 | 699,246 |
def leja_growth_rule(level):
"""
The number of samples in the 1D Leja quadrature rule of a given
level. Most leja rules produce two point quadrature rules which
have zero weight assigned to one point. Avoid this by skipping from
one point rule to 3 point rule and then increment by 1.
Parameters
----------
level : integer
The level of the quadrature rule
Return
------
num_samples_1d : integer
The number of samples in the quadrature rule
"""
if level == 0:
return 1
return level+2 | b93fe05a3bf9b8c016b92a00078dce8ef156a8c4 | 699,248 |
def nastran_replace_inline(big_string, old_string, new_string):
"""Find a string and replace it with another in one big string.
In ``big_string`` (probably a line), find ``old_string`` and replace
it with ``new_string``. Because a lot of Nastran
is based on 8-character blocks, this will find the 8-character block
currently occupied by ``old_string`` and replace that entire block
with ``new_string``.
big_string, old_string, new_string: str
"""
index = big_string.find(old_string)
block = index / 8
return big_string[:8*block] + new_string.ljust(8) + \
big_string[8*block+8:] | f9955d40a74fc57674e79dd6aeea3872ffc2c87d | 699,249 |
import re
def does_support_ssl(ip):
"""Check if IP supports SSL.
Has aba sequence outside of the bracketed sections and corresponding
bab sequence inside bracketed section.
Examples:
- aba[bab]xyz supports SSL (aba outside square brackets with
corresponding bab within square brackets).
- xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
- aaa[kek]eke supports SSL (eke in supernet with corresponding kek in
hypernet; the aaa sequence is not related, because the interior
character must be different).
- zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has
a corresponding bzb, even though zaz and zbz overlap).
"""
regex = r'''(\w)(\w)\1 # aba sequence
[a-z]* # separating characters
(\[[a-z]+\][a-z]+)* # zero or more bracketed sections
# followed by characters
\[[a-z]*\2\1\2[a-z]*\] # bracketed bab
'''
regex2 = r'''\[[a-z]*(\w)(\w)\1[a-z]*\] # bracketed aba
([a-z]+\[[a-z]+\])* # zero or more bracketed sections
[a-z]* # separating characters
\2\1\2 # bab sequence
'''
has_sequence = (re.search(regex, ip, re.VERBOSE)
or re.search(regex2, ip, re.VERBOSE))
if has_sequence:
return has_sequence.group(1) != has_sequence.group(2)
return False | f46dda13d53717352fe27446d9fa3d0292d75c26 | 699,250 |
import six
import json
def meta_serialize(metadata):
"""
Serialize non-string metadata values before sending them to
Nova.
"""
return dict((key, (value if isinstance(value,
six.string_types)
else json.dumps(value))
) for (key, value) in metadata.items()) | a2ef8762c9d1b3d78dc401996392df0985c1c226 | 699,251 |
def keep_merge(walkers, keep_idx):
"""Merge a set of walkers using the state of one of them.
Parameters
----------
walkers : list of objects implementing the Walker interface
The walkers that will be merged together
keep_idx : int
The index of the walker in the walkers list that will be used
to set the state of the new merged walker.
Returns
-------
merged_walker : object implementing the Walker interface
"""
weights = [walker.weight for walker in walkers]
# but we add their weight to the new walker
new_weight = sum(weights)
# create a new walker with the keep_walker state
new_walker = type(walkers[0])(walkers[keep_idx].state, new_weight)
return new_walker | b029bd14cab4aec2cdf8edf27a9d63c2ffbbe61e | 699,253 |
def is_nan(var) -> bool:
"""
Simple check if a variable is a numpy NaN
based on the simple check where (nan is nan) gives True but (nan == nan) gives False
"""
return not var == var | 0f91829f9b5ee3dfb22944d956066069b4a3f606 | 699,259 |
def load_instances(model, primary_keys):
"""Load model instances preserving order of keys in the list."""
instance_by_pk = model.objects.in_bulk(primary_keys)
return [instance_by_pk[pk] for pk in primary_keys] | 21f26f66047fc2b2871f77447035ba15fbf78fa7 | 699,260 |
def GetHotlistRoleName(effective_ids, hotlist):
"""Determines the name of the role a member has for a given hotlist."""
if not effective_ids.isdisjoint(hotlist.owner_ids):
return 'Owner'
if not effective_ids.isdisjoint(hotlist.editor_ids):
return 'Editor'
if not effective_ids.isdisjoint(hotlist.follower_ids):
return 'Follower'
return None | 0c03460d3e4190d4964a60a2753d31e1732b6e44 | 699,263 |
from unittest.mock import Mock
from unittest.mock import patch
def mock_gateway_fixture(gateway_id):
"""Mock a Tradfri gateway."""
def get_devices():
"""Return mock devices."""
return gateway.mock_devices
def get_groups():
"""Return mock groups."""
return gateway.mock_groups
gateway_info = Mock(id=gateway_id, firmware_version="1.2.1234")
def get_gateway_info():
"""Return mock gateway info."""
return gateway_info
gateway = Mock(
get_devices=get_devices,
get_groups=get_groups,
get_gateway_info=get_gateway_info,
mock_devices=[],
mock_groups=[],
mock_responses=[],
)
with patch("homeassistant.components.tradfri.Gateway", return_value=gateway), patch(
"homeassistant.components.tradfri.config_flow.Gateway", return_value=gateway
):
yield gateway | 6404cb18ce9dd0e97b33958958d7851ee5739bed | 699,264 |
from typing import Any
def function_sig_key(
name: str,
arguments_matter: bool,
skip_ignore_cache: bool,
*args: Any,
**kwargs: Any,
) -> int:
"""Return a unique int identifying a function's call signature
If arguments_matter is True then the function signature depends on the given arguments
If skip_ignore_cache is True then the ignore_cache kwarg argument is not counted
in the signature calculation
"""
function_sig = name
if arguments_matter:
for arg in args:
function_sig += str(arg)
for argname, value in kwargs.items():
if skip_ignore_cache and argname == 'ignore_cache':
continue
function_sig += str(value)
return hash(function_sig) | bfec647db5d819fb87cf3a227927acd5cd6dda10 | 699,267 |
import time
def date_file_name(name):
"""Generate file name with date suffix."""
time_str = time.strftime("%Y%m%d-%H%M%S")
return name + "_" + time_str | 40e37e2a5dbc0208421f797bc2ae349414b05e4e | 699,271 |
def compute_efficiency_gap(partition):
"""
Input is a gerrychain.Partition object
with voteshare and population data.
It is assumed that `add_population_data` and
`add_voteshare_data` have been called on
the given partition's GeoDataFrame.
Returns the efficiency gap of
the districting plan from the GOP perspective:
(gop_wasted_votes - dem_wasted_votes) / total_votes.
Reference: Stephanopoulos and McGhee.
"Partisan gerrymandering and the efficiency gap." 2015.
"""
k = len(partition.parts)
gop_wasted_votes = 0
dem_wasted_votes = 0
for i in range(1, k + 1):
gop_votes = partition['gop_votes'][i]
dem_votes = partition['dem_votes'][i]
if gop_votes > dem_votes:
gop_wasted_votes += gop_votes - 0.5 * (gop_votes + dem_votes)
dem_wasted_votes += dem_votes
else:
gop_wasted_votes += gop_votes
dem_wasted_votes += dem_votes - 0.5 * (gop_votes + dem_votes)
# Using total population as a proxy for total_votes for simplicity
total_votes = partition.graph.data.population.sum()
return (gop_wasted_votes - dem_wasted_votes) / total_votes | 2982fe1b2f570c8eca27fade8915e9b117397cd1 | 699,272 |
import requests
import json
def updateData(url):
"""
Returns the symbol and the price of an asset.
Parameters
-----------
url: url used for information retrieval
Returns
-----------
tuple
(symbol name, symbol price)
"""
res = requests.get(url);
text = res.text;
text = text[5:];
jsonData = json.loads(text);
symbolName = jsonData["PriceUpdate"][0][0][0][17][1];
symbolPrice = jsonData["PriceUpdate"][0][0][0][17][4];
print('{0} - {1}'.format(symbolName, symbolPrice));
return (symbolName, symbolPrice); | b458dee9da7700f5c4f82a182724bba007c7a05f | 699,273 |
def has_phrase(message: str, phrases: list):
""" returns true if the message contains one of the phrases
e.g. phrase = [["hey", "world"], ["hello", "world"]]
"""
result = False
for i in phrases:
# if message contains it
i = " ".join(i)
if i in message:
result = True
return result | f56fcc261e21c538f1f23b811e14ae29d92f3038 | 699,276 |
def check_output(solution: str, output: str) -> bool:
"""Check if program's output is correct.
Parameters
----------
solution
Sample output taken from BOJ.
output
Output from program run.
Returns
-------
bool
True if correct, False if wrong.
"""
solution_lines = [x.rstrip() for x in solution.rstrip().split("\n")]
output_lines = [x.rstrip() for x in output.rstrip().split("\n")]
return all([x == y for x, y in zip(solution_lines, output_lines)]) | 66d35952d892842bd1b47329bfa7b77e0a878a51 | 699,278 |
from typing import Sequence
def bit_array_to_int(bit_array: Sequence[int]) -> int:
"""
Converts a bit array into an integer where the right-most bit is least significant.
:param bit_array: an array of bits with right-most bit considered least significant.
:return: the integer corresponding to the bitstring.
"""
output = 0
for bit in bit_array:
output = (output << 1) | bit
return output | d902a8e3db7b65ad348ef86cbfac371361aedd58 | 699,279 |
import math
def euclidean_distance(p1, p2):
"""Calculate the euclidean distance of two 2D points.
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': 3})
3.0
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': -3})
3.0
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 3, 'y': 4})
5.0
"""
return math.sqrt((p1["x"] - p2["x"]) ** 2 + (p1["y"] - p2["y"]) ** 2) | 8cdc0e0534b2ed9272832fc0f977b9aa0e594c65 | 699,281 |
import zlib
def zlib_handler(method):
"""
Prepare hash method and seed depending on CRC32/Adler32.
:param method: "crc32" or "adler32".
:type method: str
"""
hashfunc = zlib.crc32 if method == "crc32" else zlib.adler32
seed = 0 if method == "crc32" else 1
return hashfunc, seed | 46e9d91e5ebe92f3b5b24f138ae693368128ce09 | 699,283 |
def delete_container(client, resource_group_name, name, **kwargs):
"""Delete a container group. """
return client.delete(resource_group_name, name) | d69c3fbd89ce684942af4980ca9931908b12db6a | 699,289 |
def unmatched_places(w, open, close):
"""
Given a word ``w`` and two letters ``open`` and
``close`` to be treated as opening and closing
parentheses (respectively), return a pair ``(xs, ys)``
that encodes the positions of the unmatched
parentheses after the standard parenthesis matching
procedure is applied to ``w``.
More precisely, ``xs`` will be the list of all ``i``
such that ``w[i]`` is an unmatched closing parenthesis,
while ``ys`` will be the list of all ``i`` such that
``w[i]`` is an unmatched opening parenthesis. Both
lists returned are in increasing order.
EXAMPLES::
sage: from sage.combinat.tableau import unmatched_places
sage: unmatched_places([2,2,2,1,1,1],2,1)
([], [])
sage: unmatched_places([1,1,1,2,2,2],2,1)
([0, 1, 2], [3, 4, 5])
sage: unmatched_places([], 2, 1)
([], [])
sage: unmatched_places([1,2,4,6,2,1,5,3],2,1)
([0], [1])
sage: unmatched_places([2,2,1,2,4,6,2,1,5,3], 2, 1)
([], [0, 3])
sage: unmatched_places([3,1,1,1,2,1,2], 2, 1)
([1, 2, 3], [6])
"""
lw = len(w)
places_open = []
places_close = []
for i in range(lw):
letter = w[i]
if letter == open:
places_open.append(i)
elif letter == close:
if places_open == []:
places_close.append(i)
else:
places_open.pop()
return places_close, places_open | cfd2a50c50cecc6fcc08d4fd95df56ad503fa4d2 | 699,290 |
def _clip(n: float) -> float:
"""
Helper function to emulate numpy.clip for the specific
use case of preventing math domain errors on the
acos function by "clipping" values that are > abs(1).
e.g. _clip(1.001) == 1
_clip(-1.5) == -1
_clip(0.80) == 0.80
"""
sign = n / abs(n)
if abs(n) > 1:
return 1 * sign
else:
return n | 78308e70a405b3b3d94827c00705e8842b242cde | 699,291 |
import math
def line_intersect(pt1, pt2, ptA, ptB):
"""
Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html
this returns the intersection of Line(pt1,pt2) and Line(ptA,ptB)
returns a tuple: (xi, yi, valid, r, s), where
(xi, yi) is the intersection
r is the scalar multiple such that (xi,yi) = pt1 + r*(pt2-pt1)
s is the scalar multiple such that (xi,yi) = pt1 + s*(ptB-ptA)
valid == 0 if there are 0 or inf. intersections (invalid)
valid == 1 if it has a unique intersection ON the segment
"""
DET_TOLERANCE = 0.00000001
# the first line is pt1 + r*(pt2-pt1)
# in component form:
x1, y1 = pt1
x2, y2 = pt2
dx1 = x2 - x1
dy1 = y2 - y1
# the second line is ptA + s*(ptB-ptA)
x, y = ptA
xB, yB = ptB
dx = xB - x
dy = yB - y
# we need to find the (typically unique) values of r and s
# that will satisfy
#
# (x1, y1) + r(dx1, dy1) = (x, y) + s(dx, dy)
#
# which is the same as
#
# [ dx1 -dx ][ r ] = [ x-x1 ]
# [ dy1 -dy ][ s ] = [ y-y1 ]
#
# whose solution is
#
# [ r ] = _1_ [ -dy dx ] [ x-x1 ]
# [ s ] = DET [ -dy1 dx1 ] [ y-y1 ]
#
# where DET = (-dx1 * dy + dy1 * dx)
#
# if DET is too small, they're parallel
#
DET = (-dx1 * dy + dy1 * dx)
if math.fabs(DET) < DET_TOLERANCE: return (0, 0, 0, 0, 0)
# now, the determinant should be OK
DETinv = 1.0 / DET
# find the scalar amount along the "self" segment
r = DETinv * (-dy * (x - x1) + dx * (y - y1))
# find the scalar amount along the input line
s = DETinv * (-dy1 * (x - x1) + dx1 * (y - y1))
# return the average of the two descriptions
xi = (x1 + r * dx1 + x + s * dx) / 2.0
yi = (y1 + r * dy1 + y + s * dy) / 2.0
return (xi, yi, 1, r, s) | 73ffd9674302f3be7b0edd9cdddd95df198919cb | 699,295 |
def render_icon(icon):
"""
Render a Bootstrap glyphicon icon
"""
return '<span class="glyphicon glyphicon-{icon}"></span>'.format(icon=icon) | 4fcc501cbea07d3dbe99f35f63dc39c8f629c4c4 | 699,296 |
import binascii
def hex_to_bytes(hex_repn: str) -> bytes:
"""
Convert a hexidecimal string representation of
a block of bytes into a Pyton bytes object.
This function is the inverse of bytes_to_hex.
hex_to_bytes('F803') -> b'\xf8\x03'
"""
return binascii.unhexlify(hex_repn) | 2c456a353e1cce75998d1b2dd9b077af962ee41d | 699,297 |
import re
def get_text_url_base(content):
"""Return base URL to full text based on the content of the landing page.
Parameters
----------
content : str
The content of the landing page for an rxiv paper.
Returns
-------
str or None
The base URL if available, otherwise None.
"""
match = re.match('(?:.*)"citation_html_url" content="([^"]+).full"',
content, re.S)
if match:
return match.groups()[0]
return None | c679e9e1e8b074f7fea3aaf9eb256542e20a4d7d | 699,298 |
def calculateMatchValue(incompleteObject, knownObject):
"""Calculate an integer match value, scoring +1 for each match"""
matchvalue = 0
for catkey, catval in incompleteObject.items():
if knownObject[catkey] == catval:
matchvalue += 1
return matchvalue | bd0efa089fa9edc2e290a46ca7e18b3d22bd1594 | 699,299 |
def get_contents_dir(node):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
for n in sorted(node.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(contents) | 147d26ae5fca9540a081feef495dfa4bb0fca8eb | 699,302 |
def two_way_merge(array1, array2):
"""
Given two sorted arrays, merge them into a single sorted array.
This is a very simple operation but is a precursor to k-way merge.
We compare each element at the beginning of each array and remove smaller one and add it to the merged array.
If one of the arrays run out of elements, we just copy rest of the other array into the merged array and return.
Time Complexity: O(n) - Since we only need to do one comparison operation per element.
Auxiliary Space: O(n) - We will store the final sorted data in an array of size O(n),
which is the combined length of the given arrays.
If you want to see the fully animated video explanation, it is here: https://www.youtube.com/watch?v=Xo54nlPHSpg
:param array1: A sorted array of values.
:param array2: Another sorted array of values.
:return: A single sorted array.
"""
longer_arr_len = len(array1) + len(array2)
merged_arr = []
for i in range(longer_arr_len):
if len(array1) == 0:
merged_arr += array2
break
if len(array2) == 0:
merged_arr += array1
break
if array1[0] < array2[0]:
merged_arr.append(array1.pop(0))
else:
merged_arr.append(array2.pop(0))
return merged_arr | 6d1a4779634809b7ff63159928af668596f5c00e | 699,304 |
def wavelength_to_energy(wavelength: float):
"""Conversion from photon wavelength (angstroms) to photon energy (eV)"""
return 1.2398 / wavelength * 1e4 | fc067b9fd9cae68103742e8998b6aa0117d906d0 | 699,306 |
import threading
def concurrent_map(func, data):
"""
Similar to the bultin function map(). But spawn a thread for each argument
and apply `func` concurrently.
Note: unlike map(), we cannot take an iterable argument. `data` should be an
indexable sequence.
"""
N = len(data)
result = [None] * N
# wrapper to dispose the result in the right slot
def task_wrapper(i):
result[i] = func(data[i])
threads = [threading.Thread(target=task_wrapper, args=(i,)) for i in range(N)]
for t in threads:
t.start()
for t in threads:
t.join()
return result | 5fb482055699087ca7f7b3b95b7d8c425894882f | 699,308 |
def van_vleck_weisskopf(νeval, ν, γ, δ):
"""Complex Van Vleck-Weisskopf line shape function.
νeval GHz frequency at which line shape is evaluated
ν GHz center frequency of line
γ GHz width parameter of line
δ - overlap parameter of line
Returned value is unitless.
"""
term1 = (1. - 1j*δ)/(ν - νeval - 1j*γ)
term2 = (1. + 1j*δ)/(ν + νeval + 1j*γ)
return νeval * (term1 - term2) | f2f221196fbe911d4582cfc74bf260bb87ce7db0 | 699,310 |
import re
def is_valid_username(field):
"""
Checks if it's an alphanumeric + underscore, lowercase string, at least
two characters long, and starts with a letter, ends with alphanumeric
"""
return re.match(r"[a-z][0-9a-z_]*[a-z0-9]$", field) is not None | b4c870951715e103d58d1187703276dbb21e84cf | 699,313 |
def select_number(list_of_numbers):
"""The player select *one* number of a list of numbers"""
answer = ""
while ((not answer.isdecimal()) or int(answer) not in list_of_numbers):
answer = input("Please type selected number and press ENTER: ")
return int(answer) | af91b18508ff361b0524a551949aac7d93f9afc6 | 699,324 |
def cast(s):
""" Function which clarifies the implicit type of
strings, a priori coming from csv-like files.
Example
-------
>>> cast('1')
1
>>> cast('1.')
1.0
>>> cast('1E+0')
1.0
>>> cast('1E+1')
10.0
>>> cast('one')
'one'
>>> cast('One')
'one'
"""
s = str(s)
try:
float(s)
if '.' in s or 'E' in s:
return float(s)
else:
return int(s)
except:
return s.lower() | 5e2c9b3b913a733608cab614ae0f08421e489196 | 699,326 |
def is_macosx_sdk_path(path):
"""
Returns True if 'path' can be located in an OSX SDK
"""
return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/') | 59b60fa00bf6dd10cf207e6421ea3e4828de5b9c | 699,327 |
import math
def _mean_standard(dist):
"""Find the mean and standard deviation."""
# In the dist dictionary, the key is the value of the metric and
# the value is the number of times it appears. So, the sample
# value is the key and the number of samples for the value is the
# value in dist for that key.
total_samples = sum(dist.values())
total_values = sum(key*value
for key, value in dist.items())
mean = total_values/total_samples
std_squared = sum((value/total_samples) * (key - mean)**2
for key, value in dist.items())
std = math.sqrt(std_squared)
return mean, std | 3d90807a619b6fe090571a3f07db807e60c3849c | 699,328 |
def shift2d(x,w,a,b):
"""Shift a 2d quadrature rule to the box defined by the tuples a and b"""
xs=[[a[0]],[a[1]]]+x*[[b[0]-a[0]],[b[1]-a[1]]]
ws=w*(b[0]-a[0])*(b[1]-a[1])
return xs,ws | 84c2090cc0e1689a79aa2c7fa40fb399bc03f535 | 699,329 |
def effective_kernel(kernel_shape, dilations):
"""
Args:
kernel_shape: tuple[int] representing the kernel shape in each
given dimension.
dilations: tuple[int] representing the dilation of the kernel
in each given dimension. Must be the same length as
kernel_shape, and is assumed to give the dimensions in
the same order as kernel_shape
Returns: tuple[int] representing the effective shape of the kernel
in each given dimension, with each dimension in the order given,
taking into account dilation.
See http://deeplearning.net/software/theano/tutorial/conv_arithmetic.html#dilated-convolutions
Note that a dilation of 1 is equivalent to having no dilation.
"""
if len(kernel_shape) != len(dilations):
raise ValueError(
"kernel_shape ({}) and dilations ({}) must be the same length".format(
len(kernel_shape), len(dilations)
)
)
return [(k - 1) * d + 1 for k, d in zip(kernel_shape, dilations)] | a955d185c924514bf981c2512a8e78646d523144 | 699,333 |
def int_from_32bit_array(val):
"""Converts an integer from a 32 bit bytearray
:param val: the value to convert to an int
:type val: int
:rtype: int
"""
rval = 0
for fragment in bytearray(val):
rval <<= 8
rval |= fragment
return rval | ca2f32c7eac6f42aeed688510fa57e717edfacdf | 699,334 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.