content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_best_model(X ,y):
"""Select best model from RandomForestClassifier and AdaBoostClassifier"""
ensembles = [
(RandomForestClassifier, SelectParam({
'estimator': RandomForestClassifier(warm_start=True, random_state=7),
'param_grid': {
'n_estimators': [10, 15,... | 28,200 |
def compareDates(dateA: list, dateB: list) -> int:
"""
Compares dateA and dateB\n
returns: 1 if dateA > dateB,\n
-1 if dateA <dateB,
0 if dateA == dateB \n
raise Exception if dates are invalid
"""
if not checkDateValidity(dateA, dateB):
raise invalidDateException('Invalid Dates')... | 28,201 |
def test_1():
""" Run regression test 1 """
raw = struct.pack('<BBIIIIIIBIIIIBII',
3, 3, 0, 100, 1, 101, 2, 102, 2, 3, 103, 4, 104, 1, 5, 105)
packet = Packet1.from_raw(raw)
# Parent packet has 3 sub packets
assert packet['size1'] == 3
assert len(packet['data1']... | 28,202 |
def shell():
"""Jump into a Python Shell"""
env = {
'__grains__': __grains__,
'__opts__': __opts__,
'__pillar__': __pillar__,
'__salt__': __salt__,
'__out__': salt.loader.outputters(__opts__),
'pprint': pprint.pprint,
}
try:
import readline
ex... | 28,203 |
def renderPage(res, topLevelContext=context.WebContext,
reqFactory=FakeRequest):
"""
Render the given resource. Return a Deferred which fires when it has
rendered.
"""
req = reqFactory()
ctx = topLevelContext(tag=res)
ctx.remember(req, inevow.IRequest)
render = appserver... | 28,204 |
def test_generate_vols():
"""Generate all isovolume files."""
# assert flags
r1 = r2 = False
# test database path
db = test_dir + "/test-gen-vols"
if isdir(db):
shutil.rmtree(db)
# init ivdb obj
iv = ivdb.IvDb(levels=levels, data=data, db=db)
iv.generate_vols(test_mesh)
#... | 28,205 |
def get_header_value(headers, name, default=None):
""" Return header value, doing case-insensitive match """
if not headers:
return default
if isinstance(headers, dict):
headers = headers.items()
name = to_bytes(name.lower())
for k, v in headers:
if name == to_bytes(k.lower... | 28,206 |
def fill_tract_income_marginals(marginals, tract_geoid, cols, total_col='b19025_001'):
"""Fill in missing income marginals for a tract, based on the proportion of the
income each race holds in the puma"""
tract_agg_income = marginals.loc[cols, tract_geoid]
agg_income = marginals.loc[total_col, tract_ge... | 28,207 |
def login_to_garmin_connect(args):
"""
Perform all HTTP requests to login to Garmin Connect.
"""
if python3:
username = args.username if args.username else input('Garmin Account Email: ')
else:
username = args.username if args.username else raw_input('Garmin Account Email: ')
pas... | 28,208 |
def parse_gt_from_anno(img_anno, classes):
"""parse_gt_from_anno"""
print('parse ground truth files...')
ground_truth = {}
for img_name, annos in img_anno.items():
objs = []
for anno in annos:
if anno[1] == 0. and anno[2] == 0. and anno[3] == 0. and anno[4] == 0.:
... | 28,209 |
def pt_to_tup(pt):
"""
Convenience method to generate a pair of two ints from a tuple or list.
Parameters
----------
pt : list OR tuple
Can be a list or a tuple of >=2 elements as floats or ints.
Returns
-------
pt : tuple of int
A pair of two ints.
"""
return (... | 28,210 |
def item_vector():
"""
get item vectors
"""
args = parse_args()
# check argument
assert os.path.exists(
args.model_path), 'The model_path path does not exist.'
assert os.path.exists(
args.feature_dict), 'The feature_dict path does not exist.'
paddle.init(use_gpu=False, ... | 28,211 |
def _operation(m1, m2, op, k):
"""Generalized function for basic"""
"""matrix operations"""
n = len(m1)
res = [n*[0] for i in range(n)]
if n == len(m2):
for i in range(n):
for j in range(n):
tab = {
"+" : m1[i][j]+m2[i][j],
"-" : ... | 28,212 |
def jacobi_d1(x, n, alpha, beta):
"""Evaluate the first derivative of Jacobi polynomial at x using eq. A.1.8
Args:
x: the location where the value will be evaluated
n: the order of Jacobi polynomial
alpha: the alpha parameter of Jacobi polynomial
beta: the beta parameter of Jaco... | 28,213 |
def gate_expand_1toN(U, N, target):
"""
Create a Qobj representing a one-qubit gate that act on a system with N
qubits.
Parameters
----------
U : Qobj
The one-qubit gate
N : integer
The number of qubits in the target space.
target : integer
The index of the tar... | 28,214 |
def build_component_dependency_graph(
pipeline_definition: Dict[str, Any], component_definitions: Dict[str, Any]
) -> DiGraph:
"""
Builds a dependency graph between components. Dependencies are:
- referenced components during component build time (e.g. init params)
- predecessor components in the pi... | 28,215 |
def count_distribution_artefacts(distribution_artefacts):
"""
Count distribution artefacts in nested list.
:param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants
:type distribution_artefacts: dict
:return: Amount of distribution artefacts
... | 28,216 |
def nelson_siegel_yield(tau, theta):
"""For details, see here.
Parameters
----------
tau : array, shape (n_,)
theta : array, shape (4,)
Returns
-------
y : array, shape (n_,)
"""
y = theta[0] - theta[1] * \
((1 - np.exp(-theta[3] * tau)) /
(theta[... | 28,217 |
def AskNoti():
"""[To replace the notification from one folder to the storage and send the email to the respective members.]
"""
C_Noti = input("Enter the path of the notification: ")
if not os.path.exists(C_Noti):
print("Path doesnot exists...")
return
T_Path = os.path.join(GetPath(... | 28,218 |
def parsing(lst=None):
"""
Function for parsing command line
>>> parsing(["2020", "80", "90", "dataset"])
(2020, 80.0, 90.0, 'dataset')
"""
parser = argparse.ArgumentParser(description="""Module, which reads data from a file\
with a films list, determines films, \
made in the given ye... | 28,219 |
def main() -> None:
"""
Process raw data.
Delete blacklisted corrupted images. Trim a footer from each image
and resize it to 512 pixels on its shorter dimension. Write results
to "autofocus/data/processed/images". Reformat labels from CSV and
write to a new file "autofocus/data/processed/label... | 28,220 |
def fix_filename(filename):
"""Replace illegal or problematic characters from a filename."""
return filename.translate(_filename_trans) | 28,221 |
def buildgnuf2py(mode, exflags, modulename, sourcefiles, includes=None, opt="O2", wraponly=None,
outdir="./", srcdir="./src/", tmpdir="./tmp/", env=None, verbose=True):
"""
Compiles a single PYD using the gfortran compiler
Parameters:
-----------
mode: str
either `r... | 28,222 |
def test_epsilon_reduction_unit_recursion(interface: AltInterface, grammar: str):
"""
Testing sequence of grammar algorithms: epsilon rules removal, grammar reduction, unit rules removal and left
recursion removal. In each step checking for valid output type.
:param interface: `pytest fixture` returni... | 28,223 |
def QDenseModel(weights_f, load_weights=False):
"""Construct QDenseModel."""
x = x_in = Input((RESHAPED,), name="input")
x = QActivation("quantized_relu(4)", name="act_i")(x)
x = QDense(N_HIDDEN, kernel_quantizer=ternary(),
bias_quantizer=quantized_bits(4, 0, 1), name="dense0")(x)
x = QActivatio... | 28,224 |
def _load_config():
"""Load the StreamAlert Athena configuration files
Returns:
dict: Configuration settings by file, includes two keys:
lambda, All lambda function settings
global, StreamAlert global settings
Raises:
ConfigError: For invalid or missing configuratio... | 28,225 |
def fmt_uncertainty(x, dx, sn=None, sn_cutoff=8, unit=None):
"""Format uncertainty for latex."""
n_decimals = -int(np.floor(np.log10(np.abs(dx))))
leading_magnitude = np.abs(dx)/10**-n_decimals
if leading_magnitude <= 1.5:
n_decimals += 1
if sn is None:
if np.abs(x) >= 10**sn_cutoff ... | 28,226 |
def seed_test_input(clusters, limit):
"""
Select the seed inputs for fairness testing
:param clusters: the results of K-means clustering
:param limit: the size of seed inputs wanted
:return: a sequence of seed inputs
"""
i = 0
rows = []
max_size = max([len(c[0]) for c in clu... | 28,227 |
def construct_validation_report(group_id, root_dir):
"""
Load data and perform calculations to check how close the approximated
model results conform with NEMDE solutions
"""
# Load results and convert to JSON
results = parse_validation_results(group_id=group_id)
# Construct directory wher... | 28,228 |
def calc_senescence_water_shading(
aglivc, bgwfunc, fsdeth_1, fsdeth_3, fsdeth_4):
"""Calculate shoot death due to water stress and shading.
In months where senescence is not scheduled to occur, some shoot death
may still occur due to water stress and shading.
Parameters:
agliv... | 28,229 |
def hello(friend_name: float = None) -> str:
"""Function to greet the user, takes a string and return Hello, 'string'"""
if not isinstance(friend_name, str):
raise TypeError("this function expects a string as input")
return f'Hello, {friend_name}!' | 28,230 |
def flatten(lst):
"""Shallow flatten *lst*"""
return [a for b in lst for a in b] | 28,231 |
def _transform_org_units(metadata: dict) -> pd.DataFrame:
"""Transform org units metadata into a formatted DataFrame."""
df = pd.DataFrame.from_dict(metadata.get("organisationUnits"))
df = df[["id", "code", "shortName", "name", "path", "geometry"]]
df.columns = ["ou_uid", "ou_code", "ou_shortname", "ou_... | 28,232 |
def post_process(done_exec, temp_file):
"""For renaissance, `temp_file` is a path to a CSV file into which the
results were written. For other suites, it is `None`."""
if done_exec.suite == "renaissance":
assert temp_file is not None
return post_process_renaissance(done_exec, temp_file)
... | 28,233 |
def freeze(regex_frozen_weights):
"""Creates an optimizer that set learning rate to 0. for some weights.
Args:
regex_frozen_weights: The regex that matches the (flatten) parameters
that should not be optimized.
Returns:
A chainable optimizer.
"""
return scale_selected_parameters(regex_frozen_w... | 28,234 |
def white_corners(cube_obj):
"""
Outputs the moves list for solving the down face corner cubies after
solving for the white cross
"""
# search for cubies and move into place
# corner DFR
cstate = cube_obj.cb
cubies = cube_obj.cubies
if is_white_corners(cstate):
print("white ... | 28,235 |
def test_check_classic_valid_without_preprocessor(points):
"""Test that valid inputs when using no preprocessor raises no warning"""
with pytest.warns(None) as record:
check_input(points, type_of_inputs='classic', preprocessor=None)
assert len(record) == 0 | 28,236 |
def print_line_and_file_at_callsite(indirection_number):
"""
Prints the line and filename.
If 1 is passed it prints at function call site
If 2 is passed it prints at callsite of a function
which called the function which contained this
Purpose:
When you use VSCode it should jump you t... | 28,237 |
def runner_setup(loop) -> None:
"""Adds exit signals to the given asyncio loop on which the app exits gracefully"""
signals = (
signal.SIGHUP,
signal.SIGTERM,
signal.SIGINT,
signal.SIGQUIT
)
for s in signals:
loop.add_signal_handler(s, raise_graceful_exit) | 28,238 |
def test_event_loop_fixture(event_loop):
"""Test the injection of the event_loop fixture."""
assert event_loop
ret = event_loop.run_until_complete(async_coro(event_loop))
assert ret == 'ok' | 28,239 |
def store_sourceip_telemetry():
"""
route to handle inbound telemetry from daemonset ip collector agents
"""
# load up some context so we can append to it
context = SourceIpTelemetry.get_instance()
if context.data:
telemetry = context.get()
else:
telemetry = {}
payload = ... | 28,240 |
def test_html_whitelist_h2_h3_h4_h5_h6():
"""hN elements represent headings for their sections in ranked order."""
check_html_output_contains_text("""
<h2>Second level</h2>
<h3>Third level</h3>
<h2>Also second-level</h2>
<h3>Third level</h3>
<h4>Fourth level</h4>
... | 28,241 |
def sep_num(number, space=True):
"""
Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for
the separator otherwise it will use commas
Note
----
Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separ... | 28,242 |
def raw_smooth_l1_loss(diff, delta=1.0, max_val=10.0):
"""
Creates smooth L1 loss. The regular version is sometimes unstable so here what we do is if the difference
is > some value, we will return the log instead.
So it's then
0.5 * x^2 if |x| ... | 28,243 |
def model_f2_statistics(mode_path, val_index=1, save_dir=None, save_file=None):
"""
对model目录下的所有包含"evaluate"字段的文件进行统计,分别得到all-label、one-label统计
:param mode_path: 需要统计的目录
:param save_file: 输入文件
:return:
"""
evaluate_files = []
for root, dirs, files in os.walk(mode_path):
... | 28,244 |
def read_parameters(request, view_kwargs):
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:rtype: dict[str, object]
"""
params = {}
errors = {}
for param in request.api_info.operation.parameters:
try:
... | 28,245 |
def box_off(ax):
"""
similar to Matlab's box off
"""
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left() | 28,246 |
def lookup_batch():
"""Look up parameters.
The mini-batched version of lookup. The resulting expression will be a mini-batch of parameters, where the "i"th element of the batch corresponds to the parameters at the position specified by the "i"th element of "indices"
Args:
p(LookupParameters): ... | 28,247 |
def handler(body, archiveFile=None):
""" Execute the SED-ML files in a COMBINE/OMEX archive.
Args:
body (:obj:`dict`): dictionary with schema ``SimulationRun`` with the
specifications of the COMBINE/OMEX archive to execute and the simulator to execute it with
archiveFile (:obj:`werk... | 28,248 |
def test_plot_html():
"""xfield and yfield defined at plot level"""
generate_html("level_plot.yml") | 28,249 |
def get_passwd():
"""Prompt user for a password
Prompts user to enter and confirm a password. Raises an exception
if the password is deemed to be invalid (e.g. too short), or if
the password confirmation fails.
Returns:
Password string entered by the user.
"""
passwd = getpass.getpa... | 28,250 |
def _render_footnote_block_open(self, tokens, idx, options, env):
"""Render the footnote opening without the hr tag at the start."""
html = mdit_py_plugins.footnote.index.render_footnote_block_open(
self, tokens, idx, options, env
)
lines = html.split("\n")
if lines[0].strip().startswith("<h... | 28,251 |
def project_remove(flox: Flox, feature: str):
"""Remove plugin features from active project"""
if feature not in flox.meta.features:
raise PluginException(
f"Plugin {feature} is not enabled for '{flox.meta.name}' project",
extra=f"You can list installed plugins with `flox info`"
... | 28,252 |
def test_matcher_pipe_with_matches_and_context(nlp: Language) -> None:
"""It returns a stream of Doc objects and matches and context as tuples."""
warnings.filterwarnings("ignore")
doc_stream = (
(nlp("test doc 1: Corvold"), "Jund"),
(nlp("test doc 2: Prosh"), "Jund"),
)
matcher = To... | 28,253 |
def remove_shot_from_scene(scene, shot, client=default):
"""
Remove link between a shot and a scene.
"""
scene = normalize_model_parameter(scene)
shot = normalize_model_parameter(shot)
return raw.delete(
"data/scenes/%s/shots/%s" % (scene["id"], shot["id"]),
client=client
) | 28,254 |
def all_results_failed(subsystems):
"""Check if all results have failed status"""
for subsystem in subsystems.values():
if subsystem['subsystemStatus'] == 'OK':
# Found non-failed subsystem
return False
# All results failed
return True | 28,255 |
def get_scene_id(current_scene_db):
"""gets the scene ID from the scene db"""
from src.praxxis.sqlite import connection
conn = connection.create_connection(current_scene_db)
cur = conn.cursor()
get_scene_id = 'SELECT ID FROM "SceneMetadata"'
cur.execute(get_scene_id)
id = str(cur.fetchone()... | 28,256 |
def compile_playable_podcast1(playable_podcast1):
"""
@para: list containing dict of key/values pairs for playable podcasts
"""
items = []
for podcast in playable_podcast1:
items.append({
'label': podcast['title'],
'thumbnail': podcast['thumbnail'],
'path... | 28,257 |
def mouseclick(pos):
"""
Define "mouse click" event handler; implements game
"state" logic. It receives a parameter; pair of screen
coordinates, i.e. a tuple of two non-negative integers
- the position of the mouse click.
"""
# User clicks on a "card" of the "deck" (grid of
# ev... | 28,258 |
def __get_ip_udp_int_pkt(ip_pkt):
"""
Retrieves the INT UDP packet
:param ip_pkt:
:return:
"""
logger.info('Obtaining INT data')
udp_pkt = UDP(_pkt=ip_pkt.payload)
logger.debug('UDP packet dport - [%s]', udp_pkt.dport)
if udp_pkt.dport == trans_sec.consts.UDP_INT_DST_PORT:
lo... | 28,259 |
def fixture_version_obj(bundle_data: dict, store: Store) -> models.Version:
"""Return a version object"""
return store.add_bundle(bundle_data)[1] | 28,260 |
def redirect_log(job, filename="run.log", formatter=None, logger=None):
"""Redirect all messages logged via the logging interface to the given file.
This method is a context manager. The logging handler is removed when
exiting the context.
Parameters
----------
job : :class:`signac.contrib.job... | 28,261 |
def ranges_compute(x, n_bins):
"""Computation of the ranges (borders of the bins).
Parameters
----------
x: pd.DataFrame
the data variable we want to obtain its distribution.
n_bins: int
the number of bins we want to use to plot the distribution.
Returns
-------
ranges:... | 28,262 |
def creation(basis_size: int, state_index: int) -> spr.csc_matrix:
"""
Generates the matrix of the fermionic creation operator for a given single particle state
:param basis_size: The total number of states in the single particle basis
:param state_index: The index of the state to be created by the oper... | 28,263 |
def save_vis_performance_dfg(dfg: dict, start_activities: dict, end_activities: dict, file_path: str,
aggregation_measure="mean"):
"""
Saves the visualization of a performance DFG
Parameters
----------------
dfg
DFG object
start_activities
Start activiti... | 28,264 |
def test_dont_merge_station_epochs():
"""
Stations might have epochs with different information - don't merge these
then.
"""
filename = os.path.join(data_dir, "multi_station_epoch.xml")
inv = obspy.read_inventory(filename)
assert len(inv.get_contents()["stations"]) == 3
assert len(inv.g... | 28,265 |
def LowercaseMutator(current, value):
"""Lower the value."""
return current.lower() | 28,266 |
def gtf2gff(gtfname,gffname, memt=True):
"""Convert GTF to GFF.
Args:
gtfname: path to GTF file
gffname: path for converted GFF file
memt: only select multiexon, multitranscript
Returns:
Pandas.DataFrame containing converted GFF data
"""
eids = read_gtf(gtfname,
... | 28,267 |
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, verbose_logging, logger):
"""Write final predictions to the json file."""
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
... | 28,268 |
def setup_view(view, request, *args, **kwargs):
"""Mimic ``as_view()``, but returns view instance.
Use this function to get view instances on which you can run unit tests,
by testing specific methods.
See https://stackoverflow.com/a/33647251 and
http://django-downloadview.readthedocs.io/en/latest/t... | 28,269 |
def get_density(molecule_name, temperature=273.15, pressure=101325,
cycles=5000, init_cycles="auto",
forcefield="CrystalGenerator"):
"""Calculates the density of a gas through an NPT ensemble.
Args:
molecule_name: The molecule to test for adsorption. A file of the same
... | 28,270 |
def print_json(field):
"""Print the definition of one field, in JSON"""
print(json.dumps(field, indent=4)) | 28,271 |
def is_node_up(config, host):
"""
Calls nodetool statusbinary, nodetool statusthrift or both. This function checks the output returned from nodetool
and not the return code. There could be a normal return code of zero when the node is an unhealthy state and not
accepting requests.
:param health_che... | 28,272 |
def audits(program):
"""Create 2 audits mapped to the program"""
return [rest_facade.create_audit(program) for _ in xrange(2)] | 28,273 |
def _create_run(uri, experiment_id, work_dir, entry_point):
"""
Create a ``Run`` against the current MLflow tracking server, logging metadata (e.g. the URI,
entry point, and parameters of the project) about the run. Return an ``ActiveRun`` that can be
used to report additional data about the run (metric... | 28,274 |
def delete(sock, buffer_size, param):
"""DELETE request
Args:
sock(socket.socket): socket object
buffer_size(int): maximum size of received message buffer
param(str): parameter of pathname
"""
header = 'DELETE /products/%s HTTP/1.1\r\n' \
'Host: localhost:8080\r\n' \... | 28,275 |
def _call_pt_lines_to_flows():
""" Call directly ptlines2flows from sumo/tools. """
pt_flows_options = ptlines2flows.get_options(['-n', DEFAULT_NET_XML,
'-e', '86400',
'-p', '600',
... | 28,276 |
def test_str_lower():
"""Test string conversion to lowercase using ``.str.lower()``."""
df = pd.DataFrame(
{
"codes": range(1, 7),
"names": [
"Graham Chapman",
"John Cleese",
"Terry Gilliam",
"Eric Idle",
... | 28,277 |
def convertBoard(board):
"""
converts board into numerical representation
"""
flatBoard = np.zeros(64)
for i in range(64):
val = board.piece_at(i)
if val is None:
flatBoard[i] = 0
else:
flatBoard[i] = {"P": 1, "N" : 2, "B" : 3, "R" : ... | 28,278 |
def merge_optional(default_dict: Dict[str, Any], update_dict: Dict[str, Any], tpe: str):
"""
Function to merge dictionaries to add set parameters from update dictionary into default dictionary.
@param default_dict: Default configuraiton dictionary.
@type default_dict: dict
@param update_dict: Update... | 28,279 |
def reference_pixel_map(dimensions, instrument_name):
"""Create a map that flags all reference pixels as such
Parameters
----------
dimensions : tup
(y, x) dimensions, in pixels, of the map to create
instrument_name : str
Name of JWST instrument associated with the data
Return... | 28,280 |
def geocode(value, spatial_keyword_type='hostname'):
"""convenience function to geocode a value"""
lat, lon = 0.0, 0.0
if spatial_keyword_type == 'hostname':
try:
hostname = urlparse(value).hostname
url = 'http://ip-api.com/json/%s' % hostname
LOGGER.info('Geocodi... | 28,281 |
def deploy_contract(w3, document_page_url, secret_key):
"""
TDeploy the contract
:param w3: the w3 connection
:param document_page_url: the document page url
:param secret_key: the operator secret key
:return: a pari tx_receipt, abi
"""
# 1. declare contract
document_sc = w3.eth.cont... | 28,282 |
def format_date(format_string=None, datetime_obj=None):
"""
Format a datetime object with Java SimpleDateFormat's-like string.
If datetime_obj is not given - use current datetime.
If format_string is not given - return number of millisecond since epoch.
:param format_string:
:param datetime_ob... | 28,283 |
def testdata(request):
"""
If expected data is required for a test this fixture returns the path
to a folder with name '.testdata' located in the same director as the
calling test module
"""
import pathlib
testdata_dir = '.testdata'
module_dir = pathlib.Path(request.fspath).parent
re... | 28,284 |
def delete_user_pool_domain(Domain=None, UserPoolId=None):
"""
Deletes a domain for a user pool.
See also: AWS API Documentation
Exceptions
:example: response = client.delete_user_pool_domain(
Domain='string',
UserPoolId='string'
)
:type Domain: string
... | 28,285 |
def set_price(location, algo, order, price):
"""
https://api.nicehash.com/api?method=orders.set.price&id=8&key=3583b1df-5e93-4ba0-96d7-7d621fe15a17&location=0&algo=0&order=1881&price=2.1
:param location:
:param algo:
:param order:
:param price:
:return:
"""
resp = query('orders.set.p... | 28,286 |
def setFonts(typ):
"""
Sets fonts for standard font-types
:param typ: one of sans-serif-afm, serif (sans-serif is default on init)
:type typ: str
"""
if typ == 'sans-serif-afm':
baseNameDict = {
'Helvetica': "_a______",
'Helvetica-Bold': "_ab_____",... | 28,287 |
def iterate_datalog_program(datalog_program):
"""
Iterate each rule in the AST generated from the datalog program and print the complete datalog program
"""
rule_count = 0
for datalog_rule in datalog_program:
print(str(rule_count) + ':')
print(iterate_datalog_rule(datalog_rule))
... | 28,288 |
def jaccard_coef_loss(y_true, y_pred):
"""
Loss based on the jaccard coefficient, regularised with
binary crossentropy
Notes
-----
Found in https://github.com/ternaus/kaggle_dstl_submission
"""
return (-K.log(jaccard_coef(y_true, y_pred)) +
K.binary_crossentropy(y_pred, y_t... | 28,289 |
def __apply_rule_to_files_dataset_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, preferred_rse_ids=[], source_rses=[], session=None):
"""
Apply a rule to files with ALL grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict... | 28,290 |
def call_webhook(event, webhook, payload):
"""Build request from event,webhook,payoad and parse response."""
started_at = time()
request = _build_request_for_calling_webhook(event, webhook, payload)
logger.info('REQUEST %(uuid)s %(method)s %(url)s %(payload)s' % dict(
uuid=str(event['uuid']),
... | 28,291 |
def test_compute_min_dist():
"""Test computation of minimum distance between two molecules"""
mol1_pos = np.array([[-1, -1, -1], [1, 1, 1]], np.float)
mol2_pos = np.array([[3, 3, 3], [3, 4, 5]], np.float)
mol3_pos = np.array([[2, 2, 2], [2, 4, 5]], np.float)
assert compute_min_dist(mol1_pos, mol2_po... | 28,292 |
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') | 28,293 |
def default_user_agent():
"""Return a string representing the default user agent."""
return f'airslate/{__version__} ({__url__})' | 28,294 |
def join_complementary_byteblocks(block) -> int:
"""
join_complementary_byteblocks used to combine low bit data and high bit data
as the representation of complementary code
Parameters
----------
block : list
Low Digit Block -> int
High Digit Block -> int
Returns
------... | 28,295 |
def seed(func):
""" Decorator to seed the RNG before any function. """
@wraps(func)
def wrapper(*args, **kwargs):
numpy.random.seed(0)
return func(*args, **kwargs)
return wrapper | 28,296 |
def trim_bandstructure(
energy_cutoff: float, band_structure: BandStructure
) -> BandStructure:
"""
Trim the number of bands in a band structure object based on a cutoff.
Args:
energy_cutoff: An energy cutoff within which to keep the bands. If the system
is metallic then the bands t... | 28,297 |
def color_text(text: str, *colors: str):
"""
Applies color to a specific string and appends the color code to set the
text to normal. Text can be various colors by adding more args for colors.
Parameters
----------
text: str
String to color
colors: Tuple[str]
Any amount of c... | 28,298 |
def _run_command(c: InvokeContext, cmd: str) -> CommandResult:
"""
Command runner.
:argument c: InvokeContext
:argument cmd: str the command to run
"""
try:
result = c.run(cmd)
return CommandResult(
exit_code=result.exited,
message=result.stdout,
... | 28,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.