content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def unpack_shard(shard):
"""Unpack what pack_shard() did."""
replica = (shard & SHARD_REPLICA_MASK) >> SHARD_REPLICA_SHIFT
writer = (shard & SHARD_WRITER_MASK)
return (replica, writer) | 5,292,200 |
def set_if_chain(tree: ast.AST) -> ast.AST:
"""
Used to create ``if`` chains.
We have a problem, because we cannot tell which situation is happening:
.. code:: python
if some_value:
if other_value:
...
.. code:: python
if some_value:
...
... | 5,292,201 |
def poly(n, force_zero=None, **kwargs):
"""Returns a fit function that is a polynomial of degree n
y(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n
"""
if force_zero is None and len(kwargs) == 0:
# noinspection PyUnusedLocal
def pf(x, params, const_list, const_dict):
return... | 5,292,202 |
def symptom_unreasonable_max_token_size():
"""`keystone.conf [DEFAULT] max_token_size` should be adjusted.
This option is intended to protect keystone from unreasonably sized tokens,
where "reasonable" is mostly dependent on the `keystone.conf [token]
provider` that you're using. If you're using one of... | 5,292,203 |
def cli():
""" does the thing... """
dir_to_check = get_dir_to_check()
found_repo = False
logger.debug("Checking {}", dir_to_check)
for filename in os.listdir(dir_to_check):
dirpath = os.path.normpath(f"{dir_to_check}/{filename}")
if os.path.isdir(dirpath):
logger.debug(... | 5,292,204 |
def delete_channel(_, slug):
"""Unsubscribe from a channel"""
if models.YoutubeChannel.objects.filter(slug=slug).exists():
channel = models.YoutubeChannel.objects.get(slug=slug)
channel.delete()
return redirect("notifpy:home") | 5,292,205 |
def multisign_archive(archive, cred_dirs_to_output_paths, info_props=None):
""" Given an isign.archive object,
a mapping of credential directories to desired output paths,
optional info.plist properties to overwrite,
produce re-signed versions of the IPA.
If info_props are provided... | 5,292,206 |
def xml_parser(root, project_id, scan_id):
"""
:param root:
:param project_id:
:param scan_id:
:return:
"""
global ScanName, \
ScanShortName, ScanStartURL, \
ScanStartTime, \
ScanFinishTime, \
ScanScanTime, \
ScanAborted, \
ScanResponsive, \
... | 5,292,207 |
def MakePDBAtomRecord(pdbmol,i):
""" Make string for PDB 'ATOM' record.
:param lst pdbmol: pdbmol data
:param int i: i-th atom
:return: string(str) - PDB 'ATOM' record
"""
blk=' '; fi4='%4d'; fi3='%3d'; fi2='%2d'; fi5='%5d'; ff8='%8.3f'; ff6='%6.2f'
s=blk*80; ires=0
seq... | 5,292,208 |
def sliding_window(sequence, window_size, step_size):
"""Converts a sequence into sliding windows. Returns a list of sequences.
- sequence: a string containing only nucleotides.
- window_size: Windows of equal size sequence. Default is 500 bp.
- step_size: overlap required for sliding windows. Default is... | 5,292,209 |
def get_wiki_folder(config, lecture_num, course):
"""
Return tuple of (lecture file location, markdown images path)
"""
tri = get_tri_from_course(course, config['courses'])
lecture_path = os.path.join(config['wiki-root'], "Uni", tri.capitalize(), course, "Lectures")
images_path = os.path.join(lecture_path,... | 5,292,210 |
def api_contests_join():
"""
Join/Leave a contest, GET all contests a user is in
"""
if request.method == 'GET':
user = get_queryparam('user')
returnJSON = models.select_joined_contest(
params=('*'),
conditions=('{}=\"{}\"'.format(
settings.DB_... | 5,292,211 |
def feat_numc_window(cmap, winsize=3, score_threshold=0.2):
""" Get distribution over number of contacts in certain window,
where the window is a 2d field around each contacts.
The distribution is represented as an array of counts for each
number of contacts with in the window (i.e. length=winsize^2)
... | 5,292,212 |
def expand_item(range_list, onepass=False):
""" Expand a list of plugin:parameters into a list of hosts """
if isinstance(range_list, str):
range_list = [range_list]
# Iterate through our list
newlist = []
found_plugin = False
for item in range_list:
# Is the item a plugin
... | 5,292,213 |
def load_csv(filename, sep=None, header=None):
"""Opens and parses provided csv file returning the data and info for all regions
as a list of Region objects. Since no experimental information is provided in the free-form text file,
The experimental properties are set to physically miningless defaults.
T... | 5,292,214 |
def print_devices(detail_level=0):
"""
Print all platforms and device available, optionall with detailed
device information.
Parameters
----------
details : int
If >0, the function also prints device properties. Higher
levels correspond to more (and less important) detail.
... | 5,292,215 |
def create_2dlist():
"""
create 2d list used for gamefield
"""
return [[0 for _ in range(config.NR_COLS)] for _ in range(config.NR_ROWS)] | 5,292,216 |
def Huge():
"""
Return the largest positive integer that can be stored (before a long integer
is needed)
"""
if not hasattr(Huge, "_huge"):
# If we haven't yet calculated Huge, calculate it
Huge._huge = 1
while True:
newHuge = Huge._huge * 2
if isinstance(newHuge, int):
Huge... | 5,292,217 |
def get_next_player_move(state, gui):
"""Uses input to get the next move by a human"""
def is_valid_move(state, x):
if x == '':
return False, '\n'
s = x.split(',')
if len(s) != state.ndim:
return False, 'Not the correct number of dimensions.\n'
s2 = [int(... | 5,292,218 |
def test_write_config_file(datadir, tmpdir):
"""Test for writing configuration file"""
input_fn = "../data/input/example01.fastq"
sample_fn = "../data/input/example01.txt"
gb_fn = "../data/input/ES114v2.gb"
output_name = "test_pyinseq"
expected_config = datadir("input/test-pyinseq-config.yml")
... | 5,292,219 |
async def dyno_usage(dyno):
"""
Get your account Dyno Usage
"""
await dyno.edit("```Checking dynos ✨```")
await asyncio.sleep(1)
useragent = (
'Mozilla/5.0 (Linux; Android 10; SM-G975F) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/81.0.4044.117 Mobile Safari/53... | 5,292,220 |
def test_1():
"""Test prev_mt_alg.sog_grad() for d = 2."""
d = 2
p = 3
sigma_sq = 0.05
store_c = np.zeros((p, ))
store_rotation = np.zeros((p, d, d))
store_A = np.zeros((p, d, d))
store_x0 = np.zeros((p, d))
store_c[0] = 0.5
store_c[1] = 0.6
store_c[2] = 0.7
store_rota... | 5,292,221 |
def get_kssk(fh5, remove_bragg=False):
"""Retrieve determinant S(k) from HDF5 archive
Args:
fh5 (str): hdf5 archive
remove_bragg (bool, optional): remove Bragg peaks
Return:
(np.array, np.array, np.array): raxes, gvecs, sk0a
reciprocal lattice, integer vectors, twist-resolved S(k)
"""
impor... | 5,292,222 |
def unravel_trimat( raveled, unravelIndices, shape=None ):
"""
Undo's a
Note: if shape = None, M,N are taken to be the maximum values in the matrix, so if there's zero columns
on the right, or zero rows on the bottom, they will be cropped in the returned triangular matrix.
"""
if s... | 5,292,223 |
def index_snps(snpeff_file):
"""indexes the snps"""
success, errors = helpers.bulk(es,_get_snps_document(snpeff_file), stats_only=True, chunk_size=10000)
return success, errors | 5,292,224 |
def raster_path_shape(raster_path):
"""Return the number of rows and columns in a raster
Args:
raster_path (str): file path of the raster
Returns:
tuple of raster rows and columns
"""
raster_ds = gdal.Open(raster_path, 0)
raster_shape = raster_ds_shape(raster_ds)
raster_ds... | 5,292,225 |
def set_invoiced_flag(order_id: OrderID, initiator_id: UserID) -> None:
"""Record that the invoice for that order has been (externally) created."""
db_order = _get_order_entity(order_id)
initiator = user_service.get_user(initiator_id)
now = datetime.utcnow()
event_type = 'order-invoiced'
data =... | 5,292,226 |
def mongo_to_dict(obj, exclude_fields=list()):
"""
Convert Document of MongoEngine's instance to dictionary type
:param obj: Document of MongoEngine
:param exclude_fields: field names for exclude
"""
exclude_fields.append('_cls')
return_data = {}
if obj is None:
return None
... | 5,292,227 |
def reconstruct_path(goal, branch, waypoint_fn):
"""
Reconstruct a path from the goal state and branch information
"""
current_node = goal
path = [current_node]
while current_node is not None:
previous_node = branch[waypoint_fn(current_node)]
path.append(previous_node)
cu... | 5,292,228 |
def pt_acfg(**kwargs):
""" Architecture Config (PyTorch model origin) """
bn_cfg = kwargs.pop('bn_cfg', None) or get_bn_args_pt()
return {'pad_type': 'LIKE', 'bn_cfg': bn_cfg, **kwargs} | 5,292,229 |
def nvidia_smi_current_gpu(): # pragma: no cover
"""Returns GPU ID used by the process.
(tested locally, cannot be tested on Travis CI bcs no GPU available)
Returns
-------
int
[MiB]
"""
# if theano.config.device=='cpu': return -2
try:
xm... | 5,292,230 |
def main():
"""
run code
"""
# variables
predict = Predict()
# load model
lstm = load_model("lstm_model.h5")
countries, X = predict.get_data()
data = predict.predict(countries, X, lstm)
# save to db
predict.load(data) | 5,292,231 |
def prw(value):
"""Writer share, PR"""
return calculate_value(value, PRW_SHARE) | 5,292,232 |
def get_vehicle_marker(object, header, marker_id=0, is_player=False):
"""
Return a marker msg
:param object: carla agent object (pb2 object (vehicle, pedestrian or traffic light))
:param header: ros header (stamp/frame_id)
:param marker_id: a marker id (int32)
:param is_player: True if player e... | 5,292,233 |
def default_ssl_cacerts():
"""Path to default Certificate Authority certificates"""
return SSL_CACERTS.get() | 5,292,234 |
def vectornormalization(surface, inputarray, outputarray, iscelldata=False):
"""Add data array with the normalization of a vector field."""
calc = vtk.vtkArrayCalculator()
calc.SetInput(surface)
if iscelldata:
calc.SetAttributeModeToUseCellData()
calc.AddVectorArrayName(inputarray, 0, ... | 5,292,235 |
async def fetch_file(url, path, session):
"""Fetch image files, preserve "last-mofidifed" time."""
time = None
async with session.get(url) as response:
if "Last-Modified" in response.headers:
time = email.utils.mktime_tz(
email.utils.parsedate_tz(response.headers["Last-Mo... | 5,292,236 |
def format_df(df, mhe):
"""Make a weak labels dataframe from strongly labeled (join labels)
Args:
df: pd.DataFrame, the dataframe strongly labeled with onset and offset columns (+ event_label)
mhe: ManyHotEncoder object, the many hot encoder object that can encode the weak labels
Returns:
... | 5,292,237 |
def create_judgment_matrix(N,T,layers,v_r=[],actions=[],judgment_type="OPTIMISTIC"):
"""Creates a functionality map for input into the functionality parameter in the indp function.
:param N: An InfrastructureNetwork instance (created in infrastructure.py)
:param T: Number of timesteps to optimize over.
... | 5,292,238 |
def vertically_partition_data(X, X_test, A_idx, B_idx):
"""
Vertically partition feature for party A
and B
:param X: train feature
:param X_test: test feature
:param A_idx: feature index of party A
:param B_idx: feature index of party B
:return: train data for A, B; test data for... | 5,292,239 |
def type_instantiate(attr_type: Type, **kwargs) -> Any:
"""
Instantiate a nominated type.
"""
while hasattr(attr_type, "__origin__"):
attr_type = attr_type.__origin__
return attr_type(**kwargs) | 5,292,240 |
def dropMongoDbCollections():
"""
Empties a number of MongoDB collections after each test function
"""
yield
with app.app.app_context():
Descriptor.objects.delete()
Service.objects.delete() | 5,292,241 |
def eval_tau(J, r, chieff, q, chi1, chi2, precomputedroots=None):
"""
Period of S as it oscillates from S- to S+ and back to S-.
Call
----
tau = eval_tau(J,r,chieff,q,chi1,chi2,precomputedroots=None)
Parameters
----------
J: float
Magnitude of the total angular momentum.
r:... | 5,292,242 |
def make_change_dep_eval(dep,):
"""Produce an evaluation function that returns True if any change has happened on any occurence of the given dep"""
def change_dep_eval(orig,modif):
s1 = get_pairs(orig, dep)
s2 = get_pairs(modif, dep)
return s1 != s2, bool(s1)
return change_dep_eval | 5,292,243 |
def get_verse_id(book: Book, chapter: int, verse: int) -> int:
"""
Given the Book enum, chapter number int, and verse number int return the verse id if it exists.
:param book:
:param chapter:
:param verse:
:return: the integer verse id for the given book, chapter, and verse
"""
# Not o... | 5,292,244 |
def get_fitness(cell_type,cell_neighbour_types,DELTA,game,game_params):
"""returns fitness of single cell"""
return 1+DELTA*game(cell_type,cell_neighbour_types,*game_params) | 5,292,245 |
def _ClearCachedCollectionData(collection: bpy.types.bpy_prop_collection, collectionTypeName: str = "object"):
"""
Generic function that can clear the content of any collection in the scene.
"""
dataNames = []
for name in collection.keys():
dataNames.append(name)
if len(dataNames) > 0:
... | 5,292,246 |
def patch_resource(url, body):
"""
Patch resource with the given json body
:returns: http response data
"""
timer = Timer()
response = Bridge_DAO().patchURL(url, PHEADER, body)
log_data = "PATCH %s %s ==status==> %s" % (url, body, response.status)
if not response.status == 200:
... | 5,292,247 |
def fetch_core_sketch(X, ss, **kwargs_rg):
"""
:param X: the tensor of dimension N
:param ks: array of size N
:param tensor_proj: True: use tensor random projection,
otherwise, use normal one
:return: [core_sketch:s_n\times s_n ...\times s_n,
list of sketches phis, s_n\times I_n]
"""
... | 5,292,248 |
def test_simplify():
"""Test simplification of expr according to manual rules"""
h1 = LocalSpace("h1")
a = OperatorSymbol("a", hs=h1)
b = OperatorSymbol("b", hs=h1)
c = OperatorSymbol("c", hs=h1)
d = OperatorSymbol("d", hs=h1)
expr = 2 * (a * b * c - b * c * a)
A_ = wc('A', head=Operat... | 5,292,249 |
def linear_quantize_callback(
inp: torch.Tensor,
bits: int = 8,
decimal: TensorOrInt = 5,
channel_index: int = 1,
) -> torch.Tensor:
"""quantization function with type signature of [QuantizeCallback][qsparse.common.QuantizeCallback].
Args:
inp (torch.Tensor): input tensor
bits (... | 5,292,250 |
def h2o_H2OFrame_asfactor():
"""
Python API test: h2o.frame.H2OFrame.asfactor()
Copied from pyunit_ascharacter.py
"""
h2oframe = h2o.import_file(path=pyunit_utils.locate("smalldata/junit/cars.csv"))
newFrame = h2oframe['cylinders'].asfactor()
assert_is_type(newFrame, H2OFrame)
assert ... | 5,292,251 |
def _set_parallel_all_reduce_split():
"""set centernet all_reduce fusion split"""
if net_config.last_level == 5:
context.set_auto_parallel_context(
all_reduce_fusion_config=[16, 56, 96, 136, 175])
elif net_config.last_level == 6:
context.set_auto_parallel_context(
all... | 5,292,252 |
def test_ItemsQueryType_truncates_page_size():
"""ItemsQueryType truncates a page_size greater than 500 to 500
This is not ideal, but it's what the API has always done.
"""
x = types.ItemsQueryType({'page_size': '501'})
assert x['page_size'] == 500 | 5,292,253 |
def parse_post(content):
"""
parse response content
:param content: string
:return: Dict
"""
# parse content
soup = BeautifulSoup(content, 'lxml')
# get title
mainTitle = soup.find('div', {'id': 'mainTitle'})
title = mainTitle.find('h1').text
# get publish date time
... | 5,292,254 |
def monkey_patch_py2neo_v2():
# type: () -> None
"""Install compat code into py2neo v2 mod namespace & objects."""
import py2neo.core
import py2neo.cypher.core
py2neo.Record = py2neo.cypher.core.Record
py2neo.ServerError = py2neo.core.ServerError
py2neo.URI = py2neo.core.URI | 5,292,255 |
def GoogleAccountsLogin(test, username, password, tab_index=0, windex=0):
"""Log into Google Accounts.
Attempts to login to Google by entering the username/password into the google
login page and click submit button.
Args:
test: derived from pyauto.PyUITest - base class for UI test cases.
username: us... | 5,292,256 |
def get_ocean_token_address(
address_file: str, network: Optional[str] = None, web3: Optional[Web3] = None
) -> str:
"""Returns the Ocean token address for given network or web3 instance
Requires either network name or web3 instance.
"""
addresses = get_contracts_addresses(
address_file, net... | 5,292,257 |
async def test_update_interval(hass, aioclient_mock):
"""Test correct update interval when the number of configured instances changes."""
REMAINING_RQUESTS = 15
HEADERS = {
"X-RateLimit-Limit-day": "100",
"X-RateLimit-Remaining-day": str(REMAINING_RQUESTS),
}
entry = MockConfigEntry... | 5,292,258 |
def _get_relevant_items_by_timestamp(
dataframe,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_timestamp=DEFAULT_TIMESTAMP_COL,
col_prediction=PREDICTION_COL,
k=DEFAULT_K
):
"""Get relevant items for each customer def... | 5,292,259 |
def wait_device_ops(devices=None):
"""Waits for all the async operations on the given devices to complete.
Args:
devices (string..., optional): The devices whose async ops need to be waited
for. If empty, all the local devices will be waited for.
"""
if devices is None:
devices = [... | 5,292,260 |
def check_encryption(value):
"""
check for the --???-encryption argument
raise an exception if the given encryption is invalid
"""
value = value.lower()
if value not in ['ssl', 'tls', 'starttls', 'none']:
raise ArgumentTypeError(f'{value} is an unknown encryption. Use can use ssl... | 5,292,261 |
def ENsaveinpfile(fname):
"""Writes all current network input data to a file using the format of an
EPANET input file.
Arguments
---------
fname: name of the file where data is saved
"""
ierr = _lib.ENsaveinpfile(ctypes.c_char_p(fname.encode()))
if ierr:
raise ENtoolkitError(ier... | 5,292,262 |
def demo():
""" _test_pipeline
This demo demonstrates the Pipeline structure seemingly working as a
learner, while being passed as parameter to an EvaluatePrequential
object.
"""
# # Setup the stream
# stream = FileStream("../data/datasets/covtype.csv", -1, 1)
# stream.prepa... | 5,292,263 |
def FloatSlider(
continuous_update: bool = True,
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
max: float = 100.0,
min: float = 0.0,
orientation: str = "horizontal",
... | 5,292,264 |
def _apply_feature_constraints(feature, min_value, max_value):
"""Constrains `feature` to be between `min_value` and `max_value`."""
if min_value is not None:
feature = tf.math.maximum(feature, min_value)
if max_value is not None:
feature = tf.math.minimum(feature, max_value)
return feature | 5,292,265 |
def configure_global_stackwise_virtual(device, domain=None):
""" Enables global stackwise-virtual on target device
Args:
device ('obj'): Device object
domain ('str'): Stackwise-virtual domain
Returns:
None
Raises:
SubCommandFailure
"""
... | 5,292,266 |
def main(stdscr):
"""Main routine to be wrapped on curses.wrapper"""
global chat
stdscr.clear()
chat = ChatUI(stdscr)
try:
username = chat.wait_input(str(read_stream.readline().strip('\n')))
write_stream.write(username + '\n')
write_stream.flush()
inp = ""
t =... | 5,292,267 |
def create_executable_script(filepath, body, program=None):
"""Create an executable script.
Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the ... | 5,292,268 |
def main():
"""runtime code"""
lookfor = input("What pattern am I looking for (Example: *.txt or *.cfg) ")
lookwhere = input("What is the path in which I should search? ")
print("Results: ", find(lookfor, lookwhere)) | 5,292,269 |
def get_print_func(io):
"""This is a workaround go get mocking of stdout to work with
both py2 and py3.
"""
if sys.version_info[0] == 2:
return io.write
else:
return io.writelines | 5,292,270 |
def run_server(locker, register=True):
"""Runs tickets server."""
_LOGGER.info('Tickets server starting.')
# no __init__ method.
#
# pylint: disable=W0232
class TicketLockerServer(gssapiprotocol.GSSAPILineServer):
"""Ticket locker server."""
@utils.exit_on_unhandled
def... | 5,292,271 |
def verify_incall_state(log, ads, expected_status):
"""Verify phones in incall state or not.
Verify if all phones in the array <ads> are in <expected_status>.
Args:
log: Log object.
ads: Array of Android Device Object. All droid in this array will be tested.
expected_status: If Tru... | 5,292,272 |
def buildData(all_data, outPickleFile, build_dict=False, word_only=False):
"""
i
"""
n = 0
# now only handle the eds data, to extend for all other formats
eds_data = []
for id, data in all_data.items():
# try to extend this to other frameworks
if 'mrp_eds' in data:
... | 5,292,273 |
def euclidean_distance(
point: Tuple[float, float], origin: Tuple[float, float] = None
) -> float:
"""Calculate euclidean distance from the origin"""
if origin is None:
return math.sqrt(sum((p ** 2 for p in point)))
else:
assert len(origin) == len(point)
return math.sqrt(sum(((p ... | 5,292,274 |
def perspective_edit(request, perspective_id, response_format='html'):
"""Perspective edit"""
perspective = get_object_or_404(Perspective, pk=perspective_id)
# Don't let users delete their last perspective
other_perspectives = Perspective.objects.filter(
trash=False).exclude(id=perspective_id)
... | 5,292,275 |
def _extract_key(obj):
"""Convert a handle or Event handle into a Database Event ID."""
if isinstance(obj, Event):
return obj.id
elif isinstance(obj, str):
return obj
raise TypeError('Must provide an Event or Event handle (string)') | 5,292,276 |
def convolve_adjoint_filter(x, y, ndim, input_multi_channel=False,
output_multi_channel=False, mode='full'):
"""Convolution adjoint.
Args:
x (array): input array with shape batch_shape + input_shape
if input_multi_channel=False.
Otherwise with shape ... | 5,292,277 |
def _check_juniper_userfirewall(aggregator, common_tags):
"""
Shared testing function for Juniper profiles supporting userfirewall (user auth)
"""
userfirewall_tags = [
['ldap_domain_name:Mycroft Holmes', 'ldap_host:brother'],
['ldap_domain_name:Jim Moriarty', 'ldap_host:enemy'],
]
... | 5,292,278 |
def getCompletedJobs(jobs):
"""
Gets all completed jobs
"""
completed_jobs = []
for job in jobs:
if 'result' in job:
completed_jobs.append(job)
return completed_jobs | 5,292,279 |
def ts_declaration_dir_exists():
"""Ensures f5-telemetry-streaming declaration copy directory exists"""
if not os.path.isdir(TS_DECLARATION_DIR):
os.makedirs(TS_DECLARATION_DIR) | 5,292,280 |
def test_integration(aggregator, cassandra_cluster):
"""
Testing Cassandra Nodetool Integration
"""
integration = CassandraNodetoolCheck(common.CHECK_NAME, {}, {})
integration.check(common.CONFIG_INSTANCE)
aggregator.assert_metric('cassandra.nodetool.status.replication_availability', value=200,... | 5,292,281 |
def read_pergene_file(pergene_insertions_file,chrom):
"""Reading the pergene file , the information per gene , related to where it starts and ends in the genome.
Parameters
----------
pergene_insertions_file : str
absolute path of the per gene file location
chrom : str
Name of the ... | 5,292,282 |
def _inner_search(obj, glob, separator, dirs=True, leaves=False):
"""Search the object paths that match the glob."""
for path in dpath.path.paths(obj, dirs, leaves, skip=True, separator = separator):
if dpath.path.match(path, glob):
yield path | 5,292,283 |
def gam_a98rgb(rgb):
"""Convert an array of linear-light a98-rgb in the range 0.0-1.0 to gamma corrected form."""
return [math.copysign(math.pow(abs(val), 256 / 563), val) for val in rgb] | 5,292,284 |
def conflictBetweenIPv4AndIPv6():
"""
Is there a conflict between binding an IPv6 and an IPv4 port? Return True
if there is, False if there isn't.
This is a temporary workaround until maybe Twisted starts setting
C{IPPROTO_IPV6 / IPV6_V6ONLY} on IPv6 sockets.
@return: C{True} if listening on ... | 5,292,285 |
def test_write_template_should_raise_if_can_not_write_executable_output(work_dir, mocker, valid_template_path):
"""
Test write_template raise an MlVToolException if the executable output cannot be written
"""
output_path = join(work_dir, 'output.sh')
mocker.patch('builtins.open', side_effect=IO... | 5,292,286 |
def test_simple_dict_parsing():
"""Simple test for a dict."""
args = {
'a_var': Var(
use=int,
load_from='A_VAR',
),
}
values = {
'A_VAR': '0',
}
assert parse_dict(values, args) == {
'a_var': 0,
} | 5,292,287 |
def unlock_layer(wC, uC, noise=0.0):
"""
unlock a layer of a scale invariant MERA
Args:
wC, uC (list): MERA tensors
noise (float): amplitude of noise to be added to the new layer
Returns:
wC, uC (list): new MERA tensors
"""
wC.append(copy.copy(wC[-1]))
uC.append... | 5,292,288 |
def conformal2geodetic(conformal_lat: "ndarray", ell: Ellipsoid = None, deg: bool = True) -> "ndarray":
"""
converts from conformal latitude to geodetic latitude
like Matlab map.geodesy.ConformalLatitudeConverter.inverse()
Parameters
----------
conformal_lat : "ndarray"
conformal latit... | 5,292,289 |
def get_frame_subframe(sfn_sf):
""" Get the frame and the subframe number from the
received bitstring
"""
sfn_sf_list = []
frame_mask = ~((1<<4) - 1)
frame = (sfn_sf & frame_mask) >> 4
sf_mask = ~(((1<<12) - 1) << 4)
subframe = (sfn_sf & sf_mask)
sfn_sf_list.append(frame)
sf... | 5,292,290 |
def make_renderer(nodes, use_binary_transport=False):
"""Creates the pydeck visualization for rendering"""
view_state = pydeck.ViewState(
offset=[0, 0],
latitude=None,
longitude=None,
bearing=None,
pitch=None,
zoom=10,
)
views = [pydeck.View(type="OrbitVi... | 5,292,291 |
def get_secret_value(secret_name):
"""
get secret value from AWS Secrets Manager
:param secret_name: name of the secret passed
:return secret_value: value of the secret passed
"""
client = session.client(service_name='secretsmanager')
secret_value = ''
try:
get_secret_value_respo... | 5,292,292 |
def true_positive_fraction(output, target):
"""True positive fraction of binary segmentation."""
output, target, was_numpy = _convert_to_torch(output, target)
result = _true_positives(output, target) / (torch.sum(output) + torch.sum(target))
return _convert_to_scalar(result, was_numpy) | 5,292,293 |
def backend_parameter(func):
"""Decorator for parameters reading data from the backend.
Errors are handled in a default way.
"""
def _func_wrapper(self: 'VehicleState', *args, **kwargs):
# pylint: disable=protected-access
if self._attributes is None:
raise ValueError('No dat... | 5,292,294 |
def _build_freetext_query(querystring):
"""
Parses the freetext argument 'nyckelord' in the following ways:
'word1 AND word2' => word1 and word2
'"word1"AND"word2"' => word1 and word2
'"word1 word2"' => word1 and word2
'word1 OR word2' => word1 or word2
'"word1"OR"word2"' => word1 or word2
... | 5,292,295 |
def get_course_list(only_active=True, sortedby="name"):
""" Return a list of courses.
By default only active courses.
will be ordered by given field.
[{id:, name:, title:}, ]
"""
clist = []
reload_if_needed()
for course in COURSES:
if only_active:
if COURS... | 5,292,296 |
def covars_for_custom_models_simple_training_data_4elements():
"""
defines initial covars compatible with custom_models_simple_training_data_4elements above
:return: covars (list of tuple)
"""
covars = [(0.0, -2.0, 2.0)]
return covars | 5,292,297 |
def create(ctxt, name, source_instance_id, description=None):
"""Creates migration.
Raises:
MigrationCreateFailed: If there is error during migration creation.
InstanceNotReadyForMigration: Migrating instance failed
pre-migration validations
"""
t... | 5,292,298 |
def get_asgi_application():
"""
The public interface to Django's ASGI support. Return an ASGI 3 callable.
Avoids making django.core.handlers.ASGIHandler a public API, in case the
internal implementation changes or moves in the future.
"""
django.setup(set_prefix=False)
return ASGIHandler() | 5,292,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.