content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def javacode_to_tokens(code:str):
"""
Starting on method level, without javadocs
returns a touple of ([code-tokens],code-string)
"""
code_tokens = re.findall(r"\w+(?:'\w+)*|[^\w\s]", code)
#print("Javacode to tokens to be done!",code,code_tokens)
return (code_tokens,code) | 68,100 |
def main(eda, train, test):
"""Calls the test functions
Parameters
----------
eda : str
File path of the eda data
train : str
File path of the train data
test : str
File path of the test data
"""
print("Testing EDA functions")
eda_tests(eda)
print("Testi... | 68,101 |
def static(type='artist', artist_pick='song_hotttnesss-desc', variety=.5, artist_id=None, artist=None, \
song_id=None, description=None, results=15, max_tempo=None, min_tempo=None, max_duration=None, \
min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None... | 68,102 |
def print_error(message):
"""Display an error message."""
if not message.endswith('\n'):
message += '\n'
sys.stderr.write(message) | 68,103 |
def floor_to(value: float, target: float) -> float:
"""
Similar to math.floor function, but to target float number.
"""
value: Decimal = Decimal(str(value))
target: Decimal = Decimal(str(target))
result: float = float(int(floor(value / target)) * target)
return result | 68,104 |
def registration():
"""Processes registration when user provides email and password, or
displays the form."""
if request.method == 'POST':
email = request.form.get("email")
password = request.form.get("password")
# Create a possible user object to query if the user's email is in t... | 68,105 |
def add_xyz_circ(circ,q1,q2,params):
"""
inputs:
- q1,2 qubits
- params, qiskit ParameterVector object or list of qk Parameters
returns:
- QKParamCircuit object
"""
# two qubit gates
# xx-rotation
[circ.h(q) for q in [q1,q2]]
circ.cx(q1,q2)
circ.rz(param... | 68,106 |
def generate_meta(favicon: Dict[str, str]) -> str:
"""Generate metatag based on favicon data.
Default behavior:
- If favicon data contains no ``rel`` attribute, sets ``rel="icon"``
- If no ``size`` attribute is provided, ``size`` will be omitted
- If no favicon MIME type is provided, the value for ... | 68,107 |
def select_disk(prompt='Which disk?'):
"""Select a disk from the attached disks"""
disks = get_attached_disk_info()
# Build menu
disk_options = []
for disk in disks:
display_name = '{Size}\t[{Table}] ({Type}) {Name}'.format(**disk)
if len(disk['Partitions']) > 0:
... | 68,108 |
def imageToVTK(
path,
origin=(0.0, 0.0, 0.0),
spacing=(1.0, 1.0, 1.0),
cellData=None,
pointData=None,
fieldData=None,
):
"""
Export data values as a rectangular image.
Parameters
----------
path : str
name of the file without extension where data should be saved.
... | 68,109 |
def test_duct_verification(simple_asm):
"""Test that the method to calculate interior and bypass coolant
temperatures performs as expected"""
# Set up some stuff
inlet_temp = 623.15
gap_t = np.ones(simple_asm.rodded.subchannel.n_sc['duct']['total'])
gap_t *= inlet_temp
simple_asm.rodded._upd... | 68,110 |
def do_volume_connector_delete(cc, args):
"""Delete a volume connector."""
failures = []
for vc in args.volume_connector:
try:
cc.volume_connector.delete(vc)
print(_('Deleted volume connector %s') % vc)
except exceptions.ClientException as e:
failures.appe... | 68,111 |
def compute_capacities(n, demands_across_cuts):
"""
Computes the capacities as given in the paper. Takes O(n^2) time.
:param n: ring size
:param demands_across_cuts: SymmetricMatrix containing all demands across cuts.
:return: np.array containing capacities
"""
c = np.zeros((n,), dtype=np.fl... | 68,112 |
def needs_nibabel_data(subdir=None):
""" Decorator for tests needing nibabel-data
Parameters
----------
subdir : None or str
Subdirectory we need in nibabel-data directory. If None, only require
nibabel-data directory itself.
Returns
-------
skip_dec : decorator
De... | 68,113 |
def adv_search_cumulative_product(seq: str, cum_prod_level: int):
"""
Search About Cumulative Products of Sequence
seq: A string that contains a comma seperated numbers
cum_prod_level: The cumulative product range (1 to cum_prod_level) of levels
returns: nothing
"""
numeric_seq = utils.conve... | 68,114 |
def get_ranks_lsq(df_teams, df_schedule, year, week, B_w=30., B_r=35., dS_max=35., beta_w=2.2, show=False):
"""Calculate iterative LSQ rankings, and save plot
:param df_teams: data frame wtih team_ids
:param df_schedule: data frame with data for each matchup
:param year: current year
:param week: current wee... | 68,115 |
def __create_pyramid_features(C3, C4, C5, feature_size=256):
""" Creates the FPN layers on top of the backbone features.
Args
C3 : Feature stage C3 from the backbone.
C4 : Feature stage C4 from the backbone.
C5 : Feature stage C5 from the backbone.
... | 68,116 |
def enron_dataset_part044() -> Path:
"""
Returns:
A directory with two PST files:
jason_wolfe_000_1_1.pst
jason_wolfe_000_1_2.pst
"""
name = "jason_wolfe"
files = ["jason_wolfe_000_1_1.pst", "jason_wolfe_000_1_2.pst"]
url = f"{ENRON_DATASET_URL}/jason_wolfe.zip"
yie... | 68,117 |
def parse_compare(*tests, justeq=False):
"""Decorate a function to run it against pure python.
This will run and compare the function using all available backends.
"""
def decorate(fn):
def test(backend_opt, args):
if not isinstance(args, tuple):
args = (args,)
... | 68,118 |
def port_scan(port):
"""
Scan a port on the global variable `host`
"""
try:
s = socket.socket()
s.connect((host, port))
except:
with print_lock:
print(f"{GRAY}{host:15}:{port:5} is closed {RESET}", end='\r')
else:
with print_lock:
print(f"... | 68,119 |
def check_brand_parameters(request):
"""
Function to check if the parameters of a given brand are valid
:param request: request object containing all the parameters
:return: Error if exists, if not, None
"""
if not check_parameter(request.json, NAME, 2, 15) \
or not check_parameter(r... | 68,120 |
def command_exists(cmd):
""" does the command exists in current system? """
path = which(cmd)
if path is None:
return False
return True | 68,121 |
def password_spray(user_file, password, domain, sleeptime, domain_controllers, output_filename):
"""
Password spray functionality (many users, one password)
Args:
user_file: (string) Path to a file of usernames
password: (string) Password to use in the attack
domain: (string) Domain... | 68,122 |
def fixed_grib2_to_netcdf(grib_file, nc_file, nc_var_name, msg_id=None,
grib_var_name=None, grib_level=None,
overwrite_nc_units=None, nc_format='NETCDF4'):
"""Convert a single spatial field from a GRIB file to NetCDF.
Parameters
----------
grib_file :... | 68,123 |
def _convert_names(
names, max_levels: Optional[int] = None, err_msg: Optional[str] = None
) -> List[str]:
"""Helper function that converts arguments of index, columns, values to list.
Also performs check on number of levels. If it exceeds `max_levels`,
raise ValueError with `err_msg`.
"""
resu... | 68,124 |
def importCandidatePairs(input_file, log):
"""
Import candidate pairs from a file.
Supported filetypes: txt, json, pickle (python) and csv.
"""
tim = time.clock()
logprint(log, True, "Importing candidate pairs...")
candidatePairs = dict()
# Input file extension
ext = input_file.rsplit(".", 1)
if len(ext) == 0... | 68,125 |
def extractNetFromSolver(solverstring):
"""Read a protoxt string(!) of a solver and return the network protoxt string(!).
This works only, if the solver specifies a network using the "net_param" parameter. A reference to a file using the
"net" parameter can not be handled by this method.
"""
from b... | 68,126 |
def expand_date_param(param, lower_upper):
"""
Expands a (possibly) incomplete date string to either the lowest
or highest possible contained date and returns
datetime.datetime for that string.
0753 (lower) => 0753-01-01
2012 (upper) => 2012-12-31
2012 (lower) => 2012-01-01
201208 (uppe... | 68,127 |
def _check_vmlinux():
"""
Check that /boot/vmlinux* files are readable. This is important for guestfish.
"""
try:
for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError('Make sure that the k... | 68,128 |
def _print(s: str) -> None:
"""a silly custom debugging printer"""
s_ = "\n\n---> my_phonolammps-debug\n"
print(s_ + s + "\n\n") | 68,129 |
def appliedMediumData(modelFunction,cellSpace,initialPercentageInfected,states,n_iterations,n_simulations,theSystemHasAges = False, systemAges = None):
"""Aplica el modelo epidemiológico en n_simulations
modelFunction => Función basica del modelo epidemiológico
initialPercentageInfected => Porcentaje de inf... | 68,130 |
def HD_BET_bet(niix_root,
first_level_code='PID*PNAME*', second_level_code='20*',
filename_pattern='CTP_*_mc_ncct.nii.gz', out_ext='hdbet',
low_thresh=-50, high_thresh=100, gpu='4'):
"""
"""
# retrieving the study root
pid_pname_date_roots = glob(os.... | 68,131 |
def make_id(ref: extmodule.Ref) -> Text:
"""Convert a ref to a string iddentifier."""
return "{}/{}".format(ref.type, ref.ident) | 68,132 |
def main(args=None):
"""
Main function with error catching, can force-exit with os._exit(1)
this main function calls main_() and cathes any error while giving the user a "pretty"
error.
"""
try:
# execute main application
main_(args)
except Exception as error:
# defi... | 68,133 |
def get_torch_datagens(data_dir, feature_len=300, num_video_per_person=1e4, num_audio_per_video=1e4, split_by='audio', split_size=0.2, txt_dirs=None, ratios=[1.0, 1.0]):
"""
Returns datagens for torch
Params:
data_dir: Parent directory for the pickle files. Assumed that each person has a separate fo... | 68,134 |
def plot_all_warppaths(M, N, paths):
"""
Make plots of all warping paths between two time series of
specified lengths
Parameters
----------
M: int
Number of samples in the first time series
N: int
Number of samples in the second time series
path: list of list of [i, j]
... | 68,135 |
def create_grouped_df_adv(group_param, df, ticker_name='symbol',
agg_func=np.count_nonzero, show_value_counts=False):
"""
Receive the `group_param`, `df`, `ticker_name`, `agg_func`
and return grouped by group_param DataFrame
with values aggregated by agg_func and Dict with
... | 68,136 |
def read_args(argv):
"""Print the splash screen, parse, and return the command-line arguments"""
print(splash)
help_formatter = lambda prog: argparse.HelpFormatter(prog, max_help_position=45, width=200)
parser = argparse.ArgumentParser(description="",
... | 68,137 |
def query_history_to_json(query_history: QueryHistory):
"""
The function converts an object of QueryHistory to a json string.
:param query_history: A QueryHistory object.
:type query_history: ibmpairs.query.QueryHistory
:rtype: str
"""
return QueryHi... | 68,138 |
def test_thing_bnf_query_strict_True():
"""Thing - bnf - strict=True - : Should pass """
thing = Thing(label="Thing", query_language=Lang.English)
thing.add_query_endpoint(Endpoint.bnf)
thing.query(strict_mode=True)
assert thing.attributes.get(u'owl:sameAs') == u'owl:Thing' | 68,139 |
def is_MC(parcels):
"""
Dummy for Maricopa County.
"""
return (parcels.county == 'MC').astype(int) | 68,140 |
def getMatchingCompetence(dictionary, lastmessage):
"""
Searches for a competence in a string
"""
allCompetences = getAllCompetences(dictionary)
searchedCompetence = []
for word in re.split('[ .!?]', lastmessage):
if stemmer.stem(word.strip().lower()) in [
stemmer.stem(co... | 68,141 |
def objScale(obj,factor):
"""
Object scaling function, gets obj and scale factor, returns an array of the scaled size
"""
oldSize = obj.get_size()
newSize = []
for i in oldSize:
newSize.append(int(i/float(factor)))
return newSize | 68,142 |
def tiny_shakespeare(c: NLPAutoRegressionConfigs):
"""
### Tiny Shakespeare dataset
It will download from the url if not present
"""
return TextFileDataset(
lab.get_data_path() / 'tiny_shakespeare.txt',
c.tokenizer,
url='https://raw.githubusercontent.com/karpathy/char-rnn/ma... | 68,143 |
def preprocess_encoder_input(arr):
"""
Simple method to handle the complex MFCC coefs that are produced during preprocessing. This means:
1. (For now), discarding one of the channels of the MFCC coefs
2. Collapsing any empty dimensions
:param arr: the array of MFCC coefficients.
"""
return a... | 68,144 |
def findTreeRoute(observations, tree, startNodeID, startLayer, stopLayer, alternateLeafActivation = False):
"""Classifies the observations according to the tree."""
col = 0
treeRoute = []
for i in range(startLayer,stopLayer+2):
if i == startLayer:
currentNode = tree[startNodeID]
... | 68,145 |
def update_role(RoleName=None, Description=None, MaxSessionDuration=None):
"""
Updates the description or maximum session duration setting of a role.
See also: AWS API Documentation
Exceptions
:example: response = client.update_role(
RoleName='string',
Description='string',... | 68,146 |
def create_db_triggers(table_names: typing.List[str]) -> None:
"""Create the triggers for the database tables.
Args:
table_names (List[str]): Table names.
"""
cfg.glob.logger.debug(cfg.glob.LOGGER_START)
utils.progress_msg("Create the database triggers ...")
for column_name in [cfg.gl... | 68,147 |
def determineWinCardIndex(pile):
"""
@param list pile: pile of cards in center
@return int: index of winning card -
highest index of leading suit, or if there are spades, highest spades index
"""
bestCard = (pile[0], 0)
for i in range(1, len(pile)):
bestCardSuit = bestCard[0].ind... | 68,148 |
def mailchimp_list():
"""Creates a MailChimpList. Used for testing class/instance methiods."""
yield MailChimpList(1, 2, 'foo-bar1', 'bar1') | 68,149 |
def sagemaker_timestamp():
"""Return a timestamp with millisecond precision."""
moment = time.time()
moment_ms = repr(moment).split('.')[1][:3]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment)) | 68,150 |
def EmitEval(deque_graph, # type: collections.deque
ctx, # type: Context
):
"""
Emit evaluation code(eval layers)
"""
ret = '''
bool NetworkForwardExecute(Buffer *buffer) {
'''
for layer_name in deque_graph:
node = ctx.graph[layer_name]
if node["op"] == "N... | 68,151 |
def create_server(host=None, port=None, loop=None, backend='tornado',
**server_kwargs):
"""
Create a new server object. This is automatically called; users generally
don't need this, unless they want to explicitly specify host/port,
create a fresh server in testing scenarios, or run Fl... | 68,152 |
def build_dataset_info(cfg):
"""Build information struct about the dataset from a configuration.
This performs type conversion to the expected types. Paths contained in
cfg are expected to be alread expanded. That is, it should not contain
global variables or other system dependent abbreviations.
... | 68,153 |
def cancel_job(auth, config):
"""
Attempts to cancel the selected job and returns True or False depending
on the success of the operation.
:Args:
- auth (:class:`.Credentials`): instance of the Credentials class
as returned by authentication()
- config (:class:`.Configurat... | 68,154 |
def add(interp):
"""
Performs the following operation and replaces the top two stack elements
with the result of:
stack[n] + stack[n-1]
"""
rhs = int(interp.stack.pop())
lhs = int(interp.stack.pop())
interp.stack.append(lhs + rhs) | 68,155 |
def is_database_available(name: str) -> bool:
"""
Basic check for available files, does not recognize if some files
are missing.
"""
base_name = os.path.join(BLASTDB, name)
# It may be from multiple files, so check for the first one.
return are_database_files_available(base_name) or are_data... | 68,156 |
def hdr2srgb(im):
"""[Tonemap a linear image with quasi srgb (clip and gamma 1/2.2)]
Args:
im ([[hxwx3 ndarray]): [linear image]
Returns:
[hxwx3 ndarray]: [srgb image]
"""
return (np.clip(im,0,1) ** (1/2.2) * 255).astype(np.uint8) | 68,157 |
def greyList(n):
"""
生成格雷编码序列
参考:https://www.jb51.net/article/133575.htm
:param n: 长度
:return: 范围 2 ** n的格雷序列
"""
def get_grace(list_grace, n):
if n == 1:
return list_grace
list_before, list_after = [], []
for i in range(len(list_grace)):
... | 68,158 |
def get_feature(feature: Union[str, Feature]) -> Feature:
"""Get feature from name.
Args:
name (str): Name of feature.
Returns:
Feature
"""
if isinstance(feature, str):
feature = get_feature_class(feature)()
elif not isinstance(feature, Feature):
raise TypeError... | 68,159 |
def format_seq_timing(txt_loc, edge_type=1):
"""format the hold and setup time as per .lib requirement """
attr_names = ['rise_hold', 'fall_hold', 'rise_setup', 'fall_setup']
lut_table_list = []
seq_timing_type = ''
if edge_type == 1:
clk_type = 'rising'
else:
clk_type = 'fallin... | 68,160 |
def get_predictions(theta):
"""Produce predictions for all molecules in the freesolv set"""
return np.array([predict_solvation_free_energy_jax(theta, distance_matrices[i], charges[i], type_slices[i]) for i in range(len(distance_matrices))]) | 68,161 |
def train(corpus):
"""
Computes the chunk distribution by pos
The result is stored in a dictionary
:param corpus:
:return:
"""
pos_cnt = count_pos(corpus)
maxPos = {}
for pos in pos_cnt:
testChunkCnt = count_chunks(corpus, pos)
maxPos[pos] = maxDict(testChunkCnt)
... | 68,162 |
def get_suggestions():
"""
Get chatroom suggestions based on user-entered tag
:param tag: string, the tag a user would like to match to
:return: a JSON Response object, containing the matched results
as a list of dicts with keys room_id, name, members
"""
incoming = request.get_json()
... | 68,163 |
def subset_by_value(samples, feature, value):
"""
Subset samples based on value
Parameters:
samples - Pandas DataFrame; last column is taken as the class labels
feature - Name of feature; should correspond to column in samples
value - Value to check for subset membership; can be literal value o... | 68,164 |
def build_model(input_shape, conv_window_size, num_filters, reg, dropout, word2vec = True, max_token = None, sequence_len= 190):
"""
If random init
max_token is the vocabulary size
sequence_len is the number of words in the largenst sentence
"""
model = Sequential()
#mod... | 68,165 |
def csv_fetch_resource(series, **kwargs):
"""
Mock CSV resolver.
"""
path = os.path.join(FIXTURE_DIR, 'tiltmeter_selokopo.csv')
return pd.read_csv(path, **series.csv_params) | 68,166 |
def validate(validation, dictionary):
"""
Validate that a dictionary passes a set of
key-based validators. If all of the keys
in the dictionary are within the parameters
specified by the validation mapping, then
the validation passes.
:param validation: a mapping of keys to validators
:... | 68,167 |
def poll_mag_calibration(imu, mc, evt, verbose=True):
"""
Will poll the x, y mag gauss values in order to establish min, max
"""
samples = 0
while not evt.is_set():
m = imu.mag_values()
samples += 1
x = m[lsm9ds1.XMAG_IND]
y = m[lsm9ds1.YMAG_IND]
if x < mc.xmi... | 68,168 |
def remove_message(msg):
"""Delete received message from queue"""
receipt_handle = msg.get('ReceiptHandle')
try:
# Delete received message from queue
sqs_client.delete_message(QueueUrl=queue_url,
ReceiptHandle=receipt_handle)
except Exception as e:
... | 68,169 |
def train_siamese_resnext(
*args,
embedding_network_0=ResNextNormalized(out_features=250, pretrained=True),
embedding_network_1=ResNextNormalized(out_features=250, pretrained=True),
optimizer_mixin=None,
**kwargs
):
"""Train a Siamese ResNext architecture.
Args:
args: SiameseTrainer a... | 68,170 |
def load_TD(file_path):
"""Returns the TD file given by file_path.
Can be either .val files generated by the windows GUI,
or .bin files generated by the linux C++ framework.
"""
if(file_path.endswith('.val')):
print 'Reading event file: ' + file_path
TD = eventvision.read_aer(fi... | 68,171 |
def test_get_ipv6_address(monkeypatch):
"""Test get own ipv6 address."""
class Socket(MockSocket):
def getsockname(self, *args, **kwargs):
return ("::1234",)
monkeypatch.setattr(socket, "socket", Socket)
assert get_internal_ipv6_address() == IPv6Address("::1234") | 68,172 |
def save_user_hist(user_func, outdir, session=None):
"""
Read generated_files/people.json to get players.
For each player, call get_user_data
Store that data in match_data files. Each file contains 100 entries
and are named and sorted in alphabetical order
"""
if session is None:
... | 68,173 |
def test_fibonacci3():
"""test if the fibonacci list starts from 1."""
result = sequences.fibonacci(10)[0]
correct = 1
assert result == correct | 68,174 |
async def test_flow_no_discovered_bridges(hass, aioclient_mock):
"""Test config flow discovers no bridges."""
aioclient_mock.get(hue.API_NUPNP, json=[])
flow = hue.HueFlowHandler()
flow.hass = hass
result = await flow.async_step_init()
assert result['type'] == 'abort' | 68,175 |
def hbb_to_kaa(hessian):
"""
Unit conversions on input Hessian matrix from (Hartrees/Bohr/Bohr)
(kcal/mol/Angstrom/Angstrom).
"""
hessian = (hessian * 627.509474) / (0.529177**2)
return hessian | 68,176 |
def mem_creator(path: str, num: int):
"""
This function produce a numpy memory map. The memory map is very usefull
since a small training batch is sampled from a large file.
Note: The longest recording determines the length of the recordings.
The recording with most channels determine the amou... | 68,177 |
def get_formatted_contents(
raw_contents,
use_color,
color_config,
squeeze,
subs
):
"""
Apply formatting to raw_contents and return the result. Formatting is
applied in the order: color, squeeze, subs.
"""
result = raw_contents
if use_color:
result = get_colorized_co... | 68,178 |
def problem_to_control(problem, debian_path):
"""
Converts problem.json to a deb control file.
Args:
problem: deserialized problem.json (dict)
debian_path: path to the DEBIAN directory
"""
# a-z, digits 0-9, plus + and minus - signs, and periods
package_name = problem.get("pkg_... | 68,179 |
def execute():
"""Execute template console CLI."""
app = Cli()
app.run() | 68,180 |
def home_page(request):
"""View for the home route."""
with io.open(os.path.join(HERE, 'sample.html')) as the_file:
imported_text = the_file.read()
return Response(imported_text) | 68,181 |
def mpi_grad_fq(n_nodes, m_list, q, scatter_array, qbin):
"""
Breakup the grad F(Q) job across GPU enabled nodes
Parameters
----------
n_nodes: int
Number of allocated nodes, not including the head node
Returns
-------
list of floats:
Amount of memory per GPU
"""
... | 68,182 |
def run(cmd, input=None):
"""
Run *cmd*, optionally passing string *input* to it on stdin, and return
what the process writes to stdout
"""
try:
p = subprocess.Popen(shlex.split(cmd),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
... | 68,183 |
def compute_bin_assignment(position, x_edges, y_edges=None, include_edge=True):
"""Compute spatial bin assignment.
Parameters
----------
position : 1d or 2d array
Position information across a 1D or 2D space.
x_edges : 1d array
Edge definitions for the spatial binning.
Value... | 68,184 |
def padded_tensor(
items: List[Union[List[int], torch.LongTensor]],
pad_idx: int = 0,
left_padded: bool = False,
max_len: Optional[int] = None,
) -> Tuple[torch.LongTensor, List[int]]:
"""
Create a padded matrix from an uneven list of lists.
Returns (padded, lengths), where padded is the pa... | 68,185 |
def coloring(color, text):
"""Print a text in a specified color"""
color_sequences = {
'default': '\033[0m',
'black': '\033[30m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'purple': '\033[35m',
'lightblue': '... | 68,186 |
def truediv(a, b):
"""Same as a / b."""
return a / b | 68,187 |
def calcDihedrals(prevCO, currN, currCA, currCO, nextN):
"""
Calculates phi and psi angles for an individual residue.
Requires coord tuple of each atom.
"""
prevCO = np.array(prevCO)
currN = np.array(currN)
currCA = np.array(currCA)
currCO = np.array(currCO)
nextN = np.array(nextN)
... | 68,188 |
def reset_password(
token: str = Body(...),
new_password: str = Body(...),
node: Node = Depends(deps.get_db),
) -> Any:
"""
Reset password
"""
db = node.db
email = verify_password_reset_token(token)
if not email:
raise HTTPException(status_code=400, detail="Invalid token")
... | 68,189 |
def update_backend_info(device_list: wid.VBox,
interval: int = 30) -> None:
"""Updates the device list from another thread.
Args:
device_list: Widget showing the devices.
interval: How often to refresh the backend information.
"""
my_thread = threading.currentThr... | 68,190 |
def WorkerAgentGenerator(agent_class):
"""
Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent.
"""
# Support special case where class is given as type-string (AgentsDictionary) or class-name-string.
if isinstance(agent_class, str):
... | 68,191 |
def set_seed(args):
""" set seed for the whole program for removing randomness
"""
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed) | 68,192 |
def update_monolith_stats(date=None):
"""Update monolith statistics."""
if date:
date = datetime.datetime.strptime(date, '%Y-%m-%d').date()
today = date or datetime.date.today()
jobs = [{'metric': metric,
'date': today} for metric in tasks._get_monolith_jobs(date)]
ts = [tasks.... | 68,193 |
def series_mean_with_conf(xx):
"""
Compute series mean.
Also provide confidence of mean,
as estimated from its correlation-corrected variance.
"""
mu = mean(xx)
N = len(xx)
if np.allclose(xx,mu): return val_with_conf(mu, 0)
if (not np.isfinite(mu)) or N<=5: return val_with_conf(mu, n... | 68,194 |
def your_sanity_checks():
"""
Use this space add any additional sanity checks by running:
python q2_neural.py
This function will not be called by the autograder, nor will
your additional tests be graded.
"""
print "Running your sanity checks..."
### YOUR CODE HERE
raise NotImpl... | 68,195 |
def my_display_image(image):
"""
Display an image with the 'bone' color map, bicubic interpolation and with
the gray values from the minimum of the image to the mean plus three times
the standard deviation of the image
"""
plt.imshow(image, cmap='bone', interpolation='bicubic',
vm... | 68,196 |
def multiprocessing_wc(tpm, kws, queue, test_without_wc=True):
"""
function that enables to create WordCloud in a different process.
"""
queue.put(create_wc(tpm, kws)) | 68,197 |
def get_webhook():
"""
Getting installed webhooks
:return: installed webhooks
"""
header = {'Content-Type': 'application/json;charset=utf-8'}
request_address = 'https://api.ok.ru/graph/me/subscriptions?access_token={token}'.format(token=token)
response = requests.get(request_address, headers... | 68,198 |
def haversine(rad):
"""
Returns the haversine function of an angle in radians.
"""
return (1 - math.cos(rad)) / 2 | 68,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.