content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def attr_names(obj):
"""
Determine the names of user-defined attributes of the given SimpleNamespace object.
Source: https://stackoverflow.com/a/27532110
:return: A list of strings.
"""
return sorted(obj.__dict__) | 5,316,800 |
def get_scada_range(
network: Optional[NetworkSchema] = None,
networks: Optional[List[NetworkSchema]] = None,
network_region: Optional[str] = None,
facilities: Optional[List[str]] = None,
energy: bool = False,
) -> Optional[ScadaDateRange]:
"""Get the start and end dates for a network query. Thi... | 5,316,801 |
def treetable(childreds, parents, arg3=None, nodename_colname=None):
""" 输入childres子结点id列表,和parents父结点id列表
两个列表长度必须相等
文档:http://note.youdao.com/noteshare?id=126200f45d301fcb4364d06a0cae8376
有两种调用形式
>> treetable(childreds, parents) --> DataFrame (新建df)
>> treetable(df, child_colname, parent_c... | 5,316,802 |
def plot_drawdown_periods(returns, top=10, k=None, ax=None, **kwargs):
"""
Plots cumulative returns highlighting top drawdown periods.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
... | 5,316,803 |
def test_constrained_layout5():
"""
Test constrained_layout for a single colorbar with subplots,
colorbar bottom
"""
# Remove this line when this test image is regenerated.
plt.rcParams['pcolormesh.snap'] = False
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in ... | 5,316,804 |
def redirect_back(endpoint='index', **values):
"""
跳转(优先next, 其次endpoint)
:param endpoint:
:param values:
:return:
"""
target = request.args.get('next')
if not target or not is_safe_url(target):
target = url_for(endpoint, **values)
return redirect(target) | 5,316,805 |
def load(
tag: t.Union[str, Tag],
model_store: "ModelStore" = Provide[BentoMLContainer.model_store],
) -> t.Union["BaseEstimator", "Pipeline"]:
"""
Load a model from BentoML local modelstore with given name.
Args:
tag (:code:`Union[str, Tag]`):
Tag of a saved model in BentoML lo... | 5,316,806 |
def tag_to_python(tag):
""" Convert a stream tag to a Python-readable object """
newtag = PythonTag()
newtag.offset = tag.offset
newtag.key = pmt.to_python(tag.key)
newtag.value = pmt.to_python(tag.value)
newtag.srcid = pmt.to_python(tag.srcid)
return newtag | 5,316,807 |
def play_liked(entities: DottedDict, interface: InterfaceIO) -> None:
"""Play liked tracks."""
_spotify.play_liked_tracks() | 5,316,808 |
def iter_nomenclature_plugins() -> Iterable[Obo]:
"""Get all modules in the PyOBO sources."""
from .sources import ontology_resolver
for _prefix, cls in sorted(ontology_resolver.lookup_dict.items()):
yield cls() | 5,316,809 |
def corrections(word_in, dictionary, keyboard_cm, ed=2):
"""
@input: word_in - input word
dictionary - dictionary/lexicon
keyboard_cm - confusion matrix for keyboard in question
"""
assert isinstance(dictionary, Dictionary)
candidates = oridam_generate_patterns(word_in, keyboard_cm... | 5,316,810 |
def _updatelogger(self, *args, **kwargs):
"""Renew self logger."""
self._logger = self.newlogger() | 5,316,811 |
def test_handler_no_pending(mock_config, mock_secrets):
"""When there is no pending version to change"""
mock_secrets.describe_secret.return_value = {
'RotationEnabled': True,
'VersionIdsToStages': {
'token': []
}
}
mock_secrets.get_secret_value.return_value = {'Secre... | 5,316,812 |
def read_polyglot_embeddings(filename):
"""
Read vocabulary and embeddings from a file from polyglot.
"""
with open(filename, 'rb') as f:
data = cPickle.load(f)
# first four words are UNK, <s>, </s> and padding
# we discard <s> and </s>
words = data[0]
matrix = data[1].astyp... | 5,316,813 |
def exp_by_squaring(x, n):
"""Assumes n>=0
See: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
"""
if n == 0:
return 1
if n % 2 == 0:
return exp_by_squaring(x * x, n // 2)
else:
return x * exp_by_squaring(x * x, (n - 1) / 2) | 5,316,814 |
async def test_integration_already_exists(hass):
"""Test we only allow a single config flow."""
MockConfigEntry(
domain=DOMAIN,
data={},
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={}
)
assert re... | 5,316,815 |
def validate_BOOLYN(in_value, restriction):
"""
Restriction is not used here. It is just present to be
in line with all the other validation functions
"""
value = _get_val(in_value)
if type(value) is list:
for subval in value:
if type(subval) is tuple:
... | 5,316,816 |
def test_populated_rel_rover_camera(pre_pop_transaction, global_environ):
"""Test that Rover-Camera relationships of prepopulated DB are correct."""
for camera in DBSession.query(Camera).all():
assert camera.rover_name
for rover in DBSession.query(Rover).all():
assert rover.cameras.count() >... | 5,316,817 |
def dagster_type_materializer(config_schema, required_resource_keys=None):
"""Create an output materialization hydration config that configurably materializes a runtime
value.
The decorated function should take the execution context, the parsed config value, and the
runtime value and the parsed config ... | 5,316,818 |
def get_models(deploy_cfg: Union[str, mmcv.Config],
model_cfg: Union[str, mmcv.Config], work_dir: str) -> List:
"""Get the output model informantion for deploy.json.
Args:
deploy_cfg (mmcv.Config): Deploy config dict.
model_cfg (mmcv.Config): The model config dict.
work_d... | 5,316,819 |
def remain_search(ai_settings, car, markstats):
"""小车在丢失标志物时尝试自动转向搜索"""
cnt = np.array([0, 0, 0])
turnleft_angle = ai_settings.remain_angle_left
turnright_angle = ai_settings.remain_angle_right
centerx_thre_left = ai_settings.centerx_thre_left
centerx_thre_right = ai_settings.centerx_thre_right
... | 5,316,820 |
def restart_script() -> None:
"""Restart the current script."""
args = [sys.executable, "-m", "userbot"]
if sys.platform.startswith('win'):
os.spawnle(os.P_NOWAIT, sys.executable, *args, os.environ)
else:
os.execle(sys.executable, *args, os.environ)
sys.exit(0) | 5,316,821 |
def weighted_choice(choices):
"""
Pick a weighted value off
:param list choices: Each item is a tuple of choice and weight
:return:
"""
total = sum(weight for choice, weight in choices)
selection = random.uniform(0, total)
counter = 0
for choice, weight in choices:
if count... | 5,316,822 |
def run_trf(input,trf_path,trf_options,nproc,output,verbose=True):
""" Run trf with the options provided """
tempfile_list=[]
datfile_list=[]
commands=[]
# check for one process and if so just run trf directly
if nproc == 1:
commands.append([[trf_path,input]+trf_options.split(" "),"trf... | 5,316,823 |
def update_mt(model, mt_model, alpha, step):
""" The brain of the whole thing. Takes two models then sets the
mean teacher model to use the EMA of the student models """
alpha = min(1 - 1 / (step + 1), alpha)
for ema_p, param in zip(mt_model.parameters(), model.parameters()):
ema_p.data.mul_(al... | 5,316,824 |
def css_s(property, value):
"""Creates a stringified CSSString proto with the given values"""
return proto_to_str(make_cssstyle_proto(property, value)) | 5,316,825 |
def parse_args(args):
"""
Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')
parser.add_argument('--data-path', help='Data for prediction', type=str, required=True)
parser.add_argument('--target-path', help='Target p... | 5,316,826 |
async def get_expired_members(request):
"""
Returns a list of all members that should have finished their degree, calculated by current semester and normed time
for each members associated study programme.
:param request:
:return: List of all expired members.
"""
try:
(conn, cur) =... | 5,316,827 |
def sim_hawkes(dims, adjacency, decays, baseline, kernel_support, max_points, run_time, phi_inv, plot=False, seed=None, track_intensity=False):
"""Simulate point process using Ogata razor.
Input
- S: Settings dictionary
- plot: Indication of whether to plot events and intensities
- seed: Seed for r... | 5,316,828 |
def convert_entities_from_file_to_csv(infile, outfile):
"""Convert entities from a file to CSV format.
:param infile: The file name to read entities from. Formatted as jsonlines
(http://jsonlines.org/) - one line per entity.
:param outfile: The file name to write entities to as CSV.
"""
if o... | 5,316,829 |
def ADD(sum, augend, addend):
"""
args:
sum: the register where the addition result is stored.
augend: the left operand of the addition.
addend: the right operand of the addition.
function:
Performs basic addition.
"""
return TacInstruction(instructions.ADD, sum, aug... | 5,316,830 |
def none_of(*query_expressions):
"""Match none of the query parameters given as arguments and keyword arguments"""
pass | 5,316,831 |
def __convert__(filename):
"""Convert a python script so that it can be called by slave.
The converted file is named by appending '_converted' to the filename."""
with open(filename,'r') as f:
script = f.read()
if '#main' not in script:
raise SlaveError('Could not find #main section in {... | 5,316,832 |
def parse_value(str_val, type):
""" Parse the string representation of a value (e.g., for use with an attribute of an XML object)
Args:
str_val (:obj:`str`): string representation of the value
type (:obj:`ValueType`): type
Returns:
:obj:`object`: Python representation of the value
... | 5,316,833 |
def display_training_pair(input_cuboid, output_cuboid, axis=2, **kwargs):
"""Display both given three-dimensional input images with a slider for the third dimension.
Args:
input_cuboid: three-dimensional array that contains the scan
output_cuboid: three-dimensional array that contains the segme... | 5,316,834 |
def test_invalid_mode_values(invalid_mode_values: Any) -> None:
"""
Ensure that passing in non-integers results in Type exceptions
"""
with pytest.raises(ValueError):
convert_to_numeral(10, mode=invalid_mode_values) | 5,316,835 |
def test_train_small_model_multi_target(subset_moddata, tf_session):
"""Tests the multi-target training."""
from modnet.models import MODNetModel
data = subset_moddata
# set 'optimal' features manually
data.optimal_features = [
col for col in data.df_featurized.columns if col.startswith("El... | 5,316,836 |
def _ls_emr_step_logs(fs, log_dir_stream, step_id=None):
"""Yield matching step logs, optionally filtering by *step_id*.
Yields dicts with the keys:
path: path/URI of step file
step_id: step_id in *path* (must match *step_id* if set)
"""
matches = _ls_logs(fs, log_dir_stream, _match_emr_step_lo... | 5,316,837 |
def main(dataset=None):
"""Generates anchors info which is used for mini batch sampling.
Processing on 'Cars' can be split into multiple processes, see the Options
section for configuration.
Args:
dataset: KittiDataset (optional)
If dataset is provided, only generate info for that ... | 5,316,838 |
def propeller_icon(icon, **kwargs):
"""
Render an icon
**Tag name**:
propeller_icon
**Parameters**:
icon
Icon name. See the `Propeller docs <http://propeller.in/style/icons.php>`_ for all icons.
size
Size of the icon. Must be one of 'xs', 'sm', 'md', ... | 5,316,839 |
def sbasis(i, n):
"""Standard basis vector e_i of dimension n."""
arr = np.zeros(n)
arr[i] = 1.0
return arr | 5,316,840 |
def get_users():
"""return users in admin."""
current_app.logger.debug(u'Get all users in admin.')
return render_template('admin/users/list.html') | 5,316,841 |
def InputForm(action_runner, input_text, input_id, form_id=None):
"""Sets the text value of an input field in a form on the page.
Waits until the input element exists on the page. Then executes JS to populate
the value property of the element with |input_text|.
Args:
action_runner: ActionRunner instance t... | 5,316,842 |
def decrypt(text):
"""
:param str text:
:rtype: str
"""
plain = []
for i in range(0, len(text), 2):
num, = struct.unpack('!B', text[i])
plain.append(decrypt_bets.get(num))
return ''.join(plain) | 5,316,843 |
def analyze_shots(path):
# [START video_analyze_shots]
""" Detects camera shot changes. """
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.SHOT_CHANGE_DETECTION]
operation = video_client.annotate_video(path, features=features)
print(... | 5,316,844 |
def LF_warning_signs_hypothetical(c):
"""
Check if candidate is in a list of warning signs e.g.
preceded by 'Warning Signs:'
:param c: pain-anatomy candidate
:return: -1 if True, 0 otherwise
"""
sent_spans = get_sent_candidate_spans(c)
sent = ''
for span in sent_spans:
word... | 5,316,845 |
def render_upcoming_events(event_amount=5, category=None):
"""Template tag to render a list of upcoming events."""
return {
'occurrences': _get_upcoming_events(
amount=event_amount, category=category),
} | 5,316,846 |
def aggregate_collate_fn(insts: List) -> Dict[str, List[str]]:
"""aggragate the instance to the max seq length in batch.
Args:
insts: list of sample
Returns:
"""
snts, golds = [], []
for inst in insts:
snts.append(inst['snt'])
golds.append(inst['gold'])
assert len(sn... | 5,316,847 |
def isBetween(p1, p2, p, epsilon=1e-5):
""" test if p is between p1 and p2
Parameters
----------
p1 : np.array
p2 : np.array
p : np.array
epsilon : float
tolerance default 1e-5
Returns
-------
boolean
Examples
--------
>>> p1 = np.array([0,0])
>>> p2... | 5,316,848 |
def test_logging_field_styles():
"""
Raise no error when passing a custom field style
"""
custom_style = {'asctime': {'color': 'white', 'bright': True},
'levelname': {'color': 'white', 'bright': True},
'name': {'color': 'yellow', 'bright': True}}
log_handler ... | 5,316,849 |
def quit():
"""
quit the program
Note: you could put the sys.exit call directly in the dict
but this lets you put extra code in there if you want.
"""
sys.exit(0) | 5,316,850 |
def add_match(guild, match):
"""Inserts match data into database
Args:
guild (int): ID of guild
match (Match): Match to add to database
"""
conn = sqlite3.connect('jit.db')
c = conn.cursor()
data = (guild, match.id, match.duration, match.date,
... | 5,316,851 |
def load_val_data(batch_size, dataset_name):
"""Load Patch Camelyon val data"""
val_dataset = tfds.load(
name=dataset_name, split='validation', as_supervised=True)
val_dataset = val_dataset.map(
functools.partial(preprocess_data, is_training=False))
val_dataset = val_dataset.batch(batch_size, drop_r... | 5,316,852 |
def dictfetchall(cursor):
"""
Return all rows from a cursor as a dict.
:param cursor: a database cursor.
:return: the results from the cursor as a dictionary.
"""
columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row))
for row in cursor.fetchall()] | 5,316,853 |
def dev_login(request):
"""docstring"""
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
log... | 5,316,854 |
def CheckBackwardsCompatibility(new_universe, old_universe):
"""Checks that non-abstract types are not removed or changed in new configs.
Method expects types in passed universe to have inherited_fields_expanded.
Method has the side effect of setting is_changed field on everything in this
universe that has cha... | 5,316,855 |
def pgram(N, years, fname):
"""
Calculate periodograms of LSST light curves.
"""
ps = np.linspace(2, 100, 1000) # the period array (in days)
print("Computing periodograms")
# Now compute LS pgrams for a set of LSST light curves & save highest peak
ids = np.arange(N)
periods = np.zeros_... | 5,316,856 |
def check_version(version, server_url, client='cli'):
"""
Check if the current version of the client software is supported by the One Codex
backend. Returns a tuple with two values:
- True if the user *must* upgrade their software, otherwise False
- An error message if the user should upgrad... | 5,316,857 |
def get_layout(data, width_limit):
"""A row of a chart can be dissected as four components below:
1. Label region ('label1'): fixed length (set to max label length + 1)
2. Intermediate region (' | '): 3 characters
3. Bar region ('▇ or '): variable length
This function first calculates the width of... | 5,316,858 |
def get_wordlist(seed):
"""
Takes a seed value from possible_seeds and generates a wordlist from the
thesaurus files.
Args:
seed - a string, one of possible_seeds
Returns:
a list of words for flag values
"""
word_list = []
tmp_list = []
word_string = ""
with open (os.path.join(wordlist_di... | 5,316,859 |
def save_npy(file_path, array):
"""
save_npy(file_path, array)
General purpose algorithm to save an array to a npy file
Parameters
----------
file_path: str
Path name of npy file
array: array_like (float);
Data array to be saved
"""
np.save(file_path, array) | 5,316,860 |
def downgrade():
"""Migrations for the downgrade."""
op.create_table(
'db_dbpath', sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),
sa.Column('child_id', sa.INTEGER(), autoincrement=False, nullable=True),
sa.... | 5,316,861 |
def validate_location_access(form, geographic_access, location_restrictions, group):
"""
Custom form validations related to geographic access and location restrictions
"""
if group.name == "Field Workers":
if len(location_restrictions) == 0 or geographic_access == "national":
form._e... | 5,316,862 |
def add_stats(all_data, yesterday_date_str, rows, key):
""" Given the entire registration report, augment a particular slice
of the data with male/female/total counts and label for each row.
The input rows are dictionaries with entries containing male and
female registrations by date, and total registr... | 5,316,863 |
def generate_xunit_to_rst(input_file, rst_file, itemize_suites, failure_message, log_file, *prefix_args):
""" Processes input arguments, calls mako template function while passing all needed parameters.
Args:
input_file (Path): Path to the input file (.xml).
rst_file (Path): Path to the output ... | 5,316,864 |
def assert_raises_regex(exception_class, expected_regexp,
callable_obj=None, *args, **kwargs):
"""
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and keyword arguments kwargs.
... | 5,316,865 |
def test_id():
"""Test get a random role_id"""
role_id1 = helper.role.id()
role_id2 = helper.role.id()
assert isinstance(role_id1, str)
assert isinstance(role_id2, str)
assert role_id1 != role_id2 | 5,316,866 |
def get_tiff_param(tiff_file):
"""Obtain relevant parameters of TiffFile object"""
xy_dim, description = lookup_page(tiff_file.pages[0])
shape = tiff_file.asarray().shape
if tiff_file.is_fluoview:
return get_fluoview_param(description, xy_dim, shape)
elif tiff_file.is_imagej:
retu... | 5,316,867 |
def get_number_of_classes(model_config):
"""Returns the number of classes for a detection model.
Args:
model_config: A model_pb2.DetectionModel.
Returns:
Number of classes.
Raises:
ValueError: If the model type is not recognized.
"""
meta_architecture = model_config.WhichOneof("model")
meta... | 5,316,868 |
def to_xy0(
xyz: npt.ArrayLike, radius: Optional[float] = 1.0, stacked: Optional[bool] = True
) -> np.ndarray:
"""
Convert geocentric xyz coordinates to longitude (φ) and latitude (λ)
xy0 (i.e., φλ0) coordinates.
Parameters
----------
xyz : ArrayLike
A sequence of one or more (x, y,... | 5,316,869 |
def test_s3_bucket_client_list_blobs(with_adapter: str, bucket: str) -> None:
"""Test corner-case in S3 client that isn't easily reachable from Pathy"""
from pathy.s3 import BucketClientS3
client: BucketClientS3 = get_client("s3")
root = Pathy("s3://invalid_h3gE_ds5daEf_Sdf15487t2n4")
assert len(li... | 5,316,870 |
def getDataset(filepath = ""):
"""
Reads a comma separated variables (csv) file and creates a dataset.
A dataset has the following components: Variables, Data, Types, Groups, Sorts
To call each componenet of a dataset, do the following.
Say you have a dataset named: somedata
somedata['VARI... | 5,316,871 |
def draw_matches(img0, img1, kpts0, kpts1, match_idx,
downscale_ratio=1, color=(0, 255, 0), radius=4, thickness=2):
"""
Args:
img: color image.
kpts: Nx2 numpy array.
match_idx: Mx2 numpy array indicating the matching index.
Returns:
display: image with drawn... | 5,316,872 |
def shorten_build_target(build_target: str) -> str:
"""Returns a shortened version of the build target."""
if build_target == '//chrome/android:chrome_java':
return 'chrome_java'
return build_target.replace('//chrome/browser/', '//c/b/') | 5,316,873 |
def store_initial_role_data(dynamo_table, arn, create_date, role_id, role_name, account_number, current_policy, tags):
"""
Store the initial version of a role in Dynamo
Args:
role (Role)
current_policy (dict)
Returns:
None
"""
policy_entry = {'Source': 'Scan', 'Discover... | 5,316,874 |
def _provider_next(provider_name: str) -> Any:
"""
Helper, looks up the specified provider function and yields test data from it.
Tries to close a resource after reading the data, if the provider has a 'close' callable attribute.
:param provider_name: provider name
:return: generator
"""
it... | 5,316,875 |
def apply_shift(x, shift, out):
"""
Translates elements of `x` along axis=0 by `shift`, using linear
interpolation for non-integer shifts.
Parameters
----------
x : ndarray
Array with ndim >= 1, holding data.
shift : float
Shift magnitude.
out : ndarray
Array wit... | 5,316,876 |
def get_socket(dname, protocol, host, dno):
"""socket = get_socket(dname, protocol, host, dno)
Connect to the display specified by DNAME, PROTOCOL, HOST and DNO, which
are the corresponding values from a previous call to get_display().
Return SOCKET, a new socket object connected to the X server.
... | 5,316,877 |
def azureblobstorage_folder_list(node_addon, **kwargs):
""" Returns all the subsequent folders under the folder id passed.
"""
return node_addon.get_folders() | 5,316,878 |
def summary_statistics(is_significant, time_interp, n_records_at_t, n_window):
"""Compute summary statistics."""
# Initialize
significant_number = np.zeros(len(time_interp))
significant_relative = np.zeros(len(time_interp))
max_records_around_t = np.zeros(len(time_interp))
for j in xrange(len(... | 5,316,879 |
def test_group_lasso_separable():
"""
This test verifies that the specification of a separable
penalty yields the same results as having two linear_atoms
with selector matrices. The penalty here is a group_lasso, i.e. l2
penalty.
"""
X = np.random.standard_normal((100,20))
Y = np.random... | 5,316,880 |
def draw_two(max_n: int) -> Tuple[int, int]:
"""Draw two different ints given max (mod max)."""
i = random.randint(0, max_n)
j = (i + random.randint(1, max_n - 1)) % max_n
return i, j | 5,316,881 |
def compareFloats(a, b, rtol=1.0e-5, atol=opscore.RO.SysConst.FAccuracy):
"""Compares values a and b
Returns 0 if the values are approximately equals, i.e.:
- |a - b| < atol + (rtol * |a + b|)
Else 1 if a > b, -1 if a < b
Inputs:
- a, b: scalars to be compared (int or float)
- atol: absolut... | 5,316,882 |
def net_import_share_constraint_rule(backend_model, constraint_group, carrier, what):
"""
Enforces demand shares of net imports from transmission technologies for groups of locations,
on average over the entire model period. Transmission within the group are ignored. The share
is relative to ``demand`` ... | 5,316,883 |
def _run_inferences(engines, input_data_list):
"""Runs an iteration of inferences for each engine with a random inpt.
Args:
engines: list of basic engines.
input_data_list: list of random input data.
"""
for engine, input_data in zip(engines, input_data_list):
engine.run_inference(input_data) | 5,316,884 |
async def test_invalid_claims_fail_first(mocker):
"""Check if claims are invalid, exception is raised and no network call is needed."""
client_id = 'test_client_id'
audience = 'api://default'
headers = {'alg': 'RS256', 'kid': 'test_kid'}
iss_time = time.time()
claims = {'ver': 1,
'... | 5,316,885 |
def main(verbose: int) -> None:
"""Feed documents into MayanEDMS."""
# setting up logging
logging.basicConfig()
logging.getLogger('werkzeug').setLevel(logging.CRITICAL)
logging.getLogger('socketio').setLevel(logging.CRITICAL)
logging.getLogger('engineio').setLevel(logging.CRITICAL)
if ver... | 5,316,886 |
def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
"""Raises an AssertionError if objects are not equal up to desired precision.
Args:
x(numpy.ndarray or cupy.ndarray): The actual object to check.
y(numpy.ndarray or cupy.ndarray): The desired, expected object.
... | 5,316,887 |
def loss_gaussian(X):
"""
encode X by CNML
"""
Xmat = np.matrix(X)
n, m = Xmat.shape
if n == 1:
Xmat = Xmat.T
n, m = Xmat.shape
else:
pass
if n <= 0:
return np.nan
Xc = Xmat - np.mean(Xmat, 0)
S = np.dot(Xc.T, Xc / n)
detS = sl.det(S)
l... | 5,316,888 |
def integrand(x, n):
"""
Bessel function of first kind and order n.
"""
return jn(n, x) | 5,316,889 |
def get_forms_tuple(*args):
"""
Converts a string of grammemes to a tuple of two sets:
- set of tags for declension
- set of tags for refining the word form
"""
forms = list()
specs = list()
for arg in args:
for key in force_str(arg).split(','):
if key in INFL... | 5,316,890 |
def truncate(inputs, channels, data_format):
"""Slice the inputs to channels if necessary."""
if data_format == 'channels_last':
input_channels = inputs.get_shape()[3].value
else:
assert data_format == 'channels_first'
input_channels = inputs.get_shape()[1].value
if input_channe... | 5,316,891 |
def backup_guard(fs, class_nr):
"""Guard tower of hanoi backup rotation scheme for ZFS:
http://en.wikipedia.org/wiki/Backup_rotation_scheme#Tower_of_Hanoi
.. note::
It cover [2^(n-2)+1; 2^(n-1)] days/time_units, where n is class_nr.
Fast calculation: 26 classes cover at least 2^24 + 1 = 16... | 5,316,892 |
def do_rating_by_user(parser, token):
"""
Returns a User's Rating of a Snippet, if any.
Example::
{% get_rating_by_user user.id object.id as rating %}
"""
bits = token.contents.split()
if len(bits) != 5:
raise template.TemplateSyntaxError("'%s' tag takes exactly four ar... | 5,316,893 |
def get_read_counts_total_table(path, pool):
"""
This table is used for "Fraction of Total Reads that Align to the Human Genome" plot
"""
full_path = os.path.join(path, AGBM_READ_COUNTS_FILENAME)
read_counts_total = pd.read_csv(full_path, sep='\t')
col_idx = ~read_counts_total.columns.str.conta... | 5,316,894 |
def read_data(data, ids, orm, id_field, database,
chunksize=10000, max_chunks=None,
section="mysqldb", db_env="MYSQLDB"):
"""Read data into the data and id arrays,
always starting from the last read chunk (e.g. if connection fails).
Data is read using the last available id,
... | 5,316,895 |
def get_label_funcs_threshold(bin_count=10, lower=1e-9, upper=1e-3, bin_func=bin_func_sum):
"""
:param bin_count: Number of different thresholds to encode the goes flux into.
:param lower: Lower limit for valid goes flux values.
:param upper: Upper limit for valid goes flux values.
:param bin_func: ... | 5,316,896 |
def export_offline_single_image(name, tag, path, force):
"""Download single image at <path>/images/"""
if not os.path.isdir(path):
echo("Creating base directory: {}".format(path))
os.mkdir(path)
util.pull_and_save_single_image(name, tag, path, force) | 5,316,897 |
def modify_layer(layer, name, norm = None, dropout = None):
"""Add BatchNorm and/or Dropout on top of `layer`"""
if dropout is not None:
name = "%s-dropout" % (name)
layer = Dropout(dropout, name = name)(layer)
if norm is not None:
name = "%s-%snorm" % (name, norm)
layer =... | 5,316,898 |
def create_access(terms_to_check, new_term):
"""
Breaks a new_term up into separate constituent parts so that they can be
compared in a check_access test.
Returns a list of terms that should be inserted.
"""
protos = new_term.match.get('protocol', ['any'])
sources = new_term.m... | 5,316,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.