content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def reset_option(key):
"""
Reset one or more options to their default value.
Pass "all" as argument to reset all options.
Available options:
parse.full_codestream
print.xml
print.codestream
print.short
Parameter
---------
key : str
Name of a single... | 38,600 |
def how_many(num):
"""Count the number of digits of `num`."""
if num < 10:
return 1
else:
return 1 + how_many(num // 10) | 38,601 |
def test_invalidname__validatefilename():
"""Assertion error thrown for wrong filename"""
with pytest.raises(AssertionError):
ASSAY_INFO.validateFilename(['foo']) | 38,602 |
def line_length_check(line):
"""Return TRUE if the line length is too long"""
if len(line) > 79:
return True
return False | 38,603 |
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: a file path.
Returns:
u... | 38,604 |
def possibly_intersecting(dataframebounds, geometry, buffer=0):
"""
Finding intersecting profiles for each branch is a slow process in case of large datasets
To speed this up, we first determine which profile intersect a square box around the branch
With the selection, the interseting profiles can be de... | 38,605 |
def compute_complexity(L, k=5, from_evalues=False, from_gram=False):
"""
Computes a variety of internal representation complexity metrics at once.
Parameters
----------
L : numpy.ndarray, shape (n_samples, ...)
internal representation matrix or precomputed eigenvalues
k : int, default=5
... | 38,606 |
def write_html_report(xml_root, work_dir, html_dir, html_name = 'index.html'):
""" Write the HTML report in a given directory
"""
if not os.path.isdir(html_dir):
os.makedirs(html_dir)
html_path = os.path.join(html_dir, html_name)
with io.open(html_path, 'w', encoding='utf8') as html... | 38,607 |
def settings(request, username, args={}, tab="change_password"):
"""
Show a page which allows the user to change his settings
"""
if not request.user.is_authenticated():
return render(request, "users/settings/settings_error.html", {"reason": "not_logged_in"})
profile_user = User.objects... | 38,608 |
def check_contents(md5, filepath, ignore):
"""
md5 - the md5 sum calculated last time the data was validated as correct
filepath - the location/file where the new data is, this is to be validated
ignore - a list of regular expressions that should be thrown out, line by line in the comparison
"""
... | 38,609 |
def create_id(prefix=None):
""" Create an ID using the module-level ID Generator"""
if not prefix:
return _get_generator().create_id()
else:
return _get_generator().create_id(prefix) | 38,610 |
def evaluate_policy(theta, F):
"""
Given theta (scalar, dtype=float) and policy F (array_like), returns the
value associated with that policy under the worst case path for {w_t}, as
well as the entropy level.
"""
rlq = qe.robustlq.RBLQ(Q, R, A, B, C, beta, theta)
K_F, P_F, d_F, O_F, o_F = rl... | 38,611 |
def arspec(x, order, nfft=None, fs=1):
"""Compute the spectral density using an AR model.
An AR model of the signal is estimated through the Yule-Walker equations;
the estimated AR coefficient are then used to compute the spectrum, which
can be computed explicitely for AR models.
Parameters
--... | 38,612 |
def send_recovery_password_email(token: str, email: str) -> None:
"""
Send a recovery password email.
Params:
------
- token: str - The encoded special token
- email: str - The user email
"""
# TODO ...
# Load html templates and get the content from it.
# html_content = ...
... | 38,613 |
def test_perc_cap_words_error():
"""Check TypeError raised when the text is empty or when string is not input."""
with pytest.raises(TypeError):
numbers = 123
perc_cap_words(numbers)
with pytest.raises(TypeError):
blank = ''
perc_cap_words(blank) | 38,614 |
def T_asymmetry(x, beta):
"""Performs a transformation over the input to break the symmetry of the symmetric functions.
Args:
x (np.array): An array holding the input to be transformed.
beta (float): Exponential value used to produce the asymmetry.
Returns:
The transformed input.
... | 38,615 |
def fit_improved_B2AC_numpy(points):
"""Ellipse fitting in Python with improved B2AC algorithm as described in
this `paper <http://autotrace.sourceforge.net/WSCG98.pdf>`_.
This version of the fitting simply applies NumPy:s methods for calculating
the conic section, modelled after the Matlab code in the... | 38,616 |
def test_atomic_decimal_max_inclusive_2_nistxml_sv_iv_atomic_decimal_max_inclusive_3_2(mode, save_output, output_format):
"""
Type atomic/decimal is restricted by facet maxInclusive with value
-888403528420030673.
"""
assert_bindings(
schema="nistData/atomic/decimal/Schema+Instance/NISTSchem... | 38,617 |
def generate_complex_topologies_and_positions(ligand_filename, protein_pdb_filename):
"""
Generate the topologies and positions for complex phase simulations, given an input ligand file (in supported openeye
format) and protein pdb file. Note that the input ligand file should have coordinates placing the li... | 38,618 |
def aten_append(mapper, graph, node):
""" 构造对list进行append的PaddleLayer。
TorchScript示例:
%90 : int[] = aten::append(%_output_size.1, %v.1)
参数含义:
%90 (list): 输出,append后的list。
%_output_size.1 (list): 需要进行append的list。
%v.1 (-): append的元素。
"""
scope_name = mapper.normal... | 38,619 |
def res_from_obseravtion_data(observation_data):
"""create a generic residual dataframe filled with np.NaN for
missing information
Parameters
----------
observation_data : pandas.DataFrame
pyemu.Pst.observation_data
Returns
-------
res_df : pandas.DataFrame
"""
res_df ... | 38,620 |
def trigger_events(events, loop):
"""Trigger event callbacks (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop
"""
for event in events:
result = event(loop)
if isawaitable(result):
loop.run_until_complete(result) | 38,621 |
async def selfdestruct(destroy):
""" For .sd command, make seflf-destructable messages. """
message = destroy.text
counter = int(message[4:6])
text = str(destroy.text[6:])
await destroy.delete()
smsg = await destroy.client.send_message(destroy.chat_id, text)
await sleep(counter)
await sm... | 38,622 |
def dtype_ripper(the_dtype, min_years, max_years):
"""Extract the range of years from the dtype of a structured array.
Args:
the_dtype (list): A list of tuples with each tuple containing two
entries, a column heading string, and a string defining the
data type for that column. F... | 38,623 |
def ssh_cmd(ssh_cfg, command):
"""Returns ssh command."""
try:
binary = os.environ['SSH_BINARY']
except KeyError:
if os.name != 'nt':
binary = subprocess.check_output(
'which ssh', shell=True).decode(sys.stdout.encoding).strip()
else:
raise Exc... | 38,624 |
def test_sensor_query(cbcsdk_mock):
"""Test the sensor kit query."""
def validate_post(url, param_table, **kwargs):
assert kwargs['configParams'] == 'SampleConfParams'
r = json.loads(kwargs['sensor_url_request'])
assert r == {'sensor_types': [{'device_type': 'LINUX', 'architecture': '64'... | 38,625 |
def write_file (file_name):
"""
Display the contents of the file named on standard output. File is assumed to exist and be readable.
Returns: Nowt.
:param file_name: File name to be written.
"""
f = open (file_name, 'r')
print (f.read ())
f.close () | 38,626 |
def make_all_pages(context, root_box, html, pages):
"""Return a list of laid out pages without margin boxes.
Re-make pages only if necessary.
"""
i = 0
while True:
remake_state = context.page_maker[i][-1]
if (len(pages) == 0 or
remake_state['content_changed'] or
... | 38,627 |
def ExtractParametersBoundaries(Basin):
"""
=====================================================
ExtractParametersBoundaries(Basin)
=====================================================
Parameters
----------
Basin : [Geodataframe]
gepdataframe of catchment polygon, make sure th... | 38,628 |
def encoder_apply_one_shift(prev_layer, weights, biases, act_type, name='E', num_encoder_weights=1):
"""Apply an encoder to data for only one time step (shift).
Arguments:
prev_layer -- input for a particular time step (shift)
weights -- dictionary of weights
biases -- dictionary ... | 38,629 |
def db_entry_generate_id():
""" Generate a new uuid for a new entry """
return str(uuid.uuid4()).lower().replace('-','') | 38,630 |
def get_manager_rest_service_host():
"""
Returns the host the manager REST service is running on.
"""
return os.environ[constants.REST_HOST_KEY] | 38,631 |
def angle_boxplus(a, v):
"""
Returns the unwrapped angle obtained by adding v to a in radians.
"""
return angle_unwrap(a + v) | 38,632 |
def color_gradient_threshold(img, s_thresh=[(170, 255),(170, 255)], sx_thresh=(20, 100)):
"""
Apply a color threshold and a gradient threshold to the given image.
Args:
img: apply thresholds to this image
s_thresh: Color threshold (apply to S channel of HLS and B channel of LAB)
sx_... | 38,633 |
def toeplitz(c, r=None):
"""
Construct a Toeplitz matrix.
The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row. If r is not given, ``r == conjugate(c)`` is
assumed.
Parameters
----------
c : array_like
First column of the matrix. Whateve... | 38,634 |
def upload(ctx, include, exclude, glob, suite_type, role, **kwargs):
"""
upload data defined in suite config files
"""
ctx.obj.update(**kwargs)
ctx.obj.post_process()
namespace = ctx.obj["namespace"]
config_inst = ctx.obj["config"]
yes = ctx.obj["yes"]
echo.echo(f"testsuite namespace... | 38,635 |
def MQWS(settings, T):
"""
Generates a surface density profile as the per method used in Mayer, Quinn,
Wadsley, and Stadel 2004
** ARGUMENTS **
NOTE: if units are not supplied, assumed units are AU, Msol
settings : IC settings
settings like those contained in an IC object (see ... | 38,636 |
async def checkTime():
"""
Main Loop function used for capturing and saving time values used for comparisons
"""
if (datetime.now(pytz.timezone("Etc/GMT+0")) > config.targetTime):
await performanceChart(config.Bot.get_channel(config.channelID))
config.targetTime += timedelta(hours = 24)... | 38,637 |
def process_data(data):
"""Process a chunk of data"""
# BUG
data = data.upper()
df = DBPOOL.runInteraction(real_process, data)
df.addErrback(common.email_error, data) | 38,638 |
def nlp_progress(output, fmt):
"""Extract NLP Progress SOTA tables."""
serialization.dump(tdb=scrapers.nlp_progress(), output=output, fmt=fmt) | 38,639 |
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.):
"""
Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
x : numpy.array
State estimate vector
P : numpy.array
Covariance matrix
F : numpy.array()
State Transitio... | 38,640 |
def footer_processor(request: HttpRequest) -> Dict[str, str]:
"""Add the footer email me message to the context of all templates since the footer is included everywhere."""
try:
message = KlanadTranslations.objects.all()[0].footer_email_me
return {"footer_email_me": message}
except IndexErro... | 38,641 |
def genome_2_validator(genome_2):
"""
Conducts various test to ensure the stability of the Genome 2.0
"""
standard_gene_length = 27
def structure_test_gene_lengths():
"""
Check length requirements for each gene
"""
gene_anomalies = 0
for key in genome_2:
... | 38,642 |
def list_ranking_matrices(database, count):
"""
List all the available ranking matrices.
"""
ranking_matrices = RankingMatrix.list(database, count)
click.echo(
tabulate.tabulate(
[
[
rm.eid[:8],
rm.term_document_matrix.eid[:... | 38,643 |
def product_info_from_tree(path):
"""Extract product information from a directory
Arguments:
path (str): path to a directory
"""
log.debug('Reading product version from %r', path)
product_txt = os.path.join(path, 'product.txt')
if not os.path.isfile(product_txt):
raise Command... | 38,644 |
def to_poly(group):
"""Convert set of fire events to polygons."""
# create geometries from events
geometries = []
for _, row in group.iterrows():
geometry = corners_to_poly(row['H'], row['V'], row['i'], row['j'])
geometries.append(geometry)
# convert to single polygon
vt_poly =... | 38,645 |
def get_user():
"""
Get the current logged in user to Jupyter
:return: (str) name of the logged in user
"""
uname = env_vars.get('JUPYTERHUB_USER') or env_vars.get('USER')
return uname | 38,646 |
def get_top_articles(update=False):
"""
Retrieve 10 most recent wiki articles from the datastore or from memcache
:param update: when this is specified, articles are retrived from the datastore
:return: a list of 10 most recent articles
"""
# use caching to avoid running unnecessary DB queries a... | 38,647 |
def bucket(x, bucket_size):
"""'Pixel bucket' a numpy array.
By 'pixel bucket', I mean, replace groups of N consecutive pixels in
the array with a single pixel which is the sum of the N replaced
pixels. See: http://stackoverflow.com/q/36269508/513688
"""
for b in bucket_size: assert float(b).is... | 38,648 |
def test_operationdefinition_9(base_settings):
"""No. 9 tests collection for OperationDefinition.
Test File: operation-servicedefinition-data-requirements.json
"""
filename = (
base_settings["unittest_data_dir"]
/ "operation-servicedefinition-data-requirements.json"
)
inst = oper... | 38,649 |
def _too_few_peaks_or_valleys(peak_indices: NDArray[int], valley_indices: NDArray[int]) -> None:
"""Raise an error if there are too few peaks or valleys detected.
Args:
peak_indices: a 1D array of integers representing the indices of the peaks
valley_indices: a 1D array of integeres representin... | 38,650 |
def create_msg(q1,q2,q3):
""" Converts the given configuration into a string of bytes
understood by the robot arm.
Parameters:
q1: The joint angle for the first (waist) axis.
q2: The joint angle for the second (shoulder) axis.
q3: The joint angle for the third (wrist) axis.
Returns:
The string of... | 38,651 |
def get_config():
"""Provide the global configuration object."""
global __config
if __config is None:
__config = ComplianceConfig()
return __config | 38,652 |
def size(x: "array.Array") -> "array.Array":
"""Takes a tensor as input and outputs a int64 scalar that equals to the total
number of elements of the input tensor.
Note that len(x) is more efficient (and should give the same result).
The difference is that this `size` free function adds the `Size` node... | 38,653 |
def linspace(start, stop, length):
"""
Create a pdarray of linearly spaced points in a closed interval.
Parameters
----------
start : scalar
Start of interval (inclusive)
stop : scalar
End of interval (inclusive)
length : int
Number of points
Returns
-------... | 38,654 |
def update_roles_descriptions(apps, schema_editor):
"""
Renames the descriptions of the roles to something
more useful
"""
db_alias = schema_editor.connection.alias
role = apps.get_model("api", "Role")
role.objects.using(db_alias).filter(
name="Admin"
).update(
descript... | 38,655 |
def _load_corpus_as_dataframe(path):
"""
Load documents corpus from file in 'path'
:return:
"""
json_data = load_json_file(path)
tweets_df = _load_tweets_as_dataframe(json_data)
_clean_hashtags_and_urls(tweets_df)
# Rename columns to obtain: Tweet | Username | Date | Hashtags | Likes | R... | 38,656 |
def UNTL_to_encodedUNTL(subject):
"""Normalize a UNTL subject heading to be used in SOLR."""
subject = normalize_UNTL(subject)
subject = subject.replace(' ', '_')
subject = subject.replace('_-_', '/')
return subject | 38,657 |
def parse_cigar(cigarlist, ope):
""" for a specific operation (mismach, match, insertion, deletion... see above)
return occurences and index in the alignment """
tlength = 0
coordinate = []
# count matches, indels and mismatches
oplist = (0, 1, 2, 7, 8)
for operation, length in cigarlist:
if operation... | 38,658 |
def _decode_token_compact(token):
"""
Decode a compact-serialized JWT
Returns {'header': ..., 'payload': ..., 'signature': ...}
"""
header, payload, raw_signature, signing_input = _unpack_token_compact(token)
token = {
"header": header,
"payload": payload,
"signature": b... | 38,659 |
def writeStrMaybeList(outF, value, indent=0, maxLen=115):
"""Writes out a string, or a list of strings taking care of escaping it for json.
Lists of strings are indented with a string per line."""
t = type(value)
if issubclass(t, str) or issubclass(t, bytes):
json.dump(value, outF)
else:
... | 38,660 |
def get_object_information(DirectoryArn=None, ObjectReference=None, ConsistencyLevel=None):
"""
Retrieves metadata about an object.
See also: AWS API Documentation
Exceptions
:example: response = client.get_object_information(
DirectoryArn='string',
ObjectReference={
... | 38,661 |
async def main() -> None:
"""Run the application."""
program = cuia.Program(DigitalClock(datetime.now()))
await program.start() | 38,662 |
def _top_N_str(m, col, count_col, N):
"""
Example
-------
>>> df = pd.DataFrame({'catvar':["a","b","b","c"], "numvar":[10,1,100,3]})
>>> _top_N_str(df, col = 'catvar', count_col ='numvar', N=2)
'b (88.6%), a (8.8%)'
"""
gby = m.groupby(col)[count_col].agg(np.sum)
gby = 100 * gby / gb... | 38,663 |
def insert_box(part, box, retries=10):
"""Adds a box / connector to a part using boolean union. Operating under the assumption
that adding a connector MUST INCREASE the number of vertices of the resulting part.
:param part: part to add connector to
:type part: trimesh.Trimesh
:param box: connector ... | 38,664 |
def calc_measurement_loc(inst):
""" Calculate the instrument measurement location in geographic coordinates
Parameters
----------
inst : pysat.Instrument
JRO ISR Instrument object
Note
----
Adds 'gdlat#', 'gdlon#' to the instrument, for all directions that
have azimuth and elev... | 38,665 |
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--task', type=str, required=True)
parser.add_argument('--spacy_model', type=str, default='en_core_web_sm')
parser.add_argument('--omit_answers', action='store_true')
parser.add_argument(... | 38,666 |
def pnorm(x, p):
"""
Returns the L_p norm of vector 'x'.
:param x: The vector.
:param p: The order of the norm.
:return: The L_p norm of the matrix.
"""
result = 0
for index in x:
result += abs(index) ** p
result = result ** (1/p)
return result | 38,667 |
def set_harvest_credentials(harvest_account_id, forecast_account_id, access_token):
"""
Saves Harvest credentials to ~/.wimbledon/.harvest_credentials as a
json file containing a harvest account id, a forecast account id
and an access token.
Get these from https://id.getharvest.com/developers.
... | 38,668 |
def get_arr(logdir_multiseed, acc_thresh_dict=None, agg_mode='median'):
"""
Reads a set of evaluation log files for multiple seeds and computes
the aggregated metrics with error bounds. Also computes the CL metrics
with error bounds.
Args:
logdir_multiseed (str): Path to the parent log fo... | 38,669 |
def save_parcel(obj, filename, comment=None):
"""Saves a given object as a parcel
Parameters
----------
filename : str or File
Name of the file or a file object to which the content of
the object will be saved
comment : str
A comment which will be saved together ... | 38,670 |
def _kneighborsclassifier(*, train, test, x_predict=None, metrics, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs):
"""
For more info visit :
https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsCl... | 38,671 |
def cmv(msg, label=True):
""" print the verbose log msgs belonging to the crypt manager. """
if _DISABLE_LOG_CLASS_CMV:
return
final_msg = None
if label:
final_msg = 'cm verbose: ' + str(msg)
else:
final_msg = str(msg)
print term_light_red + final_msg + term_reset | 38,672 |
def fig_dla_nhi(plate=4484, fiber=364):
""" Plot the NHI values and fits for 2 DLAs
"""
# Generate ID, load, and process the Sightline
dr12_id = Id_DR12.from_csv(plate, fiber)
sightline = read_sightline(dr12_id)
sightline.process(default_model)
# Generate model
full_lam, full_lam_rest, f... | 38,673 |
def write_pickle(data, file_path):
"""write binary contents to a pickle file"""
with open(file_path, 'wb') as f:
pickle.dump(data, f) | 38,674 |
def overlap(batch_x, n_context=296, n_input=39):
"""
Due to the requirement of static shapes(see fix_batch_size()),
we need to stack the dynamic data to form a static input shape.
Using the n_context of 296 (1 second of mfcc)
"""
window_width = n_context
num_channels = n_input
batch_x =... | 38,675 |
def eval_on_train_data_input_fn(training_dir, hyperparameters):
"""
:param training_dir: The directory where the training CSV is located
:param hyperparameters: A parameter set of the form
{
'batch_size': TRAINING_BATCH_SIZE,
'num_epochs': TRAINING_EPOCHS,
'data_downsize':... | 38,676 |
def load_config(config_file):
"""
加载配置文件
:param config_file:
:return:
"""
with open(config_file, encoding='UTF-8') as f:
return json.load(f) | 38,677 |
def decode(var, encoding):
"""
If not already unicode, decode it.
"""
if PY2:
if isinstance(var, unicode):
ret = var
elif isinstance(var, str):
if encoding:
ret = var.decode(encoding)
else:
ret = unicode(var)
els... | 38,678 |
def read_annotation_files(annotation_files_directory: str, audio_files_directory: str,
max_audio_files: int = np.inf, exclude_classes: List[str] = None) -> List[AudioFile]:
"""
Reads annotation files in a directory specified.
:param annotation_files_directory: the directory of the... | 38,679 |
def vehicle_emoji(veh):
"""Maps a vehicle type id to an emoji
:param veh: vehicle type id
:return: vehicle type emoji
"""
if veh == 2:
return u"\U0001F68B"
elif veh == 6:
return u"\U0001f687"
elif veh == 7:
return u"\U000026F4"
elif veh == 12:
return u"\U0... | 38,680 |
def np_function(func=None, output_dtypes=None):
"""Decorator that allow a numpy function to be used in Eager and Graph modes.
Similar to `tf.py_func` and `tf.py_function` but it doesn't require defining
the inputs or the dtypes of the outputs a priori.
In Eager mode it would convert the tf.Tensors to np.array... | 38,681 |
def constituency_parse(doc: List[str]) -> List[Dict]:
"""
parameter: List[str] for each doc
return: List[Dict] for each doc
"""
predictor = get_con_predictor()
results = []
for sent in doc:
result = predictor.predict(sentence=sent)
results.append(result)
assert len(result... | 38,682 |
def sequence_properties(units: List[Unit]) -> Mapping[str, Any]:
"""Extract some data from the unit sequence to be listed in the report.
Return a mapping of label names to values.
All hookimpls will be joined in order of definition.""" | 38,683 |
def ifFileExists(filePath):
"""
Cheks if the file exists; returns True/False
filePath File Path
"""
return os.path.isfile(filePath) | 38,684 |
def extract_results(filename):
""" Extract intensity data from a FLIMfit results file.
Converts any fraction data (e.g. beta, gamma) to contributions
Required arguments:
filename - the name of the file to load
"""
file = h5py.File(filename,'r')
results = file['results']
keys = sorted_nicely(... | 38,685 |
async def bundle_status(args: Namespace) -> ExitCode:
"""Query the status of a Bundle in the LTA DB."""
response = await args.di["lta_rc"].request("GET", f"/Bundles/{args.uuid}")
if args.json:
print_dict_as_pretty_json(response)
else:
# display information about the core fields
p... | 38,686 |
def determine_step_size(mode, i, threshold=20):
"""
A helper function that determines the next action to take based on the designated mode.
Parameters
----------
mode (int)
Determines which option to choose.
i (int)
the current step number.
threshold (float)
The ... | 38,687 |
def profile(args):
"""
Create an orthography profile for a string (passed as argument or read from stdin)
segments profile [STRING]
"""
_write(args, Profile.from_text(_read(args))) | 38,688 |
def scroll_down(driver):
"""
This function will simulate the scroll down of the webpage
:param driver: webdriver
:type driver: webdriver
:return: webdriver
"""
# Selenium supports execute JavaScript commands in current window / frame
# get scroll height
last_height = driver.execut... | 38,689 |
def main():
"""Main function for setuptools console_scripts"""
tornado.options.parse_command_line()
options = tornado.options.options
if options.version:
print(__version__)
return
port, debug = options.port, options.debug
if not debug:
# FIXME
LOG.warning('Only d... | 38,690 |
async def test_change_cidr_network(ops_test):
"""Test configuration change."""
flannel = ops_test.model.applications["flannel"]
await flannel.set_config({"cidr": "10.2.0.0/16"})
rc, stdout, stderr = await ops_test.run(
"juju", "run", "-m", ops_test.model_full_name, "--application", "flannel",
... | 38,691 |
def processing():
"""Renders the khan projects page."""
return render_template('stem/tech/processing/gettingStarted.html', title="Processing - Getting Started", year=datetime.now().year) | 38,692 |
def conv_unit(input_tensor, nb_filters, mp=False, dropout=0.1):
"""
one conv-relu-bn unit
"""
x = ZeroPadding2D()(input_tensor)
x = Conv2D(nb_filters, (3, 3))(x)
x = relu()(x)
x = BatchNormalization(axis=3, momentum=0.66)(x)
if mp:
x = MaxPooling2D(pool_size=(3, 3), strides=(2, ... | 38,693 |
def combine_vectors(x, y):
"""
Function for combining two vectors with shapes (n_samples, ?) and (n_samples, ?).
Parameters:
x: (n_samples, ?) the first vector.
In this assignment, this will be the noise vector of shape (n_samples, z_dim),
but you shouldn't need to know the second dime... | 38,694 |
def expandMacros(context, template, outputFile, outputEncoding="utf-8"):
"""
This function can be used to expand a template which contains METAL
macros, while leaving in place all the TAL and METAL commands.
Doing this makes editing a template which uses METAL macros easier,
becau... | 38,695 |
def graph_papers(path="papers.csv"):
"""
Spit out the connections between people by papers
"""
data = defaultdict(dict)
jkey = u'Paper'
for gkey, group in groupby(read_csv(path, key=jkey), itemgetter(jkey)):
for pair in combinations(group, 2):
for idx,row in enumerate(pair... | 38,696 |
def tariterator1(fileobj, check_sorted=False, keys=base_plus_ext, decode=True):
"""Alternative (new) implementation of tariterator."""
content = tardata(fileobj)
samples = group_by_keys(keys=keys)(content)
decoded = decoder(decode=decode)(samples)
return decoded | 38,697 |
def wait_for_gcp_account():
"""Wait until we are able to get a service account.
see https://github.com/kubeflow/code-intelligence/issues/88
"""
# TODO(jlewi): Should we use the python library instead of gcloud?
logging.info("Checking for GCP credentials")
credentials = GoogleCredentials.get_app... | 38,698 |
def juego_nuevo():
"""Pide al jugador la cantidad de filas/columnas, cantidad de palabras y las palabras."""
show_title("Crear sopa de NxN letras")
nxn = pedir_entero("Ingrese un numero entero de la cantidad de\nfilas y columnas que desea (Entre 10 y 20):\n",10,20)
n_palabras = pedir_entero("I... | 38,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.