content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_net_dev(dev):
"""Delete a network device only if it exists."""
if device_exists(dev):
try:
utils.execute('ip', 'link', 'delete', dev, run_as_root=True,
check_exit_code=[0, 2, 254])
LOG.debug("Net device removed: '%s'", dev)
except proc... | 46,900 |
def _maybe_node_for_newtype(
typ: Union[NewType, Any],
overrides: OverridesT,
memo: MemoType,
forward_refs: ForwardRefs
) -> Tuple[Optional[schema.nodes.SchemaNode], MemoType, ForwardRefs]:
""" newtypes do not change the underlying runtime data type that is used in
calls like isinstance(), there... | 46,901 |
def read_slug(filename):
"""
Returns the test slug found in specified filename.
"""
with open(filename, "r") as f:
slug = f.read()
return slug | 46,902 |
def boolean_value(value):
"""Given a Value, returns whether the object is statically known to be truthy.
Returns None if its truth value cannot be determined.
"""
if isinstance(value, KnownValue):
try:
return bool(value.val)
except Exception:
# Its __bool__ thre... | 46,903 |
def _Import(name):
"""Import a module or package if it is not already imported."""
module = sys.modules.get(name, None)
if module is not None:
return module
return import_module(name, None) | 46,904 |
def delete_document(client: SymphonyClient, document: Document) -> None:
"""This function deletes existing document.
Args:
document ( `pyinventory.consts.Document` ): document object
Raises:
FailedOperationException: on operation failure
Example:
```
... | 46,905 |
def bin_sparse(X, file, scan_names, bins, max_parent_mass = 850, verbose=False, window_filter=True, filter_window_size=50, filter_window_retain=3):
""" Parses and bins a single MGF file into a matrix that holds the charge intensities of all the spectra
Args:
X: Scipy sparse matrix in the format of bins... | 46,906 |
def print_schema_banner(schema):
"""
Prints a banner to call out the schema name.
:param schema: The schema
"""
print('-- *************************************')
print('-- * SCHEMA: ' + schema.name)
print('-- *************************************') | 46,907 |
def test_conv3d():
"""
Test the layer.Conv3d class and its default attributes. No need to test the call() function since its
a tensorflow class
"""
conv3d = layer.Conv3d(8)
assert isinstance(conv3d._conv3d, type(tf.keras.layers.Conv3D(8, 3)))
assert conv3d._conv3d.kernel_size == (3, 3, 3)
... | 46,908 |
def debug_logging(severity, message, output="file"):
"""
debug_logging
Function to log debugging details to log file or stdout
severity = the severity of the debug message. Should be Information, Debug, or Error
message = the message to log
output (default is file) = the output method, c... | 46,909 |
def ls_img_sequence(path):
"""Listing all available coherent image sequence from path
Arguments:
path (str): A nuke's node object
Returns:
data (dict): with nuke formated path and frameranges
"""
file = os.path.basename(path)
dirpath = os.path.dirname(path)
base, ext = os.p... | 46,910 |
def _convert_to_dict(tracked_dict):
"""
Recursively convert a Pony ORM TrackedDict to a normal Python dict
"""
if not isinstance(tracked_dict, orm.ormtypes.TrackedDict):
return tracked_dict
return {k: _convert_to_dict(v) for k, v in tracked_dict.items()} | 46,911 |
def sky_coords(cluster):
"""Get the sky coordinates of every star in the cluster
Parameters
----------
cluster : class
StarCluster
Returns
-------
ra,dec,d0,pmra,pmdec,vr0 : float
on-sky positions and velocities of cluster stars
History
-------
2018 - Writt... | 46,912 |
def create_log_file(*, fn_log="tomo_info.dat", wd=".", hdf5_ext="h5"):
"""
Create log file ``fn`` based on the files contained in ``wd``. If ``fn``
is a relative path, it is assumed that the root is in ``wd``.
"""
wd = _process_dir(wd)
fn_log = _process_fn(fn_log, fn_dir=wd)
# Create the li... | 46,913 |
def macro_cons_silver_volume():
"""
全球最大白银 ETF--iShares Silver Trust 持仓报告, 数据区间从 20060429-至今
:return: pandas.Series
"""
t = time.time()
res = requests.get(
JS_CONS_SLIVER_ETF_URL.format(
str(int(round(t * 1000))), str(int(round(t * 1000)) + 90)
)
)
json_data =... | 46,914 |
def scan_files(prefix):
""" Gets all words from all files ending in the specified prefix and returns
them as a list.
"""
files = ['/'.join([data.DATA_DIR, f])
for f in os.listdir(data.DATA_DIR) if f.startswith(prefix)]
words = []
for f in files:
with open(f, 'r') as wf:... | 46,915 |
def test_backend_features_interface(cseabreeze, pyseabreeze):
"""test if the public backend feature class interfaces are identical"""
c_feature_interface = _get_class_public_interface_dict(cseabreeze)
py_feature_interface = _get_class_public_interface_dict(pyseabreeze)
# test if there's a difference be... | 46,916 |
def get_jasper(version,
use_dw=False,
use_dr=False,
bn_epsilon=1e-3,
vocabulary=None,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs)... | 46,917 |
def test_db_shell(app_scaffold, dev_db): # noQA
"""Create an application and see if db-shell is started."""
execute_ws_command('ws-db-shell', app_scaffold, wait_and_see=2.0) | 46,918 |
def preprocess_img(img):
"""Preprocessing function for images."""
return img/255 | 46,919 |
def test_pdbqt():
"""RDKit PDBQT writer and reader"""
mol = next(oddt.toolkit.readfile('sdf', xiap_actives))
mol2 = oddt.toolkit.readstring('pdbqt', mol.write('pdbqt'))
assert mol.title == mol2.title
# test loop breaks in DFS algorithm
mol = oddt.toolkit.readstring('smi', 'CCc1cc(C)c(C)cc1-c1cc... | 46,920 |
def get_apitools_metadata_from_url(cloud_url):
"""Takes storage_url.CloudUrl and returns appropriate Apitools message."""
messages = apis.GetMessagesModule('storage', 'v1')
if cloud_url.is_bucket():
return messages.Bucket(name=cloud_url.bucket_name)
elif cloud_url.is_object():
generation = int(cloud_url... | 46,921 |
def test_collect():
"""Tests the recursive_collect function"""
collect = t.recursive_collect
# Generate a few objects to find
find_me = [Dummy(i) for i in range(5)]
d = dict(
a=1,
b=tuple([1, 2, find_me[0], find_me[1]]),
c=find_me[2],
d=dict(aa=find_me[3], bb=2, cc=... | 46,922 |
def branch(ref=None):
"""Return the name of the current git branch."""
ref = ref or "HEAD"
return local("git symbolic-ref %s 2>/dev/null | awk -F/ {'print $NF'}"
% ref, capture=True) | 46,923 |
def fit_anis(celldmsx, Ex, ibrav=4, out=False, type="quadratic", ylabel="Etot"):
"""
An auxiliary function for handling fitting in the anisotropic case
"""
if out:
print (type+" fit")
if type=="quadratic":
a, chi = fit_quadratic(celldmsx, Ex, ibrav, out, ylabel)
eli... | 46,924 |
def solicitacao_incluir(discente, sugestao_turma):
"""
Inclui uma Solicitação de interesse do Discente na Sugestão de Turma.
:param discente: Um objeto da classe @Discente
:param sugestao_turma: Um objeto da classe @SugestaoTurma
:return: Um objeto da classe @SolicitacaoTurma e um booleano informand... | 46,925 |
def _evolve_trotter_gates(psi,
layers,
step_size,
num_steps,
euclidean=False,
callback=None):
"""Evolve an initial wavefunction psi via gates specified in `layers`.
If the evolution is... | 46,926 |
def load_worksheet(
filename,
sheet=None,
worksheet=0,
skip_rows=0,
csv_delimiter=DEFAULT_CSV_DELIMITER,
ext=None,
):
"""
Load a worksheet from a supported file format
:param filename: File to be loaded
:type filename: str
:param sheet: If not None, load the data into the sh... | 46,927 |
def _get_next_traj_id(root_data_dir='data'):
""" Resolve what is the next trajectory number """
if not os.path.exists(os.path.join(root_data_dir, 'screens')):
return 0
return 1 + max([
int(x) for x in os.listdir(os.path.join(root_data_dir, 'screens'))
]) | 46,928 |
def get_user(email):
""" Sometimes user account is setup using @gmail.com domain,
but android phone says @googlemail.com and vice versa
"""
try:
if 'googlemail' in email or 'gmail' in email:
uname = email.partition('@')[0]
users = User.objects.filter(Q(email=uname+'@googl... | 46,929 |
def test_meta_data():
""" BDD Scenario. """ | 46,930 |
def test_tuning_gpu_inherits_pass_context(target, dev):
"""Autotvm tuner inherits PassContexts but also adds a gpu verification pass by default.
Test that using PassContext inherits passes properly but also runs gpu verification pass.
"""
from tvm.tir.analysis import _ffi_api as _analysis_ffi_api
... | 46,931 |
def make_scae(config):
"""Builds the SCAE."""
# return: model 应该是整个的要训练的model了吧
# 这个好像是要transform 训练集
# canvas & template size 都有什么用呢 在这里?
img_size = [config.canvas_size] * 2
template_size = [config.template_size] * 2
# 这个只是part encoder的一部分, 用的是卷积,直接就是4个卷积层了 padding可以自动, snt NB!!
'''
Sequential(
(... | 46,932 |
def get_materialization_versions(dataset_name, materialization_endpoint=None):
""" Gets materialization versions with timestamps """
if materialization_endpoint is None:
materialization_endpoint = analysisdatalink.materialization_endpoint
url = '{}/api/dataset/{}'.format(materialization_endpoin... | 46,933 |
def WilcoxonRankSum(tpms):
"""May be very slow for large datasets."""
wrs = tpms[['SMTSD', 'ENSG']].copy().drop_duplicates().sort_values(by=['SMTSD', 'ENSG'])
wrs.reset_index(drop=True, inplace=True)
wrs['stat'] = pd.Series(dtype=float)
wrs['pval'] = pd.Series(dtype=float)
for smtsd in wrs.SMTSD.unique():
... | 46,934 |
def filter_image(image, filter_DFT):
"""
Just takes the DFT of a filter and applies the filter to an image
This may optionally pad the image so as to match the number of samples in the
filter DFT. We should make sure this is greater than or equal to the size of
the image.
"""
assert image.dtype == 'float... | 46,935 |
def create_database(server, db_name, encoding=None):
"""This function used to create database and returns the database id"""
db_id = ''
try:
connection = get_db_connection(
server['db'],
server['username'],
server['db_password'],
server['host'],
... | 46,936 |
def _create_diff_matrix(n, order=1):
"""Creates n x n matrix subtracting adjacent vector elements
Example:
>>> print(_create_diff_matrix(4, order=1))
[[ 1 -1 0 0]
[ 0 1 -1 0]
[ 0 0 1 -1]]
>>> print(_create_diff_matrix(4, order=2))
[[ 1 -1 0 0]
... | 46,937 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv:
argv = sys.argv
# setup command line parser
parser = E.OptionParser(version="%prog version: $Id$",
usage=globals()["__doc__"])
parser... | 46,938 |
def test_potential_vorticity_baroclinic_non_unity_derivative(pv_data):
"""Test potential vorticity calculation with unity stability and height on axis 0."""
u, v, lats, _, dx, dy = pv_data
potential_temperature = np.ones((3, 4, 4)) * units.kelvin
potential_temperature[0] = 200 * units.kelvin
potent... | 46,939 |
def fourier_frequencies_from_times(times):
"""
Calculates the Fourier frequencies from a set of times. These frequencies are in 1/units, where
`units` is the units of time in `times`. Note that if the times are not exactly equally spaced,
then the Fourier frequencies are ill-defined, and this returns th... | 46,940 |
def application_tags(ctx: click.Context, application_tags):
"""Reads json string with application tags. Eg:'[{"tag":"MELPCFR030", "category":"wgs",...},...]'"""
adapter = ctx.obj["adapter"]
LOG.info("Reading json.")
try:
json_list = json.loads(application_tags)
except json.JSONDecodeError as... | 46,941 |
def lint(ctx):
"""lint - check style with flake8."""
ctx.run('flake8 nsct tests') | 46,942 |
def fission(candidate_seed, pop, n, max_seed_area):
"""
In fusion, we use the convention of putting one seed on
the left and the other seed on the right, before we fuse
the two seeds. In fission, we assume that fission will
split the left part from the right part. Find the most
sparse column in the... | 46,943 |
def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
param:
box: tuple or array, shifted to the origin (i. e. width and height)
clusters: numpy array of shape (k, 2) where k is the number of clusters
return:
numpy array of shape (... | 46,944 |
def write_and_verify_qr_code(name, filename, data):
"""
Write a QR code and then read it back to try and detect any tricksy malware tampering with it.
name: <string> short description of the data
filename: <string> filename for storing the QR code
data: <string> the data to be encoded
"""
... | 46,945 |
def test_camel_to_snake():
"""Test camel_to_snake"""
assert camel_to_snake('') == ''
assert camel_to_snake('foo') == 'foo'
assert camel_to_snake('Foo') == 'foo'
assert camel_to_snake('fooBar') == 'foo_bar'
assert camel_to_snake('fooBarBaz') == 'foo_bar_baz' | 46,946 |
def lambda_handler(event, context):
"""Secrets Manager Rotation Template
This is a template for creating an AWS Secrets Manager rotation lambda
Args:
event (dict): Lambda dictionary of event parameters. These keys must include the following:
- SecretId: The secret ARN or identifier
... | 46,947 |
def cli():
"""CLI utility to interact with ETNA's APIs.""" | 46,948 |
def munge_av_status(av_statuses):
"""Truncate and lowercase availability_status"""
return [a[20:].lower() for a in av_statuses] | 46,949 |
def cdf(vals, reverse=False):
"""Computes the CDF of a list of values"""
vals = sorted(vals, reverse=reverse)
tot = float(len(vals))
x = []
y = []
for i, x2 in enumerate(vals):
x.append(x2)
y.append((i+1) / tot)
return x, y | 46,950 |
def user_document_verification(request, document_id):
"""Display user's document information request.
Args:
request: URL request
document_request_id: document ID in firebase
Returns:
Render user document verification view.
"""
# Document Data
document_ref = db.collection("d... | 46,951 |
def get_not_repeated_file_name(path_with_file):
"""
Returns file_name if file_name does not exist. If it exists, it appends an underscore until
this new file name does not exist, returning it. For example if "/home/mine/file.txt" exists,
it will return "/home/mine/_file.txt".
@param path_with_... | 46,952 |
def validate_repos(repos):
""" Validate repository objects. """
if type(repos) is not list:
raise Exception('repos must be a list, not "%s"' % type(repos))
for repo in repos:
validate_repo(repo) | 46,953 |
def attr(name, thing=word, subtype=None):
"""Generate an Attribute with that name, referencing the thing.
Instance variables:
Class Attribute class generated by namedtuple()
"""
# if __debug__:
# if isinstance(thing, (tuple, list)):
# warnings.warn(type(thing).__name__... | 46,954 |
def bulk_records(
name: str,
bulk: TextClassificationBulkData,
common_params: CommonTaskQueryParams = Depends(),
service: TextClassificationService = Depends(
TextClassificationService.get_instance
),
datasets: DatasetsService = Depends(DatasetsService.get_instance),
current_user: Us... | 46,955 |
def environment_list(p_engine, p_username, format, envname):
"""
Print list of environments
param1: p_engine: engine name from configuration
param2: format: output format
param3: envname: environemnt name to list, all if None
return 0 if environment found
"""
ret = 0
enginelist = ... | 46,956 |
def loss(logits, labels, weight_decay_factor, class_weights = None):
"""
Total loss:
----------
Args:
logits: Tensor, predicted [batch_size * height * width, num_classes]
labels: Tensor, ground truth [batch_size, height, width, 1]
weight_decay_factor: float, factor with which... | 46,957 |
async def _(bot: Bot, event: GroupMessageEvent):
"""
/删头衔 @user 删除头衔
"""
msg = str(event.get_message())
stitle = msg.split()[-1:][0]
logger.info(str(msg.split()), stitle)
sb = At(event.json())
gid = event.group_id
if sb:
if len(msg.split()) == len(sb) + 1 and 'all' not in sb:... | 46,958 |
def apply_Ry(psi, theta, i, parametrize=False, **gate_opts):
"""Apply a Y-rotation of ``theta`` to tensor network wavefunction ``psi``.
"""
mtags = _merge_tags('RY', gate_opts)
if parametrize:
G = ops.PArray(ry_gate_param_gen, (theta,))
else:
G = qu.Ry(float(theta))
psi.gate_(G, ... | 46,959 |
def negative(num):
"""assumes num is a numeric
returns a boolean, True if num is negative, else False"""
return num < 0 | 46,960 |
def readSudokus(filename):
"""
Returns the n first sudokus of the file with given name
"""
f = open(filename)
res = None
txt = f.readline().strip()
if txt != "":
res = [[int(txt[i + j * 9]) for i in range(9)] for j in range(9)]
f.close()
return np.array(res) | 46,961 |
def plot_spatial_correlation(anomlous = False, temporal_resolution = 'monthly', detrend = 'raw', temp_decomp = 'anomalous', imagefolder = 'images/correlations/spatial/', n = 5, seaice_source='nsidc'):
"""Summary
Args:
anomlous (bool, optional): Description
temporal_resolution (str, optional... | 46,962 |
def script_info(base_app):
"""Get ScriptInfo object for testing a CLI command.
Scope: module
.. code-block:: python
def test_cmd(script_info):
runner = CliRunner()
result = runner.invoke(mycmd, obj=script_info)
assert result.exit_code == 0
"""
from flas... | 46,963 |
def provideCommonTimerSymbols( aComponent ):
""" Symbol interface required to be a TMR provider to SYS_TIME """
global instanceName
timerStartApiName = instanceName.getValue() + "_TimerStart"
timerStopApiName = instanceName.getValue() + "_TimerStop "
compareSetApiName = instanceName.ge... | 46,964 |
def measured_points(idf, return_periods, interim_results=None, max_duration=None):
"""
get the calculation results of the rainfall with u and w without the estimation of the formulation
Args:
idf (IntensityDurationFrequencyAnalyse): idf class
return_periods (float | np.array | list | pd.Ser... | 46,965 |
def is_serial_port_fixture() -> Generator[MagicMock, None, None]:
"""Patch the serial port check."""
with patch("homeassistant.components.mysensors.gateway.cv.isdevice") as is_device:
is_device.side_effect = lambda device: device
yield is_device | 46,966 |
def get_charpixel():
""" Render a single charpixel """
if options.table == 'input':
c = getch()
if c in ['\n','\t']:
print(c)
else:
c = choice( CHARTABLES[ options.table ] )
return c.encode('utf-8') | 46,967 |
def marathon_check(service_path):
"""Check whether a marathon yaml file exists in service directory, and
print success/failure message.
:param service_path: path to a directory containing the marathon yaml
files
"""
if is_file_in_dir('marathon*.yaml', service_path):
... | 46,968 |
def test_custom_fixer():
""" Test custom ParseFixer
Verify that read_csv uses custom ParseFixer
"""
class fix_pi(ParseFixer):
def __init__(self):
super().__init__()
# augment existing method, simple fix float
def fix_illegal_cell_value(self, vtype, value):
... | 46,969 |
def context_factory(policy, name):
"""Factory function for creating context objects."""
if not isinstance(name, qpol.qpol_context_t):
raise TypeError("Contexts cannot be looked-up.")
return Context(policy, name) | 46,970 |
def decode_mail_header(value, default_charset='us-ascii'):
"""Decode a header value into a unicode string."""
try:
headers = decode_header(value)
except email.errors.HeaderParseError:
return value.encode(default_charset, 'replace').decode(default_charset)
else:
for index, (text, ... | 46,971 |
def pack():
"""
create a new source distribution as tarball
"""
with project():
local('python setup.py sdist --formats=gztar', capture=False) | 46,972 |
def typing(session: Session) -> Session:
"""Run the type checker (using mypy)."""
args = session.posargs or locations
install(session, "mypy")
session.run("mypy", *args)
# mypy module_name | 46,973 |
def xyz2xyzr(xyz: np.ndarray, *,
axis: int=None,
illuminant: Illuminant=get_default_illuminant(),
observer: Observer=get_default_observer()) -> np.ndarray:
"""
Convert XYZ to normalized XYZ reflectance
:param xyz: the raw xyz values
:param axis: the axis that the X... | 46,974 |
def last_updated(a):
"""
Check the time since file was last updated.
"""
return time.time() - op.getmtime(a) | 46,975 |
def lstm_acd_decomposition(inp, model):
"""
inp: tf.Tensor(dtype=np.int32, shape=(1, -1)) tokenized input
model: tf.keras.Model or equivalent
"""
l = inp.numpy().size
e, k, rk, b, dw, db = model.weights
embed_inp = tf.nn.embedding_lookup(params=e, ids=inp)
return acd_1d_decomposition(... | 46,976 |
def modify_ad_attributes(distinguished_name, validated_entry, ldap_conn):
"""
Modify the the (user | group) with the filtered attributes
from sawtooth_entry.
"""
for ad_attribute in validated_entry:
if ad_attribute == "member":
ldap_conn.modify(
dn=disting... | 46,977 |
def ST_IsValid(geos):
"""
Check if geometry is of valid geometry format.
:type geos: Series(dtype: object)
:param geos: Geometries in WKB form.
:rtype: Series(dtype: bool)
:return: True if geometry is valid.
:example:
>>> import pandas
>>> import arctern
>>> data = panda... | 46,978 |
def initializeProject(root, settings):
"""
Initialize a project at the given root.
"""
writeSettings(root, settings)
archiveDirectory = getArchiveDirectory(root, settings)
if archiveDirectory == getDefaultArchiveDirectory(root):
if not os.path.exists(archiveDirectory):
os.mkd... | 46,979 |
def import_email(assessment, campaign_number, template_smtp):
"""Import email from file."""
temp_template = Template(name=f"{assessment.id}-T{str(campaign_number)}")
temp_smtp = copy.deepcopy(template_smtp)
temp_smtp.name = f"{assessment.id}-SP-{campaign_number}"
# Receives the file name and checks... | 46,980 |
def get_framerate(has_already_started,
start_time,
frame_counter,
frame_rate,
frame_num=5,
decimal_round_num=2):
""" Returns current framerate of video based on
time elapsed in frame_num frames.
Works in a while loop ... | 46,981 |
def check_for_solve(grid):
""" checks if grid is full / filled"""
for x in range(9):
for y in range(9):
if grid[x][y] == 0:
return False
return True | 46,982 |
def Sn(i, length):
"""Convert an int to a binary string."""
s = ''
while i != 0:
digit = i & 0xff
i >>= 8
s += chr(digit)
if len(s) > length:
raise Exception("Integer too big to fit")
while len(s) < length:
s += chr(0)
return s | 46,983 |
def _get_config_file_schema():
"""
Return the path to the parameters file json schema.
"""
module_file = _decode_filesystem_path(__file__)
return os.path.join(os.path.dirname(module_file), "pystepsrc_schema.json") | 46,984 |
def test_create_tmp_meta_recipe_env_file():
"""
Test that the create_tmp_meta_recipe_env_file() method creates a tmp dir for meta-recipe env info
"""
tmp_dir, env_json, env_commands = utils.create_tmp_meta_recipe_env_file()
## Check that the dir exits and that it is writeable
assert os.path.e... | 46,985 |
def parse_args():
"""Parse command line arguments"""
parser = ArgumentParser(
description='Print contents of a parsed config file',
formatter_class=ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
'pipeline', metavar='CONFIGFILE',
nargs='?',
default='settings... | 46,986 |
def run_best_experiments(map: Map):
"""Run a series of experiments among Random, Linear, and the Best Curiosity agents for various starting position."""
# Some high-level parameters
num_starting_positions = 10
random.seed(12345)
base_results_dir = "results2_best"
path_length = 1000
fov = 64... | 46,987 |
def _normalize_annotation(annotation, tag_index):
"""
Normalize the annotation anchorStart and anchorEnd,
in the sense that we start to count the position
from the beginning of the sentence
and not from the beginning of the disambiguated page.
:param annotation: Annotation object
:param tag_index: start index... | 46,988 |
def read_lc(csvfile, comment='|'):
"""
Read a light curve csv file from gAperture.
:param csvfile: The name of the csv file to read.
:type csvfile: str
:param comment: The character used to denote a comment row.
:type comment: str
:returns: pandas DataFrame -- The contents of the csv fi... | 46,989 |
def check_cutoffs(cutoffs):
"""Validates the cutoff
Parameters
----------
cutoffs : np.ndarray or pd.Index
Returns
----------
cutoffs (Sorted array)
Raises
----------
ValueError
If cutoffs is not a instance of np.array or pd.Index
If cutoffs array is empty.
... | 46,990 |
def hook(images, augmenter, parents, default):
"""Determines which augmenters to apply to masks."""
return augmenter.__class__.__name__ in MASK_AUGMENTERS | 46,991 |
def _get_videos(course, pagination_conf=None):
"""
Retrieves the list of videos from VAL corresponding to this course.
"""
videos, pagination_context = get_videos_for_course(
str(course.id),
VideoSortField.created,
SortDirection.desc,
pagination_conf
)
videos = li... | 46,992 |
def test_flatten_repeated_variable_in_rule():
"""
Given a program with the rule `R(x, x) :- Q(x, x, z)` and a (single
predicate) conjunctive query `R(x, y)`, we expect the resulting flattened
query to be either `Q(y, y, _freshvar_), x = y` or `Q(x, x, _freshvar_), y
= x`.
"""
rule = Implica... | 46,993 |
def sample_stacking_program(num_primitives, device, address_suffix="", fixed_num_blocks=False):
"""Samples blocks to stack from a set [0, ..., num_primitives - 1]
*without* replacement. The number of blocks is stochastic and
can be < num_primitives.
Args
num_primitives (int)
device
... | 46,994 |
def get_mmr_address(rn, m0m1):
"""Return address of an memory-mapped register and its size in bits.
"""
mmr_map = { 0b00 : 0xf0400,
0b01 : 0xf0500,
0b10 : 0xf0600,
0b11 : 0xf0700 }
address = mmr_map[m0m1] + (rn * 0x4)
size = get_register_size_by_addres... | 46,995 |
def add_adversarial_constraint(model, logit_vars, true_label, logit_bounds):
""" Adds the adversarial constraint to the model
Two cases here:
1) only two valid logits could be maximal, so
"""
if len(logit_vars) == 2:
model.addConstr(logit_vars[true_label] <= logit_vars[1 - true_... | 46,996 |
def with_translations(**columns):
"""Decorator that creates a translations table for the decorated model.
Creates a table mapped to a ``ModelTranslations`` class (given a
decorated model class ``Model``) containing the provided `**columns`,
with references to the :class:`.Language` and the decorated mo... | 46,997 |
def _delete_paths_from_glob(root_dir: Path, paths_glob: str):
"""Delete paths matching the glob"""
old_paths = (root_dir / paths.SPRITES_FOLDER).glob(paths_glob)
for old_path in old_paths:
os.remove(old_path) | 46,998 |
def thread_map(func, data):
"""
http://code.activestate.com/recipes/577360-a-multithreaded-concurrent-version-of-map/
"""
#todo: this is disabled
return map(func, data)
N = len(data)
result = [None] * N
# wrapper to dispose the result in the right slot
def task_wrapper(i):
result[i] = func(data[i])
threa... | 46,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.