content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_salesforce_origin_query_cdc_no_object(sdc_builder, sdc_executor, salesforce):
"""Test SDC-12378 - enabling CDC with blank object name ('get notifications for all objects') was causing
initial query to fail.
Create data using Salesforce client and then check if Salesforce origin receives them using... | 5,286,100 |
def generate_inside_field(center, segment, n, max_features, min_features, feature_variance):
"""
Args:
"center" corresponds to the target instance to explain
Segment corresponds to the size of the hypersphere
n corresponds to the number of instances generated
feature_variance: Ar... | 5,286,101 |
def ecr_used_images():
"""
Check currently running ECS tasks for their used image and return images from ECR that are not in use.
"""
used_images = []
ecs = boto3.client('ecs')
response = ecs.list_clusters()
for c in response['clusterArns']:
tasks = ecs.list_tasks(cluster=c)['taskArn... | 5,286,102 |
def diversity_score(xyz, distance_type:str, **kwargs) -> torch.tensor.shape == [1]:
"""
:param xyz: [B, P, N, 3] tensor
:param distance_type: shape/part
:param kwargs: {downsample_type:None, npoint_per_part:10}
:return: [1] tensor of divs_score
"""
if distance_type == "shape":
dist =... | 5,286,103 |
def find_left_element(sorted_data, right, comparator):
"""!
@brief Returns the element's index at the left side from the right border with the same value as the
last element in the range `sorted_data`.
@details The element at the right is considered as target to search. `sorted_data` must
... | 5,286,104 |
def burn_io(instance_ids: List[str] = None,
execution_duration: str = "60",
configuration: Configuration = None,
secrets: Secrets = None) -> List[AWSResponse]:
"""
Increases the Disk I/O operations per second of the virtual machine.
Parameters
----------
instance... | 5,286,105 |
def test_create_raster_from_image_set(py_client: ImageryClient, sample_raster_multi: RasterMeta):
"""Test that creation of an ImageSet succeeds."""
# Get image set from supplied raster
image_set: ImageSet = sample_raster_multi.parent_raster.image_set
imageset_dict = model_to_dict(image_set)
# Delet... | 5,286,106 |
def register_insert(gearman_worker, gearman_job):
""" registering new user """
sys.stdout.write("[%s] :: Registering new user\n" % t)
# convert string > datetime object
gearman_data = json.loads(gearman_job.data)
gearman_data.update({'datetime': parse(gearman_data['datetime'])})
# insert data > ... | 5,286,107 |
def write_file(file_path, content):
"""
Write file at the specified path with content.
If file exists, it will be overwritten.
"""
handler = open(file_path, 'w+')
handler.write(content)
handler.close() | 5,286,108 |
def CreateTestBudget(client):
"""Creates a budget to run tests with.
Args:
client: AdWordsClient client to obtain services from.
Returns:
int Budget ID
"""
budget_service = client.GetBudgetService(SERVER, VERSION, HTTP_PROXY)
budget = {
'name': 'Budget #%s' % Utils.GetUniqueName(),
'am... | 5,286,109 |
def logout():
"""Used to logout users"""
logout_user()
return redirect(url_for('home')) | 5,286,110 |
def test_scenario_1():
"""Tests a scenario where lots of night roles are at play."""
builder = GameBuilder.load("test")
game = builder.build(["Alice", "Bob", "Charlie", "Dave", "Emily"], n_mafia=1)
alice, bob, charlie, dave, emily = game.actors[:5]
tally: Tally = game.aux.filter_by_type(Tally)[0]
... | 5,286,111 |
def gaussian_kernel(x1: np.ndarray, x2: np.ndarray, sigma: int) -> np.ndarray:
"""
Compute the Gaussian kernel between x1 and x2.
Args:
x1: The first vector.
x2: The second vector.
sigma: The sigma of the Gaussian function.
Returns:
The Gaussian kernel between x1 an... | 5,286,112 |
def make_windows_timestamp_value_getter(value_name):
"""
return a function that fetches the value from the registry key
as a Windows timestamp.
"""
f = make_value_getter(value_name)
def _value_getter(key):
try:
return parse_windows_timestamp(f(key) or 0)
except Valu... | 5,286,113 |
def compute_area(c, target_layer):
"""
Compute area of the component on a given layer
"""
_print("Computing area ", c.name)
c.flatten()
# return c.area(by_spec=True)[layer]
polys_by_spec = c.get_polygons(by_spec=True)
_area = 0
for (layer, polys) in polys_by_spec.items():
_pr... | 5,286,114 |
def Sourceify(path):
"""Convert a path to its source directory form."""
if '$(' in path:
return path
if os.path.isabs(path):
return path
return srcdir_prefix + path | 5,286,115 |
def admin_add_user(request):
"""
:param request:
:return:
"""
# Make sure user has permissions
# Get data
group_results = group.objects.filter(
is_deleted=False,
).values()
permission_set_results = permission_set.objects.filter(
is_deleted=False,
).values()
... | 5,286,116 |
def generate_flac_dirname(library_root, metadata):
"""Build the directory for a track's FLAC file.
:arg str library_root: the FLAC library directory
:arg dict metadata: the finalized metadata for a single track
:return: an absolute directory path
:rtype: :obj:`str`
"""
_log.call(library_ro... | 5,286,117 |
def NamedParameterNames(fn):
"""!
@brief Get names available to use as named parameters.
"""
try:
co = fn.__code__
except AttributeError:
return ()
return co.co_varnames[co.co_posonlyargcount:co.co_argcount+co.co_kwonlyargcount] | 5,286,118 |
def random_noise_model_profile(num_voters, num_cand, p, phi, distance="hamming"):
"""
Generate a random profile using the *Random Noise* probability distribution.
Parameters
----------
num_voters : int
The desired number of voters in the profile.
num_cand : int
... | 5,286,119 |
def create_and_validate_config(parsed_config: YAML = None) -> Config:
"""Run validation on config values."""
if parsed_config is None:
parsed_config = fetch_config_from_yaml()
# specify the data attribute from the strictyaml YAML type.
_config = Config(
app_config=AppConfig(**parsed_con... | 5,286,120 |
def optimizer():
"""
Get the optimizer to use for training
:return: optimizer object
"""
opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
return opt | 5,286,121 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Trafikverket Weatherstation config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) | 5,286,122 |
def add_tensor(uni, fp):
"""
Simple function to add a tensor object to the universe.
Args:
uni (universe): Universe object
fp (str): file pathname
"""
uni.tensor = Tensor.from_file(fp) | 5,286,123 |
def valid_write_option(string):
"""
This method checks whether the string is one of the valid write options and if not raises an error.
:param string: The write option
:type string: str
:return: str
"""
valid_options = ["w", "a"]
if string not in valid_options:
raise argparse.A... | 5,286,124 |
def raise_404(request):
"""Raise a 404 Error."""
raise Http404 | 5,286,125 |
def test_conversion():
"""### Comment
* This is used to convert some data into `PIL.Image.ImageP`.
### Comment.
"""
from PIL import Image
from pathlib import Path
from fairyimage import from_source
script = Path(__file__).read_text("utf8")
image = from_source(script)
assert isi... | 5,286,126 |
def get_relative_path(kid: str, parent: str) -> Union[List[str], None]:
"""
Return the relative path depth if relative, otherwise MAX_INT.
Both the `kid` and `parent` should be absolute paths without trailing /
"""
# Note that os.path.commonpath has no trailing /
# TODO: python3.9 pathlib has i... | 5,286,127 |
def min_w_ind(lst: List) -> Tuple[int, Any]:
"""
Returns the min value and its index
:param lst: The list to get the max value in
:return: Min value and its index
"""
val = min(lst)
ind = lst.index(val)
return ind, val | 5,286,128 |
def check_input_format(output, target):
""" check input format of outpt and target
output: BxCxHxW tensor where C is the number of classes
target: Bx1xHxW tensor where every entry is an int in the range [0, C-1]
"""
try:
assert len(output.shape) == 4
assert len(target.shape) == 4
... | 5,286,129 |
def run_transition():
"""
Transition execution/"stepping"
- run color change for long dimming periods
- runs the generated color dimming generators
:return: Execution verdict
"""
if None not in Data.FADE_OBJ:
try:
r = Data.FADE_OBJ[0].__next__()
g = Data.F... | 5,286,130 |
def DatetimesRangeFieldWidget(field, request): # pylint: disable=invalid-name
"""Datetimes range widget factory"""
return FieldWidget(field, DatetimesRangeWidget(request)) | 5,286,131 |
def examine_command(logger, options):
""" look at the command and guess if it is an AWS CLI built in command """
if not options.no_cli_guess and options.command:
try:
import awscli.clidriver
logger.debug("Guessing if the supplied command is an AWS CLI command..")
cli ... | 5,286,132 |
def get_company_news(
ticker: str,
s_start: str,
s_end: str,
) -> List[Dict]:
"""Get news from a company. [Source: Finnhub]
Parameters
----------
ticker : str
company ticker to look for news articles
s_start: str
date to start searching articles, with format YYYY-MM-DD
... | 5,286,133 |
def count(iterable):
"""
Returns the number of items in `iterable`.
"""
return sum(1 for whatever in iterable) | 5,286,134 |
def cli() -> None:
"""
Custom scripts which help modmail development.
All custom scripts should be listed below as a command, with a description.
In addition, some built in modules may be listed below as well.
If a custom script is not shown below please open an issue.
"""
pass | 5,286,135 |
def scipy_rankdata(a):
"""
Ranks the data, dealing with ties appropriately.
Equal values are assigned a rank that is the average of the ranks that
would have been otherwise assigned to all of the values within that set.
Ranks begin at 1, not 0.
Parameters
----------
a : array_like
... | 5,286,136 |
def handle_filters(payload):
"""
Add filters to the filter object based on received arguments
"""
args_conversion = {
'alert-status': 'alert.status',
'policy-name': 'policy.name',
'policy-label': 'policy.label',
'policy-compliance-standard': 'policy.complianceStandard',
... | 5,286,137 |
def _return_4roles(Z_com_deg, parti_coef):
"""private function for computing 4 roles"""
assert Z_com_deg.shape[0] == parti_coef.shape[0], ("Error, Z_com_deg {} \
should have same length as parti_coef {} ".format(Z_com_deg.shape[0],
parti_coef.sha... | 5,286,138 |
def xy_to_cxcy(xy):
"""
Convert bounding boxes from boundary coordinates (x_min, y_min, x_max, y_max) to center-size coordinates (c_x, c_y, w, h).
:param xy: bounding boxes in boundary coordinates, a tensor of size (n_boxes, 4)
:return: bounding boxes in center-size coordinates, a tensor of size (n_box... | 5,286,139 |
def delete_app_env(appname, envname):
"""Delete the specified environmental variable set"""
app = _get_app(appname)
deleted = app.remove_env_set(envname)
if not deleted:
abort(404, 'App `%s` has no env `%s`' % (app.name, envname))
return DEFAULT_RETURN_VALUE | 5,286,140 |
def _angle(p,q,r):
"""
compute the positive angle formed by PQR
"""
return np.abs(get_angle_between(Ray(q,p),Ray(q,r))) | 5,286,141 |
def plotMatrix(matrix, title, xticklabels: Sequence[str], yticklabels: Sequence[str], xlabel: str, ylabel: str, normalize=True, figsize=(9,9),
titleAdd: str = None) -> matplotlib.figure.Figure:
"""
:param matrix: matrix whose data to plot, where matrix[i, j] will be rendered at x=i, y=j
:param title... | 5,286,142 |
def reformat(session: nox.Session) -> None:
"""Reformat this project's modules to fit the standard style."""
install_requirements(session, "reformat")
session.run("black", *GENERAL_TARGETS, *verbose_args())
session.run("isort", *GENERAL_TARGETS, *verbose_args())
session.log("sort-all")
LOGGER.d... | 5,286,143 |
def _sample_flux_snr(distances, fwhm, plsc, n_injections, flux_min, flux_max,
nproc=10, random_seed=42, wavelengths=None, spectrum=None,
mode='median', scaling='temp-standard',
svd_mode='randsvd'):
"""
Sensible flux intervals depend on a combination... | 5,286,144 |
def chi_srch(char):
"""Search the chinese chars"""
for image in ImageData.objects(chi_cap=char):
found_images.add(image) | 5,286,145 |
def addBrightness(image, scale):
"""Adds Brightness to an image.
Parameters:
image (PIL.Image.Image) = The image to be modified.
Returns:
bright.enhance(1.1) = The modified image.
"""
#Use the pillow brightness method to add brightness
bright = ImageEnhan... | 5,286,146 |
def download_log_simple():
"""
Download the log of job types that have a single console log
:return: 0 in case of success, -1 in case of an error
"""
response = requests.get("{}/job/{}/{}/consoleText".format(jenkins_url, job_name, build_id), stream=True,
auth=(login_name,... | 5,286,147 |
def register_event_to_calendar(event: dict[str, str]) -> None:
"""
イベント情報を PyCon JP カレンダーに登録する
https://developers.google.com/resources/api-libraries/documentation/calendar/v3/python/latest/calendar_v3.events.html
:param dict event: connpassのイベント情報
"""
# カレンダーAPIを使用するためにサービスを取得
calendar = g... | 5,286,148 |
def test_can_connect(aggregator, instance, dd_run_check):
"""
Regression test: a copy of the `can_connect` service check must be submitted for each check run.
(It used to be submitted only once on check init, which led to customer seeing "no data" in the UI.)
"""
check = ClickhouseCheck('clickhouse'... | 5,286,149 |
async def _compose(choice):
"""Figure out exactly what resource we're requesting and return the correct
class."""
nchoice = list(choice.keys())[0]
id = list(choice.values())[0]
if '_id' in nchoice:
nchoice = nchoice[:-3]
return ('/'.join([base_uri, nchoice, str(id), '']), nchoice) | 5,286,150 |
def validate(guess: str, solution: str) -> str:
"""Validates the user guess against the solution, coloring correct characters"""
return "".join([validate_char(i, guess, solution) for i in range(WORD_LENGTH)]) | 5,286,151 |
def infection_rate_symptomatic_80x40():
"""
Real Name: b'infection rate symptomatic 80x40'
Original Eqn: b'Susceptible 40*Infected symptomatic 40x80*contact infectivity symptomatic 40x80*(self quarantine policy SWITCH self 40\\\\ * self quarantine policy 40+(1-self quarantine policy SWITCH self 40))/non con... | 5,286,152 |
def input_text(frame_r: tk.Frame,
label_text: str,
text_width: int,
initial: str = None,
side_: constants = TOP,
side_label: constants = LEFT,
fmt: str = None):
"""テキストの入力ボックスを作成
Args:
frame_r (tkinter.Frame): 配置す... | 5,286,153 |
def plot_pca_variance(data):
"""Runs PCA on passed data and creates the plot figure to visualize the
variance corresponding to each component and returns finally the figure object.
Consider that the method matplotlib.pyplot.show is called inside this function
and the plot is showed if the regarding exec... | 5,286,154 |
def connect_to_database(user: str, database: str):
""" Connects to the PostgreSQL database
Creates connection to the backend PostgreSQL database.
Args:
user: PostgreSQL username to acces the database.
database: Name of the database to connect to.
Todo:
* Add support for more ... | 5,286,155 |
def _get_validated_args(input_args: Optional[List[str]] = None) -> argparse.Namespace:
"""validate arguments"""
parser = argparse.ArgumentParser()
# These parameters are always required
parser.add_argument("--tasks", default="BoolQ,CB,RTE", type=str, required=True,
help="Choose o... | 5,286,156 |
def on_volume_balance_vec(data_df, window=14):
"""
On Volume Balance (OBV).
:param data_df: Unstacked for one symbol only.
:param window: An integer number of days to look back.
:return: A pandas Series with the values of OBV for all the valid dates.
"""
obv_delta = data_df['Volume'] * np.si... | 5,286,157 |
def centroidCalculator(cell):
"""
Centroid is assumed to be roundish so the euclidean distance will always
be larger at that region than along protrusions.
"""
edt = distance_transform_edt(cell)
centroid = np.where(edt == np.max(edt))
centroid = [centroid[0][0], centroid[1][0]]
return ... | 5,286,158 |
def is_ethernet_port(interface):
"""Judge whether it is ethernet port"""
ethernet_port = ['ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'meth']
if_type = get_interface_type(interface)
if if_type in ethernet_port:
return True
return False | 5,286,159 |
def cross_product_configs(**configs):
"""
Given configs from users, we want to generate different combinations of
those configs
For example, given M = ((1, 2), N = (4, 5)),
we will generate (({'M': 1}, {'N' : 4}),
({'M': 1}, {'N' : 5}),
({'M': 2}, {'N' : 4... | 5,286,160 |
def parse_distribution(s):
"""
Parses the distribution from the given string
"""
segments = s.split(' ')
dist = segments[0]
args = segments[1:]
# Check to see if the given distribution is supported
if dist not in distributions.keys():
raise ValueError('Unsupported distribution %... | 5,286,161 |
def run_cgi(cgi, req_type, req_content, cookie=None):
"""CGI handler. It maps the given request to appropriate place, and run it"""
print("running: " + WWWROOT + cgi)
new_env = os.environ.copy()
if cookie is not None:
new_env['HTTP_COOKIE'] = cookie
runner_stdin = None
if req_type == "GE... | 5,286,162 |
def calculate_p_b(*args):
"""
Determines how difficult a text is according to the number of words that are, most likely, unknown to readers.
The other formulas we referred to based the score on the number of words and sentences only
"""
words_count, sentences_count, diff_words_count = args[0... | 5,286,163 |
def part1(entries: tuple) -> int:
"""part1 solver"""
card_key, door_key = entries
loop_size = 0
key = 1
while key not in (card_key, door_key):
loop_size += 1
key = (key * 7) % 20201227
if key == card_key:
return pow(door_key, loop_size, 20201227)
return pow(card_key,... | 5,286,164 |
def train(args):
"""Train with the given args.
Args:
args (namespace): The program arguments.
"""
set_deterministic_pytorch(args)
# check cuda availability
if not torch.cuda.is_available():
logging.warning('cuda is not available')
# get input and output dimension info
... | 5,286,165 |
def id_function(fixture_value):
"""Convert a param from the use_case fixture to a nicer name.
By default, the name (used in the test generated from the parameterized
fixture) will use the fixture name and a number.
Eg: test_foo[use_case0]
Providing explicit 'ids' (either as strings, or as a functi... | 5,286,166 |
def iterparshios(year, israel=False):
"""Generate all the parshios in the year.
Parameters
----------
year : int
The Hebrew year to get the parshios for.
israel : bool, optional
``True`` if you want the parsha according to the Israel schedule
(with only one day of Yom Tov). Defau... | 5,286,167 |
async def async_test_dimmer_from_light(hass, cluster, entity_id,
level, expected_state):
"""Test dimmer functionality from the light."""
attr = make_attribute(0, level)
cluster.handle_message(False, 1, 0x0a, [[attr]])
await hass.async_block_till_done()
assert h... | 5,286,168 |
def application_create(request, name, redirect_uris, scopes=['all_info'],
client_type='confidential', description=None,
grant_type='authorization_code', **kwargs):
""" Registers a new consumer in the Keystone OAuth2 extension.
In FIWARE applications is the name OAu... | 5,286,169 |
def del_lo_ipaddr(nflink, ip_addr, prefix_len):
"""Remove ipv4 address from loopback interface
Remove existing ipv4 address, defined by ip_addr and prefix_len, from
loopback interface.
Args:
nflink: a pyroute2.IPRoute() object/NFLINK connection
ip_addr (str): IP address
prefix_... | 5,286,170 |
def recursive_plot(data, plot_function, ax, **kwargs):
"""A utility to recursively plot sets of data.
Parameters
----------
data : list
List of datasets to iteratively add to the plot.
plot_function : callable
Plot function to call to plot the data.
ax : matplotlib.Axes
... | 5,286,171 |
def create_spreadsheets_json(worksheet_title=None):
"""
create base parameters json for spreadsheets api call
"""
if worksheet_title is None:
raise ValueError('Missing worksheet_title parameter')
return {
"spreadsheet_key": SPREADSHEET_KEY,
"worksheet_title": worksheet_t... | 5,286,172 |
def draw_histogram(x_data, y_data, title, legend_img_uri, filename):
"""Creates a histogram.
Does not use plotly's histogram functionality
(https://plot.ly/python/histograms) as the data is already binned
in pandas (see calc_histogram() in lists.py). Instead uses a bar
chart with no spacing and x-a... | 5,286,173 |
def os_version_arch():
"""Return OS name, version and platform architecture."""
system = platform.system()
version = ""
arch = platform.machine()
if system == "Darwin":
return "darwin", "", arch
if system == "Windows":
return "windows", "", arch
if system == "Linux":
... | 5,286,174 |
def constraint_configure_mentoring(model, tracks, v_tdh):
"""Configure the mentoring of onboarders appropriately."""
# If agent is on, he/she to be paired with exactly 1 mentor:
for d in range(num_days):
for h in agents_onb:
model.Add(
sum(v_mentors.loc[(d, h)].values.tol... | 5,286,175 |
def update_open_pos_stats_nb(record: tp.Record, position_now: float, price: float) -> None:
"""Update statistics of an open position record using custom price."""
if record['id'] >= 0 and record['status'] == TradeStatus.Open:
if np.isnan(record['exit_price']):
exit_price = price
else... | 5,286,176 |
def fail():
"""
No argument, raises an exception
"""
raise ValueError("Everything I do fails") | 5,286,177 |
def json_export(out: Export = Export("sbx_metadata/[metadata.id].json"),
corpus_id: Corpus = Corpus(),
lang: Language = Language(),
metadata: dict = Config("metadata"),
sentences: AnnotationCommonData = AnnotationCommonData("misc.<sentence>_count"),
... | 5,286,178 |
def _parts_span_selector(pspec):
"""
Selector for `System`Span` part specification
"""
if len(pspec.leaves) > 3:
raise MessageException("Part", "span", pspec)
start = 1
stop = None
step = 1
if len(pspec.leaves) > 0:
start = pspec.leaves[0].get_int_value()
if len(pspec... | 5,286,179 |
def generateTests(j):
"""Generate all tests and pass along the j parameter to make."""
if isWin():
doCommand("mingw32-make -j%d generate-tests -s" % (j or 1))
else:
doCommand("make -j%d generate-tests -s" % (j or 1)) | 5,286,180 |
def selection(triple, variables):
"""Apply selection on a RDF triple"""
bindings = set()
if variables[0] is not None:
bindings.add((variables[0], triple[0]))
if variables[1] is not None:
bindings.add((variables[1], triple[1]))
if variables[2] is not None:
bindings.add((variab... | 5,286,181 |
def schema_factory(
schema_cls: Type[BaseModel],
name: str = "",
excludes: List[str] = ["id", "created_at", "updated_at"],
) -> Type[BaseModel]:
"""
Is used to create a CreateSchema which does not contain pk
From: https://github.com/awtkns/fastapi-crudrouter/blob/master/fastapi_crudrouter/core/_... | 5,286,182 |
def daily_std_error(merged_data):
"""Calculates daily seasonal standard error of the timeseries data in a DataFrame
Parameters
----------
merged_data: DataFrame
A pandas DataFrame with a datetime index and columns containing float type values.
Returns
-------
DataFrame
A p... | 5,286,183 |
def bruteforce(model, c, max_iter=1000):
"""
Generiere Zufallsdaten, bis diese eine Klasse maximieren oder die maximale Anzahl an Iterationen verbraucht ist.
"""
shape = (1,) + model.input_shape[1:]
for i in range(max_iter):
image = np.random.random(shape)
prediction = model.predict(... | 5,286,184 |
def process_logic(op):
"""
Parse the binary operation binary expression.
Convert operator to fabric of AST-classes 'AndBexp' / 'OrBexp'.
"""
if op == '&&':
return lambda l, r: AndBexp(l, r)
elif op == '||' or op == '!!':
return lambda l, r: OrBexp(l, r)
else:
raise Ru... | 5,286,185 |
def update_reporting(options, is_quiet_task, run_tracker):
"""Updates reporting config once we've parsed cmd-line flags."""
# Get any output silently buffered in the old console reporter, and remove it.
old_outfile = run_tracker.report.remove_reporter('capturing').settings.outfile
old_outfile.flush()
buffere... | 5,286,186 |
def _build_chef_properties(env, config_file):
"""
Build python object representation of the Chef-solo node.json file from
node_extra.json in config dir and the fabric environment.
"""
json_properties = _parse_json(config_file)
return build_properties(env, "chef", json_properties) | 5,286,187 |
def bond_vector(xi, xi_neig, box_length):
""" Determine the normalized bond vector between atoms i and j.
"""
bond = xi - nearest_atom_image(xi_neig, xi, box_length)
bond /= np.linalg.norm(bond)
return bond | 5,286,188 |
def get_activation_fn(name, framework="tf"):
"""Returns a framework specific activation function, given a name string.
Args:
name (str): One of "relu" (default), "tanh", or "linear".
framework (str): One of "tf" or "torch".
Returns:
A framework-specific activtion function. e.g. tf.... | 5,286,189 |
def rolling_weighted_triangle_conv(values, weights, window_size):
"""Smoothes the data with a window and given the weights
Original algorithm: stackoverflow.com/a/46232913/1257075
Returns:
Smoothed values
Args:
values: data to smoothen
weights: weights for each data point
window_s... | 5,286,190 |
def par(q):
"""Parameterize using t^3 + t, where t is the polar angle."""
t = np.arctan2(q[1], q[0])
# A simple diffeomorphism from R^1 -> R^1.
return t**3 + t | 5,286,191 |
def tanimoto_sparse(str1, str2):
"""!
Calculate the tanimoto coefficient for a pair of sparse vectors
@param str1 str: String of 1s and 0s representing the first compound fingerprint
@param str2 str: String of 1s and 0s representing the second compound fingerprint
@return Returns float
"""
n... | 5,286,192 |
def perform_experiment(relax: bool, spring_constant: Vector, random_strength: Vector, seed: Vector):
"""
A function that takes potential values of parameters and returns a dataframe with experiment results
for all possible combinations of these parameters.
Parameters
----------
relax : bool
... | 5,286,193 |
def test_table_expire():
"""
Tests the table expire command.
"""
ret = {}
ret["stderr"] = "1/1 addresses expired."
ret["retcode"] = 0
mock_cmd = MagicMock(return_value=ret)
with patch.dict(pf.__salt__, {"cmd.run_all": mock_cmd}):
assert pf.table("expire", table="bad_hosts", numbe... | 5,286,194 |
def get_saml_response(html):
"""
Parse SAMLResponse from Shibboleth page
>>> get_saml_response('<input name="a"/>')
>>> get_saml_response('<body xmlns="bla"><form><input name="SAMLResponse" value="eG1s"/></form></body>')
'xml'
"""
soup = BeautifulSoup(html, "html.parser")
for elem in ... | 5,286,195 |
def _is_namespace_visible(context, namespace):
"""Return true if namespace is visible in this context"""
if context.is_admin:
return True
if namespace.get('visibility', '') == 'public':
return True
if namespace['owner'] is None:
return True
if context.owner is not None:
... | 5,286,196 |
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.a... | 5,286,197 |
def get_aa_subseq_df(sg_designs, aa_seq_df, width, id_cols,
transcript_base_col='Transcript Base',
target_transcript_col='Target Transcript',
aa_index_col='AA Index'):
"""Get the amino acid subsequences for a design dataframe
:param sg_designs: Dat... | 5,286,198 |
def _step(context, element):
"""
:type context: HackedContext
"""
try:
item = context.driver.simple_find(element)
assert not item.is_displayed(),\
u'{} should not be present and displayed'.format(element)
except NoSuchElementException:
pass | 5,286,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.