content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_package_file(name: str) -> dict:
"""Load a yaml package file returning the represented dict.
Args:
name: base name of the package file
Returns:
A dict based on specified yaml packaged file
"""
return load_file(package_filename(name)) | 65,600 |
def convert_string_to_list(df, col, new_col):
"""Convert column from string to list format."""
fxn = lambda arr_string: [int(item) for item in str(arr_string).split(" ")]
mask = ~(df[col].isnull())
df[new_col] = df[col]
df.loc[mask, new_col] = df[mask][col].map(fxn)
return df | 65,601 |
def set_circuit_ic_mrucc(n_qubit_system, nv, na, nc, DS, theta_list, ndim1):
""" Function
Author(s): Yuto Mori
"""
circuit = QuantumCircuit(n_qubit_system)
if DS:
icmr_ucc_singles(circuit, n_qubit_system, nv, na, nc, theta_list, 0)
icmr_ucc_doubles(circuit, n_qubit_system, nv, na, n... | 65,602 |
def _parse_or_search(hint: Dict[str, str], attr_query: Dict[str, str]) -> Dict[str, str]:
"""Performs keyword analysis processing.
The search keyword is separated by OR and passed to the next process.
Args:
hint (dict[str, str]): Dictionary of attribute names and search keywords to be processed
... | 65,603 |
def tei_place_name(elem_text, attrib_ref="",
attrib_evidence=None, attrib_cert=None):
"""
| create TEI element <placeName> with given element text, @ref
| and (optional) @evidence and @cert
"""
place_name = etree.Element("placeName")
place_name.text = elem_text
add_attrib(... | 65,604 |
def _write_csv(file_name, d):
""" Writes the dictionary with the reference results to a csv file.
:param file_name: The name of the csv reference file.
:param: A dictionary with the reference results.
"""
import numpy as np
# Get the length of the data series
# Check if time is a k... | 65,605 |
def sed(pattern, replacement, filename1, filename2):
"""Write contents of file1 into file2, replacing any occurrence
of pattern with replacement.
pattern, replacement: strings
filename1, filename2: strings, names of files
"""
fin = open(filename1) # open the normal way
fout = open(filename2... | 65,606 |
def r_unit(p1, p2):
"""
r_unit(x, y) : Function computes the unit vector
between two points with coordinates p1(x1, y1) and p2(x2, y2)
"""
assert len(p1) == len(p2), 'locs must be the same shape.'
dx = []
for ii in range(len(p1)):
dx.append((p2[ii] - p1[ii]))
# Compute length... | 65,607 |
def raw_directory(request):
"""Gets 'raw' directory with test datafiles"""
return Path(request.config.rootdir) / "tests/testdata/2020/6/raw" | 65,608 |
def _update_cycle(self, cycle, scatter=False, **kwargs):
"""
Try to update the `~cycler.Cycler` without resetting it if it has not changed.
Also return keys that should be explicitly iterated over for commands that
otherwise don't use the property cycler (currently just scatter).
"""
# Get the o... | 65,609 |
def solution(dataset: list) -> int:
""" "there is a '\n' on the end of the first line but zip() will only go to the sortest length.
If both lines have '\n's then they will be equivalent and won't be counted"""
return sum(i != j for i, j in zip(*dataset)) | 65,610 |
def load_image(path_image, force_rgb=True):
""" load the image in value range (0, 1)
:param str path_image: path to the image
:param bool force_rgb: convert RGB image
:return ndarray: np.array<height, width, ch>
>>> img = np.random.random((50, 50))
>>> save_image('./test_image.jpg', img)
>... | 65,611 |
def _GetFeatureCenters(num_groups, center_var, feature_dim):
"""Helper function to generate multivariate Normal feature centers.
Args:
num_groups: number of centers to generate.
center_var: diagonal element of the covariance matrix (off-diagonals = 0).
feature_dim: the dimension of each center.
Retur... | 65,612 |
def async_pipe(*args, **kwargs):
"""A processor that asynchronously retrieves the current exchange rate
for a given currency pair.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. May... | 65,613 |
def get_new_ticket():
"""Request a new upload ticket from Vimeo."""
response = _vimeo_request('vimeo.videos.upload.getTicket', 'POST',
upload_method='post')
if response['stat'] == 'fail':
err = response['err']
logger.error(u'Error retrieving upload ticket: <{cod... | 65,614 |
def _tau(x, y):
"""Helper function for faster computation"""
n = len(x)
numerator = 0
for i in range(n-1):
for j in range(i+1, n):
sx = np.sign(x[i] - x[j])
sy = np.sign(y[i] - y[j])
numerator += sx * sy
nn = n * (n-1) / 2
return numerator / nn | 65,615 |
def test_access_data():
"""Demonstrate and test access patterns within the data island."""
binders = {
"Polyethylene Glycol 100M": 0.02,
"Sodium lignosulfonate": 0.004,
"Polyvinyl Acetate": 0.0001
}
powders = {"Al2O3": 0.96}
island = make_data_island(
density=1.0,
... | 65,616 |
def get_session():
"""Make a cached session."""
settings.CACHE_PATH.mkdir(exist_ok=True, parents=True)
path = settings.CACHE_PATH.joinpath("http").as_posix()
session = CachedSession(cache_name=path, expire_after=settings.CACHE_EXPIRE)
session.headers.update(HEADERS)
# weird monkey-patch: default... | 65,617 |
def write_plot1dfile(ini0,plot1dfile):
"""
Take a dictionary with all the relevant information for the
structure, extract the Kpath, and write the data to the
plot1dfile for the Elk code.
"""
length = len(ini0["kpath_label"])
plot1dfile.write("plot1d\n")
plot1dfile.write(" %d\n" % lengt... | 65,618 |
def createSource(uid, payload):
"""
if id_source in payload, use that id, provided no record already exists, if not use new id
returns the id
"""
source = None
url = payload["url"]
page = parsePage(url)
if "id_source" in payload:
id = payload["id_source"]
source = M.... | 65,619 |
def add_atom_counts(df, struct_df):
"""Add atom counts (total and per type) to 'df'."""
pd.options.mode.chained_assignment = None
atoms_per_mol_df = struct_df.groupby(['molecule_name', 'atom']).count()
atoms_per_mol_map = atoms_per_mol_df['atom_index'].unstack().fillna(0)
atoms_per_mol_map = atoms_p... | 65,620 |
def test_init_not_iterable():
"""Test for typeerror message if not iterable."""
with pytest.raises(TypeError) as message:
Stack(3)
assert "data must be iterable" in str(message) | 65,621 |
def nround(number: float, decimals=1):
"""Normalized round. nround(0.5) = 1 (unlike round())"""
number = str(number)
# if decimal places <= decimals
if len(number[number.index('.')::]) <= decimals + 1:
return float(number)
if number[-1] == '5':
number = number[:-1:] + '6'
... | 65,622 |
def coast2bln(coast, bln_file):
"""Converts a matlab coast (two column array w/ nan for line breaks) into
a Surfer blanking file.
Where coast is a two column vector and bln_file is the output file name.
Needs `fixcoast`."""
c2 = fixcoast(coast)
ind = np.where(np.isnan(c2[:, 0]))[0]
n = le... | 65,623 |
def uniform_vector(shape, min_value=0, max_value=1, return_symbol=False):
"""
Generates a uniformly random tensor
:param shape: shape of the tensor
:param min_value: minimum possible value
:param max_value: maximum possible value (exclusive)
:param return_symbol: True if the result should be a ... | 65,624 |
def format_seconds(seconds: float) -> str:
"""
Runtimes can be really long, due to exponentially growing configurational space, therefore those h
"""
minute = 60
hour = 60*minute
day = 24*hour
year = 365 * day
units = collections.OrderedDict([
(230000000*year, 'galactic year'),
... | 65,625 |
def randomise_MFVI_net(bnn):
"""randomise the means and logvars in an MFVI BNN"""
for layer in bnn.layers:
layer.w_mean = Parameter(torch.randn_like(layer.w_mean))
layer.w_logstd = Parameter(torch.randn_like(layer.w_logstd) / 2)
layer.b_mean = Parameter(torch.randn_like(layer.b_mean))
... | 65,626 |
def clear_schema(pg):
"""Removes tables prior to tests."""
with psycopg2.connect(**pg.dsn()) as conn:
with conn.cursor() as cursor:
cursor.execute('DROP TABLE IF EXISTS test_table;')
cursor.execute('DROP TABLE IF EXISTS another_table;') | 65,627 |
def _get_tables_and_columns_in_schema(db, schema):
"""Returns a dict describing all tables and columns in `schema`."""
# Obtain names of tables in `schema`:
q = """
SELECT table_name FROM information_schema.tables
WHERE table_schema = '""" + schema + """'
ORDER BY table_name;
"""
... | 65,628 |
def _setup_metrics(metric_publisher_class, metric_publisher_args):
"""
Sets up a metrics publisher based on command line args.
Args:
metric_publisher_class
metric_publisher_args
"""
try:
publisher = load_cli_plugin(metric_publisher_class,
metric_publisher_args)
... | 65,629 |
def setup(obs_bp_path, binmixmat_path, mix_lmin, cov_path, pos_nl_path, she_nl_path, noise_lmin, input_lmax,
n_zbin):
"""
Load and precompute everything that is fixed throughout parameter space. This should be called once per analysis,
prior to any calls to execute.
Args:
obs_bp_path ... | 65,630 |
def mk_comorbidity(data_id, data): # measurement group 26
"""
transforms a c-comorbidity.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param data: data array from the json form
:return: T... | 65,631 |
def raw_formatter(subtitles):
"""
Serialize a list of subtitles as a newline-delimited string.
"""
return ' '.join(text for (_rng, text) in subtitles) | 65,632 |
def get_gids(features: dict, data_pd: pd.DataFrame):
"""
Parameters
----------
features : dict
Mapping genome -> feature
data_pd : pd.DataFrame
Feature table
Returns
-------
gid_features : dict
Mapping genome -> feature
"""
data_feats = set(data_pd.index... | 65,633 |
def test_session_key_v1():
"""Test the compute_key_v1() function."""
# Define variables
num_agents = 3
num_timesteps = 5
action_space_size = 3
# Build agent histories
histories_list = []
for l in range(num_agents):
# Build history for number of timestepss
history = []
for t in range(num_timesteps):
... | 65,634 |
def average_mse():
"""
Plotting average MSE over time
"""
data, model = load('two')
ts_t = torch.from_numpy(data.train_time_steps).float()
trajs = torch.from_numpy(data.train_expect_data).float()
z = model.encode(trajs, ts_t)
xs = model.decode(z, ts_t).numpy()
multiplier = 1000
m... | 65,635 |
def send_message(queue, message_body, message_attributes=None):
"""
Send a message to an SQS queue.
:param queue: The queue that receives the message.
:param message_body: The body text of the message.
:param message_attributes: Custom attributes of the message. These are key-value
... | 65,636 |
def platform(data):
"""Request to scan platform"""
data.client.request("scan", "platform", "platform", None) | 65,637 |
def dict_diff(first, second):
"""
>>> dict_diff({'a':'b', 'c':1}, {'a':'c', 'c':1})
{'a': {'original':'b', 'changed': 'c'}
:type first: dict
:type second: dict
:rtype dict
"""
diff = {}
keys = set(first) | set(second)
for key in keys:
first_value = first.get(key)
... | 65,638 |
def struct_union_class_factory (class_name, class_dict):
"""Create a class type with name class_name, descended from
struct_or_union_base and object, to be a factory for instantiating
struct/union values."""
return new.classobj (class_name, (struct_or_union_base,),
class_dict) | 65,639 |
def normalize_images(mode="tr"):
"""
Normalizes all data related to either training or testing, this includes depth, B&W and raw matrixes.
The result is a 100x100 image of the face.
"""
#RGB images for light estimation
rgb_imgs, rgb_labels, rgb_names = manager.get_samples(mode,"rgb")
... | 65,640 |
def getNGramCounts(data, N):
"""Count the occurences of all N+1 grams in the
data. Outputs a dictionary mapping histories of length N
to a histogram dictionary."""
counts = defaultdict(dict)
for i in xrange(N,len(data)):
history = tuple(data[i-N:i])
obs = data[i]
if obs in counts[history]:
... | 65,641 |
def csv_to_grid_02():
"""
:return: 20200201_20200215 csv to grid
"""
df = pd.read_csv('./csv_data/shortstay_20200201_20200215.csv', sep='\t')
df.columns = ['date', 'hour', 'grid_x', 'grid_y', 'index']
grid_h = []
date_h = []
for d in range(20200201, 20200216):
df_y = df[df.iloc[... | 65,642 |
def network_association_find_distinct_networks(context,
host_name,
session):
"""
returns unique networks from all network associations for given host
:param context: The context for building the data
:param hos... | 65,643 |
def check_single_instance():
"""Use pgrep to check if protonvpn-applet is already running
"""
pid = None
try:
pid = subprocess.run('pgrep protonvpn-applet'.split(), check=True, capture_output=True)
except subprocess.CalledProcessError:
try:
pid = subprocess.run('pgrep pr... | 65,644 |
def create_component_update_issue(jira_host, username, password, project_key, summary, component_name):
"""
Creates upstream JIRA issue for the component update
jira_host -- host address of the JIRA instance to connect to.
username -- JIRA username with administration permissions.
password -- JIRA ... | 65,645 |
def add_space_after_commas(origString):
"""
Directives with arguements need spaces insert after commas.
"""
# space after a comma
newString = re.sub(',', ', ', origString)
return newString | 65,646 |
def remove_reaction(message: SlackMessage, reaction: str) -> None:
"""Removes reaction from the given message
Parameters
----------
message : SlackMessage
Slack message to remove the reaction from
reaction : str
The reaction to remove
"""
try:
slack_api.reactions_rem... | 65,647 |
def get_jwt_key(kid):
"""Get the public key via http."""
# from https://github.com/auth0-samples/auth0-python-api-samples/blob/master/00-Starter-Seed/server.py
# This is only as secure as our HTTP connection is secure ...
url = 'https://{}/.well-known/jwks.json'.format(gaetkconfig.AUTH0_DOMAIN)
resp... | 65,648 |
def preprocess_tds(df):
"""
Parameters
----------
df : JSON to CSV converted time domain settings data.
Returns
-------
df_expanded : Restructured and reformatted tds data.
"""
#NEED DECIDE WHICH TIMESTAMP TO KEEP, TIMESTOP, OR TIMESTART
df = df.rename(columns={"timeStart": "tim... | 65,649 |
def make_photometry_indexdb(framedir,
outfile,
frameglob='*_5.fits', # avoid ISM FITS products
photdir=None,
photext='text-fiphot',
maxframes=None,
ove... | 65,650 |
def rr_interval_update(rpeak_temp1: List[DataPoint],
rr_ave: float,
min_size: int = 8) -> float:
"""
:param min_size: 8 last R-peaks are checked to compute the running rr interval average
:param rpeak_temp1: R peak locations
:param rr_ave: previous rr-interval ... | 65,651 |
def get_all_matching(cls, column_name, values):
"""Get all the instances of ``cls`` where the column called ``column_name``
matches one of the ``values`` provided.
Setup::
>>> from mock import Mock
>>> mock_cls = Mock()
>>> mock_cls.query.filter.return_value.a... | 65,652 |
def assign_country_code(indices, cosmo_grid, projections, countries):
"""Assign the country codes on the gridcells indicated by indices.
Each gridcell gets assigned to code of the country with the most
area in the cell.
If for a given grid cell, no country is found (Ocean for example),
the country... | 65,653 |
def new_figure_manager(num, *args, FigureClass=FigureSurface, **kwargs):
"""Create a new figure manager instance."""
# If a main-level app must be created, this (and
# new_figure_manager_given_figure) is the usual place to do it -- see
# backend_wx, backend_wxagg and backend_tkagg for examples. Not all... | 65,654 |
async def on_member_join(client, member):
"""When a new member joins Off the Dial."""
if member.guild != client.OTD: # Check if it's the correct the server
return
await add_roles(client, member) | 65,655 |
def get_observation_photo_metadata(observation_id, access_token):
"""Attempt to scrape metadata from a photo info pages associated with an observation
(first photo only)
"""
print(f'Fetching observation {observation_id}')
obs = get_observation(observation_id)
photo_ids = [photo['id'] for photo i... | 65,656 |
def get_median_pulse_height(data_dir: str, fov: str, channel: str,
panel: Union[Tuple[float, float], pd.DataFrame] = (-0.3, 0.0),
time_res: float = 500e-6):
"""Retrieves median pulse intensity and mean pulse count for a given channel
Args:
data_di... | 65,657 |
def ui2py(src_path,tar_path):
"""
将ui文件编译成py代码
"""
print("build start".center(100,"*"))
# 构建编译路径
path = os.getcwd() +src_path
# 获取所以文件
all_file_path = []
get_all_listdir(path,all_file_path)
# 遍历所以文件并编译ui文件
for one_file in all_file_path:
# 分割路径与文件名
file_pat... | 65,658 |
def _prepare_hdf5_write_value(array_like):
"""Cast a python object into a numpy array in a HDF5 friendly format.
:param array_like: Input dataset in a type that can be digested by
``numpy.array()`` (`str`, `list`, `numpy.ndarray`…)
:return: ``numpy.ndarray`` ready to be written as an HDF5 dataset
... | 65,659 |
def resize(img, rate, flg=cv2.INTER_NEAREST):
"""
画像サイズを変更する
[in] img: N倍にする画像
[in] rate: 倍率
[in] flg: N倍にする時のフラグ
[out] N倍にされた画像リスト
"""
if rate < 0:
logger.debug('resize({},{},{})'.format(
img.shape, rate, flg
))
return img
size = (int(img.shap... | 65,660 |
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if not si... | 65,661 |
def get_day_of_week(year: int, month: int, day: int) -> int:
"""
0表示星期日,1-6表示星期一到星期六
"""
if month in (1, 2):
year -= 1
month += 12
return (
day
+ 2 * month
+ 3 * (month + 1) // 5
+ year
+ year // 4
- year // 100
+ year // 400
... | 65,662 |
def main(args):
"""
Run the checks
"""
# the metadata found by the checks is used in the online PRIMAVERA
# validation but can be ignored in this simple check
_output = []
num_errors_found = 0
if args.single_file:
data_files = [args.directory]
else:
data_files = lis... | 65,663 |
def AddDefaultLocationToListRequest(ref, args, req):
"""Python hook for yaml commands to wildcard the region in list requests."""
del ref
project = properties.VALUES.core.project.Get(required=True)
if hasattr(args, 'zone'):
location = args.region or args.zone or LOCATION_WILDCARD
else:
location = args... | 65,664 |
def normalize_model_parameter(model_parameter):
"""
Args:
model_parameter (str / dict): The parameter to convert.
Returns:
dict: If `model_parameter` is an ID (a string), it turns it into a model
dict. If it's already a dict, the `model_parameter` is returned as it
is. It re... | 65,665 |
def cls(
workspace,
output_file,
measurement,
patch,
testpoi,
teststat,
backend,
optimizer,
optconf,
):
"""
Compute CLs value(s) for a given pyhf workspace.
Example:
.. code-block:: shell
$ curl -sL https://raw.githubusercontent.com/scikit-hep/pyhf/master/d... | 65,666 |
def _make_json_error(ex):
"""Return JSON error pages, not HTML!
Using a method suggested in http://flask.pocoo.org/snippets/83/, convert
all outgoing errors into JSON format.
"""
status_code = ex.code if isinstance(ex, HTTPException) else 500
response = jsonify(message=str(ex), code=statu... | 65,667 |
def check_refcard(reffield):
"""
Checks wether the reference card was detected properly by comparing with the original reference
Input:
reffield: list of separated reference field of the detected reference card
Output:
ref_detected: Boolean, indicating, wether the card was detected pro... | 65,668 |
def householder_qr(A):
"""Computes the QR = A factorization of A using Householder reflections
Algorithm 5.2.1
"""
m, n = A.shape
A = householder_qr_packed(A)
QF , R = householder_split_qf_r(A)
Q = householder_ffm_backward_accum(QF, n)
return Q, R | 65,669 |
def score_by_label (y_test, y_predict):
"""
calculate score of prediction by label type: bas, reasonable and good
Parameters
----------
y_test : pd.Series
y value to predict
y_predict : list
y value predicted
return
----------
score_list : list
score li... | 65,670 |
def _VerifyBackupDirectories (slotID: int) -> None:
"""
Verify that all existing backups have an attached game backup file that still exists. If the game backup save doesn't exist, the corresponding backup
will be deleted.
:param slotID: The slot id of the targeted save file.
:type slotID: int
"""
for backupInd... | 65,671 |
def skipUnlessImported(module, obj):
"""如果对象不在导入的模块中,跳过被装饰的测试 .
@skipUnlessImported('airflow.operators.mysql_operator', 'MySqlOperator')
@skipUnlessImported('xTool.utils.tests', 'skipUnlessImported')
"""
import importlib
try:
m = importlib.import_module(module)
except ImportE... | 65,672 |
def check_valid_border(border):
"""\
Raises a :py:exc:`ValueError` iff `border` is negative.
:param int border: Indicating the size of the quiet zone.
"""
if border is not None and (int(border) != border or border < 0):
raise ValueError('The border must not a non-negative integer value. '
... | 65,673 |
def get_owned_assets(addresses):
"""Gets a list of owned assets for one or more addresses"""
result = config.mongo_db.tracked_assets.find({
'owner': {"$in": addresses}
}, {"_id": 0}).sort("asset", pymongo.ASCENDING)
return list(result) | 65,674 |
def rgb2hed(rgb):
"""RGB to Haematoxylin-Eosin-DAB (HED) color space conversion.
Parameters
----------
rgb : array_like
The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.
Returns
-------
out : ndarray
The image in HED format, in a 3-D array of shape ``(.., ..... | 65,675 |
def get_role_type_and_id(role, role_id=''):
"""
Return both type and ID of a role.
Args:
role (obj): string or role instance.
role_id (str): string ID or None.
Returns:
tuple: type and ID of role.
"""
if isinstance(role, str):
return role, role_id
return get... | 65,676 |
def is_user_context(context):
"""Indicate if the request context is a normal user."""
if not context:
return False
if context.is_admin:
return False
if not context.user or not context.project:
return False
return True | 65,677 |
async def test_hass_fan_to_melissa(hass):
"""Test for translate melissa states to hass."""
with patch('homeassistant.components.melissa'):
with patch('homeassistant.components.climate.melissa._LOGGER.warning'
) as mocked_warning:
api = melissa_mock()
device = (... | 65,678 |
async def handle_voice_client_update(client, voice_state, old_attributes):
"""
Called when the client's voice state is edited.
This function is a coroutine.
Parameters
----------
client : ``Client``
The respective client.
voice_state : ``VoiceState``
The client's vo... | 65,679 |
def parse(url, quantity):
""" Url-parser function, that extracts fixed-size quantity of images from url
(Insert only unique values)
:param url: the link to web-site with images
:param quantity: the quantity of images to insert
"""
images_links = Parser.parse_images(url)
quantity = int(qu... | 65,680 |
async def get_genomes_dict():
"""
**Private endpoint**, which returns the entire 'genomes' part of the config
"""
_LOGGER.info(f"serving genomes dict: '{rgc[CFG_GENOMES_KEY]}'")
return rgc[CFG_GENOMES_KEY] | 65,681 |
def type_description(name, types):
""" Returns a dictionary description the given type. See `types.yml`
for more information about keys and values there. """
return types[dereference_type(name)] | 65,682 |
def rank_features_groups_heatmap(
adata: AnnData,
groups: Union[str, Sequence[str]] = None,
n_features: Optional[int] = None,
groupby: Optional[str] = None,
feature_symbols: Optional[str] = None,
var_names: Optional[Union[Sequence[str], Mapping[str, Sequence[str]]]] = None,
min_logfoldchange... | 65,683 |
def median_ci(pop, n, ci=0.95):
""" Estimate the approximate ci 95% error margins for the median
using a rule of thumb based on Hollander and Wolfe (1999).
Parameters
----------
pop : numpy array
a sorted dataset
n : scalar, positive int
the sample size
ci : float, scalar ... | 65,684 |
def find_source(function_key, data, functions):
"""
Finds the source of the 'function_key' in 'data' or in 'functions', and returns it
"""
# To fund sources in regular triples maps
for tm in data['TriplesMap']:
if len(data['TriplesMap'][tm]['Predicate_Object']['Function']) != 0:
... | 65,685 |
def _interpret_emr_bootstrap_stderr(fs, matches, partial=True):
"""Extract errors from bootstrap stderr.
If *partial* is true, stop when we find the first match.
(In practice, we usually target a single file anyway.)
"""
result = {}
for match in matches:
stderr_path = match['path']
... | 65,686 |
def wrap_strictly(value: Any, type_: type) -> StrictSmartWrapper:
"""Less-code style version of StrictSmartWrapper constructor call."""
return StrictSmartWrapper(value, type_) | 65,687 |
def check_slurm_queue_id(job_id):
"""Returns true if the job whose id is job_id is in the slurm queue.
Args:
job_id (int): The ID of the job.
Returns:
A boolean indicating whether or not the slurm job is running.
"""
try:
return string_in_output("squeue", str(int(job_id)))
... | 65,688 |
def make_undirected(mat):
"""
Takes an input adjacency matrix and makes it undirected (symmetric).
Parameter
----------
mat: array
Square adjacency matrix.
"""
if not (mat.shape[0] == mat.shape[1]):
raise ValueError('Adjacency matrix must be square.')
sym = (mat + mat.t... | 65,689 |
def inc(n):
"""Increment an integer."""
return -~n | 65,690 |
def task_update(context, task_id, values):
"""Update a task object"""
global DATA
task_values = copy.deepcopy(values)
task_info_values = _pop_task_info_values(task_values)
try:
task = DATA['tasks'][task_id]
except KeyError:
LOG.debug("No task found with ID %s", task_id)
r... | 65,691 |
def test_mediator_task_view():
"""Same as above for mediator tasks."""
secret1 = factories.make_secret(1)
locked_amount1 = TokenAmount(11)
payee_transfer = factories.create(
factories.LockedTransferUnsignedStateProperties(secret=secret1)
)
payer_transfer = factories.create(
facto... | 65,692 |
def plot_series(
series,
y=None,
y_pred=None,
x_label="$t$",
y_label="$x(t)$",
legend=True
):
"""
AG's convenience function to do clean time series plots.
"""
plt.plot(series, ".-")
if y is not None:
plt.plot(n_steps, y, "bo", label="Target")
... | 65,693 |
def _load_docker_image(FLAGS, workspace_dir, setup_execution_time):
"""Runs docker load --input_image <FLAGS.dockerfile_path>.
Fetches FLAGS.dockerfile_path to workspace_dir/<temp-dir>/local_docker first.
Runs docker load --input <path-to-local-docker>.
Deletes workspace_dir/<temp-dir> after the docker image i... | 65,694 |
def indent(elem, level=0):
"""Recurse through XML tree and add indentation.
Args:
elem: The element to recurse over
level: The current indentation level.
"""
i = '\n' + level*' '
if elem is not None:
if not elem.text or not elem.text.strip():
elem.text = i + ' '
if not elem.tail or n... | 65,695 |
def get_neighbor_in_filter(neigh_ip_address):
"""Returns a neighbor in_filter for given ip address if exists."""
core = CORE_MANAGER.get_core_service()
peer = core.peer_manager.get_by_addr(neigh_ip_address)
return peer.in_filters | 65,696 |
def test_technical_controls_post_bad_request_for_missing_parent(client):
"""
Given: An empty technicalContols table
When: When a correctly formed technical control definition is posted to the api with a non existent parent
Then: 400 is returned
"""
# Arrange
SystemFactory(id=2, stage=SystemS... | 65,697 |
def Vowel_or_Consonant(char = ''):
"""
A boolean function, which return either True or False
"""
# Determine whether each letter in the text is a vowel or a
# consonant. if it is a vowel, set test to True, otherwise, set test to false.
for i in char:
if str(i)in 'aeiouy':
te... | 65,698 |
def override_client_settings(settings, cache, xpctl_config):
"""Use server POV for things line cache and xpctl config."""
settings['datacache'] = cache
if xpctl_config is None:
settings.get('reporting', {}).pop('xpctl', None)
else:
settings.get('reporting', {}).get('xpctl', {})['cred'] =... | 65,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.