content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getToken():
"""
Method that generates and retrieves a temporary API access token for Reveal(x) 360 authentication.
Returns:
str: A temporary API access token
"""
auth = base64.b64encode(
bytes(TARGET_ID + ":" + TARGET_SECRET, "utf-8")
).decode("utf-8")
headers = {... | 53,800 |
def set_blendshape_weights_array(bs_node_name, weights):
""" cmds version """
weight_attrs = cmds.listAttr(bs_node_name + ".weight", multi=True)
if len(weight_attrs) != len(weights):
print "Error: nun weights != num of attributes"
return
for i in range(len(weights)):
# print "Se... | 53,801 |
def valid_units(span, data):
"""Validate and update data units."""
units = [t.lower_ for t in span if t.ent_type_ in UNIT_ENTS]
if units:
units = REPLACE.get(units[0], units[0])
# Remove bad units
if units not in ('m', 'ft'):
return False
data['elev_units'] = u... | 53,802 |
def win_active_by_handle(handle):
"""
:param handle:
:return:
"""
ret = AUTO_IT.AU3_WinActiveByHandle(HWND(handle))
return ret | 53,803 |
def set_title_str(title: str) -> str:
"""Get the required string, including ANSI escape codes, for setting window title for the terminal.
:param title: new title for the window
:return: string to write to sys.stderr in order to set the window title to the desired test
"""
return cast(str, colorama.... | 53,804 |
def two_sum_ver2(nums: list, target: int) -> list:
"""Use dictionay"""
# Save numbers and indexes
num_idx = {}
for i, num in enumerate(nums):
num_idx[num] = i
# Search an index using a key target - num
for i, num in enumerate(nums):
if target - num in num_idx and i != num_idx[ta... | 53,805 |
def _GetAndValidateCmekKeyName(args):
"""Parses the CMEK resource arg, makes sure the key format was correct."""
kms_ref = args.CONCEPTS.kms_key.Parse()
if kms_ref:
_ShowCmekPrompt()
return kms_ref.RelativeName()
else:
# Check for partially specified disk-encryption-key.
for keyword in [
... | 53,806 |
def test_get_and_verify_covars_input_with_dependencies_fails(tmp_observe_class, covariates, kwarg_covariates, monkeypatch):
"""
test _get_and_verify_covars_input which depends on _read_covars_manual_input and
_validators.Validators.__validate_num_covars. monkeypatch the user input (when needed), also test t... | 53,807 |
async def clone_projectversion(request):
"""
Clone a project version.
---
description: Clone a project version.
tags:
- ProjectVersions
parameters:
- name: project_id
in: path
required: true
type: string
- name: projectversion_id
i... | 53,808 |
def event_download_photos(photos):
"""Use asynchronous I/O to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
try:
assert gevent
assert grequests
except NameError:
logger.error('You need install gevent module. Aborting...')
... | 53,809 |
def callback_tag(dataset, data_element, pattern):
""" Called from the dataset 'walk' recursive function, will anonymize
all the tag 'tag'."""
tag, action = pattern
if tag in dataset:
tag_repr = repr(data_element.tag)[1:-1].replace(" ", "")
value = data_element.value
anon_value = ... | 53,810 |
async def bookshelf_read(request):
"""
Book has now been read.
"""
payload = await request.content.read()
# create an event from this request
payload = json.loads(payload.decode('utf-8'))
event = make_event(name="book-read", payload=payload)
await send_event(b"bookshelf", event)
re... | 53,811 |
def _repr_unicode(dumper, data):
"""Fix yaml str representation."""
data = data.encode('ascii', 'ignore').decode() # XXX:Is this the best way?
if '\n' in data:
return dumper.represent_scalar('tag:yaml.org,2002:str', data,
style='|')
else:
return du... | 53,812 |
def delete_url(url,request_num,log,phase):
"""
# Desc : Function to send delete requests to the server. Type 3 is delete requests
# also captures the data record being deleted and saves it in a list(post/_datalist)
# which is used for new post requests
# Input : Delete request URL, Request N... | 53,813 |
def train_model():
"""
Trains a model
"""
tic = time.time()
args = get_args()
path_save_dir = Path(args.path_save_dir)
if path_save_dir.exists():
raise ValueError(f"Save directory already exists! ({path_save_dir})")
path_save_dir.mkdir(parents=True)
logging.getLogger().addH... | 53,814 |
def get_paper_data(paper_name):
"""Gets paper code and paper type based on paper name"""
split = paper_name.split("_")
code = split[-1]
paper_type = split[-2]
if len(split) == 5:
code = split[-2] + split[-3]
paper_type = split[-1]
elif len(split) == 3:
code = "00"
... | 53,815 |
def create_macrobe():
"""Create VFDBlToolResult with randomized field data."""
packed_data = create_values()
return MacrobeToolResult(macrobes=packed_data).save() | 53,816 |
def setup_exception_handlers(app: FastAPI) -> None:
"""
Helper function to setup exception handlers for app.
Use during app startup as follows:
.. code-block:: python
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_exception_handlers(app)
:... | 53,817 |
def ConnectDispatcher(element, signal, callback, *args):
""" Global helper function to wrap TPyDispatcher"""
if isinstance(callback , SJCallBack):
callback.element = element
disp = ROOT.TPyDispatcher(callback)
_dispatchers.append(disp)
element.Connect(signal, "TPyDispatcher", disp, "Dispatch... | 53,818 |
def assert_result_equal(result, title=None, rows=None, headers=None,
status=None, auto_status=True, assert_contains=False):
"""Assert that an sqlexecute.run() result matches the expected values."""
if status is None and auto_status and rows:
status = '{} row{} in set'.format(
... | 53,819 |
def toLongPathSafe(path):
"""Converts the specified path string to a form suitable for passing to API
calls if it exceeds the maximum path length on this OS.
@param path: A path. Can be None/empty. Can contain ".." sequences.
@return: The passed-in path, absolutized, and possibly with a "\\?\" prefix added,
... | 53,820 |
def model_parameters(parser_nn):
"""Xception model parameters.
Args:
parser_nn: global command line args parser
Returns: parser with updated arguments
"""
parser_nn.add_argument(
'--cnn1_kernel_sizes',
type=str,
default='5',
help='Kernel_size of the conv block 1',
)
parser_nn... | 53,821 |
def test_can_run_as_admin():
"""
A simple test function; check if we're admin, and if not relaunch
the script as admin.
"""
if not isUserAdmin():
print("You're not an admin.", os.getpid(), "params: ", sys.argv)
# rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()... | 53,822 |
def handler_add_channel():
"""Add a channel.
.. :quickref: Media; Add a channel.
:json string name: The name of the new channel
:json string link: The link to fetch the channel from
:status 200: The channel was correctly inserted
:status 400: The provided JSON is invalid or there is a data... | 53,823 |
def distance_pattern_strings(
sequences: List[Sequence],
pattern: Sequence,
) -> Dict[str, Union[List[Optional[Sequence]], int]]:
"""Calculates the sum of distances between the pattern and each string.
The Hamming distance is minimized for each sequence, respecting a fixed
pattern length.
Args... | 53,824 |
def run_simulation():
"""
Entry-point for running Ms. Pac-man simulation
"""
ENV = gym.make(GAME_TYPE)
ACTION_SIZE = ENV.action_space.n
DONE = False
#print game parameters
print ("~~~Environment Parameters~~~")
print ("Num episodes: %s" % NUM_EPISODES)
print ("Max timesteps: %s... | 53,825 |
def hideLogPane(event):
"""Hide the log pane. Fully expand the outline pane."""
c = event.get('c')
if not c:
return
c.frame.divideLeoSplitter2(1.0) | 53,826 |
def lulesh_caliper_json(data_dir, tmpdir):
"""Builds a temporary directory containing the lulesh JSON file."""
cali_json_dir = os.path.join(data_dir, "caliper-lulesh-json")
cali_json_file = os.path.join(cali_json_dir, "lulesh-annotation-profile.json")
shutil.copy(cali_json_file, str(tmpdir))
tmpfil... | 53,827 |
def is_struct_field_address(xpr: X.XXpr, astree: AbstractSyntaxTree) -> bool:
"""Return true if the expression is the address of a known struct."""
if xpr.is_int_constant:
return astree.is_struct_field_address(xpr.intvalue)
return False | 53,828 |
def bar():
"""
>>> import queue
>>> def test():
... import bisect
... pass
"""
pass | 53,829 |
def get_scanner(hass, config):
"""Validate the configuration and return an ASUS-WRT scanner."""
scanner = AsusWrtDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None | 53,830 |
def remove_vulgarity_id(sentence):
"""remove_vulgarity_id Removes uncivilised words in Bahasa Indonesia
Prevent words such as "anjir", "babi" etc to be included in natual language generation tasks
:param sentence: An input string
:type sentence: str
:return: A string where common swear words i... | 53,831 |
def str_class(s: str) -> str:
"""Expand a string of character ranges.
Example: str_class("a-cx0-9") = "abcx0123456789"
"""
i = 0
n = len(s)
ret: List[str] = []
while i < n:
if i + 2 < n and s[i+1] == '-':
start = ord(s[i])
end = ord(s[i+2])
if sta... | 53,832 |
def activate_boolean_map(bool_map):
"""
Performs activation on a single boolean map.
"""
# use the boolean map as a mask for flood filling
activation = np.array(bool_map, dtype=np.uint8)
mask_shape = (bool_map.shape[0] + 2, bool_map.shape[1] + 2)
ffill_mask = np.zeros(mask_shape, dtype=... | 53,833 |
def migrate(migrator, database, fake=False, **kwargs):
"""Write your migrations here."""
@migrator.create_model
class CommentReportLog(pw.Model):
rid = pw.ForeignKeyField(
db_column="id", model=migrator.orm["sub_post_comment_report"], field="id"
)
action = pw.IntegerFiel... | 53,834 |
def adjust_verbs(sentence, conjugator, lemmatizer):
"""adjusts verbs in sentences to their respective plural form"""
tagged = pos_tag(word_tokenize(sentence))
adjusted = []
for t in tagged:
if t[1] == 'VBZ':
lem = lemmatizer.lemmatize(t[0], pos="v")
if lem == 'go':
... | 53,835 |
def hexstr2int(hexstr):
"""
Convert string of hex values to list of integers.
example:
"1a 1b 1c 1d" => [26, 27, 28, 29]
"""
return [int(x, 16) for x in pairwise(hexstr.replace(" ", ""))] | 53,836 |
def testCompomer():
"""
@tests:
Compomer.__init__
"""
a = pyopenms.Compomer() | 53,837 |
def getlength():
"""retrieves the length of every document and stores in a dictionary"""
le={}
o = open("lengths.txt", 'r')
for line in o:
li=line.strip().split(' ')
le[li[0]]=li[1]
o.close()
return le | 53,838 |
def vib_energy_diagram(
quant_nums, vibrations, maxV=2, maxE=3000.0, useFull=True, image=None, imagesize=0.1
):
"""
Function that will generate a vibrational energy diagram.
This function wraps the make_elevel_plot function!
Input arguments are
quant_nums: A 2D numpy... | 53,839 |
def ellipse_fit():
"""Load the data from ellipse.npy. Use least squares to calculate the
ellipse that best fits the data.
Plot the original data points and the least squares ellipse together.
"""
raise NotImplementedError("Problem 4 Incomplete") | 53,840 |
def generate_guide_stars(catalog):
"""Generate a catalog with the angular distance of all stars
combinations"""
guide_stars = {}
FOV_h = 14.455 * math.pi/180
FOV_v = 10.94 * math.pi/180
FOV_diag = math.sqrt(FOV_h**2 + FOV_v**2)/2
for a, b in itertools.combinations(catalog, 2):
a_car... | 53,841 |
def create_loaders(full, batch_size, val_split, shuffle=True, min_val=1):
"""Split full dataset into training and validation
:param torch.utils.data.Dataset full: Entire dataset
:param int batch_size: Number of samples per batch
:param float val_split: Percent of full dataset to use for validation
... | 53,842 |
def sd_features_length(self):
"""features_length for SubDataset
Args:
self (SubDataset):
"""
return self._dataset.features.features_length() | 53,843 |
def indexing_start():
"""
Function for ``eurocli indexing start``.
Calls the main of the indexing job.
"""
click.echo("Starting indexing")
ep_indexer.main() | 53,844 |
def create_node2vec_model(lvl_data, is_weighted, dimension=None, file_name=None, prefix=None, dimensions=[]):
"""Creates a node2vec model and saves it.
:param lvl_data: data that will be used to create the model
:dimension: Integer value that tells in which dimension should the embeddings be
:is_wei... | 53,845 |
def filter_edges(nodes:List[int], edges: List[Tuple[int,int,int]]) -> List[Tuple[int,int,int]]:
"""Filter the edges of a subgraph.
Parameters
----------
nodes: list containing the nodes
edges: list containing the edges of the original graph
Returns
-------
inverse dictionary of nodes
... | 53,846 |
def get_shared_symmetry_operations(struc, pointops, tol=0.1):
"""
Get all the point group operations shared by a pair of atomic sites
in the form [[point operations of site index 1],[],...,[]]
Args:
struc: Pymatgen structure
pointops: list of point group operations from get_site_symmetr... | 53,847 |
def rest_server(port: int) -> None:
"""
Starts the REST server
:param port:
:return:
"""
http_server = http.server.HTTPServer(('', port), RESTRequestHandler)
http_server.service_actions = service_worker
try:
http_server.serve_forever(poll_interval)
except KeyboardInterrupt:
... | 53,848 |
def flatten(node: ir.Node) -> ir.Node:
"""Flattens an node if possible.
Flattens an node if it is:
+ a singleton BinaryOp; or
+ a compound BinaryOp with reduction operators; or
+ a compound Operand; or
+ a Unary with an identity operator.
An Operand is a compound Operand if and only if its attr ... | 53,849 |
def is_primes(n) :
"""return 'True' if 'n' is a prime number. False otherwise"""
b =[]
if n==1:
return False # 1 is not a prime
if n==2:
return True
if n > 2 and n % 2 ==0:
return False
max_divisor = math.floor(math.sqrt(n))
for i in rang... | 53,850 |
def run(program) -> None:
"""runs a program"""
program = "".join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'],program)) #deal with disallowed characters before running for speed improvements
for line in _iterRunner(program):
pass | 53,851 |
def test_md042_good_non_empty_link():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/md004 directory that has consistent asterisk usage on a single
level list.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
... | 53,852 |
def parseInput():
""" USE THIS IF: json input has song_url and not track_id """
""" """
# test_case
with open( 'test_in.json') as test:
lines = json.load( test)
#/test_case | 53,853 |
def _generate_waveform_name_dict():
"""Maps _WAVEFORM_DEFS -> _WAVEFORM_NAMES.
_WAVEFORM_NAMES is a sparse map of the following keys:
"id:device:channel" -> name
"id:device:" -> name
"id::channel" -> name
"id:" -> name
"""
data = {}
for waveform in _WAVEFORM_DEFS:
for key, ... | 53,854 |
def generate_gcode(*args):
"""
generate gcode for heightmap in a given orientation
note: [toBeImproved]heightmap passed as formatted string isnt a
good way to structure the code
"""
arg = args[0][0]
orientation = args[0][1]
global diameter, step, feed
command = ["./script... | 53,855 |
def dense_rank_based_voting(score_df, level, column='score'):
"""
The amount of vote each program component
(corresponding to a row in `score_df`) cast is defined by
the inverse of the dense rank of its suspiciousness score,
which is stored in the column `column` of `score_df`.
Then, the total v... | 53,856 |
def test_cmake_option_build_perf_test_off(qibuild_action):
""" Test CMake Option Build Perf Test Off """
project = qibuild_action.add_test_project("perf")
qibuild_action("configure", "perf", "-DQI_WITH_PERF_TESTS=OFF")
qibuild_action("make", "perf")
test_path = qibuild.find.find([project.sdk_directo... | 53,857 |
def average_gradients(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradien... | 53,858 |
def write_frames(frames: list, fname: str, height: int, width: int):
"""Method to write frames to a video
"""
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter(fname, fourcc, 29.97, (width, height))
for frame in frames:
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
ou... | 53,859 |
def power_spectral_density(signal, window, overlap, fmin, fmax, fs, average=True):
"""Compute PSD using welch method
Parameters
----------
signal : array of shape (n_samples,)
The signal to compute the PSD on.
window : int
Length of the segments.
overlap : float
proporti... | 53,860 |
def GetStatus(issue):
"""Get the status of an issue, whether it is explicit or derived."""
return issue.status or issue.derived_status or '' | 53,861 |
def mqtt_on_message(client_object, userdata, msg): # noqa: pylint: disable=unused-argument
"""The callback for when a PUBLISH message is received from the server."""
matched = False
for device_object in ACTIVE_DEVICES:
if msg.topic == device_object.command_topic():
LOG_OBJECT.info("Comma... | 53,862 |
def test_get_move_actions(spadl_actions: DataFrame[SPADLSchema]) -> None:
"""It should filter passes, dribbles and crosses."""
move_actions = xt.get_move_actions(spadl_actions)
assert move_actions.type_id.isin(
[
spadl.config.actiontypes.index("pass"),
spadl.config.actiontype... | 53,863 |
def set_safe_attr(instance, attr, val):
"""Sets the attribute in a thread safe manner.
Returns if new val was set on attribute.
If attr already had the value then False.
"""
if not instance or not attr:
return False
old_val = getattr(instance, attr, None)
if val is None and old_val... | 53,864 |
def receives(func):
""" Decorate a method to enable method mocking
"""
def call_receiver(*kargs, **kwargs):
receiver = Receiver()
kwargs['receive'] = receiver
result = func(*kargs, **kwargs)
receiver.finalize()
return result
return call_receiver | 53,865 |
def upload():
"""Recieve a perun tarball, store it in a temporary file and process it."""
# Create a tempfile to write the data to. delete=False because we will
# close after writing, before processing, and this would normally cause a
# tempfile to disappear.
file = tempfile.NamedTemporaryFile(pref... | 53,866 |
def decide_action(args, username, vagrant_cloud_token):
"""Make decision on what to do from arguments being passed."""
if args.action == 'build_all':
build_all(username, vagrant_cloud_token)
# upload_boxes(username, vagrant_cloud_token)
elif args.action == 'change_controller':
change... | 53,867 |
def test_ecb_256():
"""
Verify that single-block 256-bit ECB en/decryption works.
Test vectors from here:
https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-
Algorithm-Validation-Program/documents/aes/AESAVS.pdf
Appendix D. VarTxt Known Answer Test Values -- first 10 values from D.3... | 53,868 |
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=3, type=int)
parser.add_argument('--cpu', dest='cpu_mode',
... | 53,869 |
def left_hash(msg, func="HS256"):
""" Calculate left hash as described in
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
for at_hash and in
for c_hash
:param msg: The message over which the hash should be calculated
:param func: Which hash function that was used for the ID to... | 53,870 |
def xbin_ybwt(x, y, xbins, Nmin=1):
"""
Take x,y pairs. Bin in x, find biweight location and scale
Input: x and y, xbins
Nmin : default 1
minimum number of points per bin to be used (otherwise nan)
Return: xbins centers, yloc, yscale
"""
assert len(x) == len(y)
... | 53,871 |
def get_container_runtime_module():
"""check what container runtime is running
and return a handle to it"""
# TODO THIS LOCKS SSH CLIENT TO CONTROLLER
ssh_client = topology.list_openstack_nodes(group='controller')[
0].ssh_client
if docker.is_docker_running(ssh_client=ssh_client):
ret... | 53,872 |
def render_body_keypoints(img: np.array,
body_keypoints: np.array) -> np.array:
"""
Render OpenPose body keypoints on input image.
Args:
img (np.array): Input image of shape (H, W, 3) with pixel values in the [0,255] range.
body_keypoints (np.array): Keypoint array ... | 53,873 |
def say(s):
"""A wrapper for print() that's compatible with Python 2 & 3"""
print (s) | 53,874 |
def do_create(cs, args):
"""Create a container."""
opts = {}
opts['name'] = args.name
opts['image'] = args.image
opts['memory'] = args.memory
opts['cpu'] = args.cpu
opts['environment'] = zun_utils.format_args(args.environment)
opts['auto_remove'] = args.auto_remove
opts['workdir'] = ... | 53,875 |
def doc(thing, title='Python Library Documentation: %s', forceload=0,
output=None):
"""Display text documentation, given an object or a path to an object."""
try:
if output is None:
pager(render_doc(thing, title, forceload))
else:
output.write(render_doc(thing, ti... | 53,876 |
def create_app():
"""
建立web应用
url: http://flask.pocoo.org/docs/1.0/quickstart/
:return:
"""
flask_app = Flask(__name__)
with flask_app.app_context():
# 项目内部配置
mongodb_base = MongodbManager.get_mongo_base(
mongodb_config=Config.MONGODB_CONFIG
)
app... | 53,877 |
def update_status_config(milestones_content):
"""Convert the JSON milestones from GitHub to a simple dict."""
milestones = json.loads(milestones_content)
# Test that GitHub milestones and local definitions are equivalent
status_names = sorted(STATUSES.keys())
milestone_names = sorted([milestone['tit... | 53,878 |
def getNjuClassesUrl(date=date.today()):
"""url of classes information"""
return 'https://wx.nju.edu.cn/njukb/wap/default/classes?date={}'.format(str(date)) | 53,879 |
def validate_data(file_abs_path, datatype):
"""Validate datafile.
Validation method depends on the datatype
"""
if datatype == '2bit':
is_valid_2bit(file_abs_path)
elif datatype in ('genes', 'features'):
is_valid_bigbed(file_abs_path)
elif datatype == 'variants':
is_valid... | 53,880 |
def sg_to_brix(sg):
"""
Specific Gravity to Degrees Brix
:param float sg: Specific Gravity
:return: Degrees Brix
:rtype: float
Source:
* http://en.wikipedia.org/wiki/Brix
* http://www.brewersfriend.com/brix-converter/
"""
if sg > 1.17874:
raise SugarException(u"Above 4... | 53,881 |
def trigger_renditions_bucket_event(data, context):
"""Background Cloud Function to be triggered by Cloud Storage.
This function retrieves a source video and triggers
the generation of renditions by means of an http asynchronous
call to the create_renditions_http function
Args:
dat... | 53,882 |
def mpl_save_list(img_list,
output_file_path,
title_list=None,
highlight_mask_list=None,
metadata_dict=None):
"""Plot several images at once.
Parameters
----------
img_list
A list of 2D numpy array to plot.
"""
# M... | 53,883 |
def detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising',
kpsh=False, valley=False, show=False, ax=None):
"""Detect peaks in data based on their amplitude and other features.
Parameters
----------
x : array-like
1D vector with data
mph : {None, number}, optional (def... | 53,884 |
def HarmonicOscillatorsSample(N_k=[100, 100, 100], O_k = [0, 1, 2], K_k = [1, 1, 1], seed=None):
"""
Generate samples from 1D harmonic oscillators with specified relative spacing (in units of std devs).
OPTIONAL ARGUMENTS
N_k (list or numpy.array of nstates) - number of samples per state
O_k (list or num... | 53,885 |
def temporary_filename():
# type: () -> Iterator[str]
"""Creates a temporary filename.
This is useful when you need to pass a filename to an API. Windows requires all handles to a
file be closed before deleting/renaming it, so this makes it a bit simpler.
"""
with named_temporary_file() as fp:
... | 53,886 |
def genkeys(e, bit):
"""
Generates keys for rsa.
Parameters:
e (int): public key
bit (int): bit length of primes
Outputs:
n (int): modulus
e (int): public key
d (int): private key
"""
lam=0
while np.gcd(e, lam) != 1:
p=genprime(bit)
q=genprime(bit)
... | 53,887 |
def test_resource_immediate_requests(env):
"""A process must not acquire a resource if it releases it and immediately
requests it again while there are already other requesting processes."""
def child(env, res):
result = []
for i in range(3):
with res.request() as req:
... | 53,888 |
def get_xml_subelement(xml_elem, subelement, attribute=None, multi=False, convert=None, default=None, quiet=False):
"""
Return the text or attribute of the specified subelement
=== PARAMETERS ===
xml_elem : search the children nodes of this element
subelement: name of the subelement whose text wil... | 53,889 |
def sub_env_var(uri, envvars):
"""Substitute any environment variables found"""
match = ENVVAR_RE.search(uri)
if not match: # no environment variable in uri
return uri
old = match.group(1)
envvar = match.group(2)
if not envvar in envvars:
print(f'Undefined environment variable {... | 53,890 |
def filter_intensity_jumps(i0,winsz=20,num_quantiles=2,quantile=0.5):
"""
Identify locations in the trajectory where the intensity jumps significantly
Parameters
----------
i0 : numpy.ndarray
Dot intensity time series.
winsz : int
Window size for creating the trendl... | 53,891 |
def test_creation_extension_ignore_invalid_metadata(api):
"""
CREATION extension ignore invalid metadata
"""
metadata1 = 'value1'
metadata2 = 'value2'
headers = {
'Upload-Length': '100',
'Upload-Metadata': f'key0,key1 {base64_encode(metadata1)},key2 {base64_encode(metadata2)}',
... | 53,892 |
def str_to_tn(str_):
"""Fully parses str_.
A full parse might not be necessary. Both blocks and the nodes can be (and
probably should be) parsed lazily.
"""
lines = str_.split(NODE_BREAK)
return get_blocks(lines) | 53,893 |
def read_multiple_files(files):
"""read multiple L1-related files and return dictionary of executed read-in class instances
Args:
files: list of files to read in
Returns:
dictionary with keys brt, blb, irt, met, hkd containing list with all read-in class instances for the
correspond... | 53,894 |
def parse_with_semantics(text: str, semantics: type=None) -> List[base.StatementObject]:
"""Parse a file with given semantics."""
return lang.parse(text, semantics=semantics()) | 53,895 |
def get_object_expiry_time(storage_url, auth_token, container, name):
"""Return in seconds the header x-expiry-at for the given object."""
cont = client.head_object(storage_url, auth_token, container, name)
return cont.get('x-delete-at', '') | 53,896 |
def file(input_file):
"""Import colorscheme from json file."""
data = util.read_file_json(input_file)
if "wallpaper" not in data:
data["wallpaper"] = "None"
if "alpha" not in data:
data["alpha"] = "100"
return data | 53,897 |
def find_artists(artist):
"""
Searches and returns the first page results of AZLyrics artists.
:param artist: string with the name of the artist
:return: list of dicts with artist and url strings
"""
r = requests.get("https://search.azlyrics.com/search.php",
params=dic... | 53,898 |
def l_model_forward(x, parameters):
"""
Forward propagation of deep learning.
@param x: input x, numpy arrays
@param parameters:
@return: output aL and caches for following calculations, numpy arrays and indexes
"""
caches = []
a = x
l_total = len(parameters) // 2 # number of layer... | 53,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.