content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _live_tensors(f, attr_name="inputs"):
"""Returns the indices of the used inputs.
Note: This currently only handles direct index accesses e.g. op.inputs[1].
If the function has slicing or list comprehension on attr_name then returns
_ALL. This ensure that this is correct even if inefficient.
Args:
f:... | 3,000 |
def update_site_config(site_name, parameters):
"""Update the site config to establish the database settings"""
site_directory = os.path.join('web', 'sites', site_name)
if not os.path.isdir(site_directory):
print('site directory {} missing'.format(site_directory))
sys.exit(-1)
config_fil... | 3,001 |
def plot_with_front(gen, front, title, fname):
"""
plot with front: Print the generation gen and front,
highlighting front as the pareto front on the graph.
Parameters:
gen: The generation to plot.
front: The pareto front extracted from generation gen
title: Plot Title
fname: path t... | 3,002 |
def find_closest_positive_divisor(a, b):
"""Return non-trivial integer divisor (bh) of (a) closest to (b) in abs(b-bh) such that a % bh == 0"""
assert a>0 and b>0
if a<=b:
return a
for k in range(0, a-b+1):
bh = b + k
if bh>1 and a % bh == 0:
return bh
bh = b ... | 3,003 |
def simplify_stl_names(decl):
"""Take common STL/Standard Library names and simplify them to help make the
stack trace look more readable and less like the graphics in the matrix.
"""
p = simplify_template_call(decl)
if p == []:
return decl
return p[0] + '<' + ', '.join(p[1:-1]) + ... | 3,004 |
def check_exising_flags(ds_ind, stokes='I', client=None):
""" Check the existing flags in the input Measurement Set."""
# Determine which polarization state to grid and flag
if stokes=='I':
flags = ds_ind.FLAG.data[:,0] | ds_ind.FLAG.data[:,-1]
elif stokes=='Q':
flags = ds_ind.FLAG.... | 3,005 |
def sample_switching_models(
models: Sequence,
usage_seq: Sequence,
X: Union[None, Sequence, Callable] = None,
initial_conditions: Optional[Tuple[Sequence, Sequence]] = None,
return_input: bool = False,
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
""" Sample from a non-stationary stoch... | 3,006 |
def test_remove(tree_fixture):
"""Test removal of nodes.
"""
tree = tree_fixture[0]
n = tree_fixture[1]
tree.add(n[1])
tree.add(n[2])
tree.add(n[3], parent=n[1])
tree.add(n[4], parent=n[3])
tree.add(n[5], parent=n[4])
assert tree._nodes == [n[1], n[3], n[4], n[5], n[2]]
al... | 3,007 |
def eval_per_class(c_dets, c_truths, overlap_thresh=0.5, eval_phrase=False):
""" Evaluation for each class.
Args:
c_dets: A dictionary of all detection results.
c_truths: A dictionary of all ground-truth annotations.
overlap_thresh: A float of the threshold used in IoU matching.
Re... | 3,008 |
def define_components(mod):
"""
Adds components to a Pyomo abstract model object to describe
unit commitment for projects. Unless otherwise stated, all power
capacity is specified in units of MW and all sets and parameters
are mandatory.
-- Commit decision, limits, and headroom --
CommitP... | 3,009 |
def adjustwithin(df, pCol, withinCols, method='holm'):
"""Apply multiplicity adjustment to a "stacked"
pd.DataFrame, adjusting within groups defined by
combinations of unique values in withinCols
Parameters
----------
df : pd.DataFrame
Stacked DataFrame with one column of pvalues
... | 3,010 |
def parse_url_query_params(url, fragment=True):
"""Parse url query params
:param fragment: bool: flag is used for parsing oauth url
:param url: str: url string
:return: dict
"""
parsed_url = urlparse(url)
if fragment:
url_query = parse_qsl(parsed_url.fragment)
else:
url_... | 3,011 |
def sample_random_lightdirs(num_rays, num_samples, upper_only=False):
"""Randomly sample directions in the unit sphere.
Args:
num_rays: int or tensor shape dimension. Number of rays.
num_samples: int or tensor shape dimension. Number of samples per ray.
upper_only: bool. Whether to samp... | 3,012 |
def gaussgen(sigma):
"""
Function to generate Gaussian kernels, in 1D, 2D and 3D.
Source code in MATLAB obtained from Qiyuan Tian, Stanford University, September 2015
:param sigma: Sigma for use in generating Gaussian kernel (see defaults in generate_FSL_structure_tensor)
:return: Gaussian kernel wi... | 3,013 |
def metrics_specs_from_keras(
model_name: Text,
model_loader: types.ModelLoader,
) -> List[config.MetricsSpec]:
"""Returns metrics specs for metrics and losses associated with the model."""
model = model_loader.construct_fn()
if model is None:
return []
metric_names = []
metrics = []
if hasattr... | 3,014 |
def __main__(recipe, params):
"""
Main code: should only call recipe and params (defined from main)
:param recipe:
:param params:
:return:
"""
# ----------------------------------------------------------------------
# Main Code
# -----------------------------------------------------... | 3,015 |
def AICrss(n, k, rss):
"""Calculate the Akaike Information Criterion value, using:
- n: number of observations
- k: number of parameters
- rss: residual sum of squares
"""
return n * log((2 * pi) / n) + n + 2 + n * log(rss) + 2 * k | 3,016 |
def CONVERT_OUT(s):
"""
convert a directory of module into a reponsed output directory
if s doesn't beneath the module, raise NotInSelfModuleError
Args:
s : a relative directory beneathed the module
Returns:
return the relative path of responsed output directory
"""
if sys.ar... | 3,017 |
def random_traveling_salesman(points, distmat, avg_edges=None, start=None,
max_perm_samples=2e3, end=None, debug=0):
"""
Finds the shortest route to visit all the cities by bruteforce.
Time complexity is O(N!), so never use on long lists.
We use a limit of max_perm_samples (default=2k) random s... | 3,018 |
def get_username_from_access_token(token: str, secret_key: str, algorithm: str) -> Optional[str]:
"""
Decodes a token and returns the "sub" (= username) of the decoded token
:param token: JWT access token
:param secret_key: The secret key that should be used for token decoding
:param algorithm: The ... | 3,019 |
def _inject_getter_attrs(
metaself,
objname,
attrs,
configurable_attrs,
depc_name=None,
depcache_attrs=None,
settable_attrs=None,
aliased_attrs=None,
):
"""
Used by the metaclass to inject methods and properties into the class
inheriting from ObjectList1D
"""
if sett... | 3,020 |
def date_handler(obj):
"""make datetime object json serializable.
Notes
-----
Taken from here: https://tinyurl.com/yd84fqlw
"""
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError | 3,021 |
def add_token_price(token, _method, _id, price):
""" Adds a new token on coinprices.json """
token = token.lower()
with open(coinprices_path) as f:
coinprices = json.load(f)
coinprices[token] = {}
coinprices[token]['method'] = _method
coinprices[token]['id'] = _id
coinprices[token]... | 3,022 |
def has_type(typestmt, names):
"""Return type with name if `type` has name as one of its base types,
and name is in the `names` list. otherwise, return None."""
if typestmt.arg in names:
return typestmt
for t in typestmt.search('type'): # check all union's member types
r = has_type(t, n... | 3,023 |
def generic_ecsv(file_name, column_mapping=None, **kwargs):
"""
Read a spectrum from an ECSV file, using generic_spectrum_from_table_loader()
to try to figure out which column is which.
The ECSV columns must have units, as `generic_spectrum_from_table_loader`
depends on this to determine the meaning... | 3,024 |
def parse_valuation_line(s, encoding=None):
"""
Parse a line in a valuation file.
Lines are expected to be of the form::
noosa => n
girl => {g1, g2}
chase => {(b1, g1), (b2, g1), (g1, d1), (g2, d2)}
:param s: input line
:type s: str
:param encoding: the encoding of the input... | 3,025 |
def scrape_dailykos(keywords=KEYWORDS):
"""
Scrapes news article titles from dailykos.com
"""
dk_request = requests.get('https://www.dailykos.com')
dk_homepage = dk_request.content
dk_soup = BeautifulSoup(dk_homepage, 'html.parser')
dk_tags = dk_soup.find_all('div', class_='cell-wrapper')
... | 3,026 |
def write_json(file_path, data, do_clear=False):
"""Write `data` to the JSON file specified by `file_path`, optionally clearing the file before
adding `data`
Parameters
----------
file_path: String
The target .json file path to which `data` will be written
data: Object
The conte... | 3,027 |
def test_output_result_01(fixture_main_detection_01, monkeypatch):
"""output_result emits files (plot is excluded from test)"""
args = fixture_main_detection_01["args"]
log = pd.DataFrame(
[
[pd.Timestamp("2021-06-01 01:00:00"), "1.1.1.1", 1, 11],
[pd.Timestamp("2021-06-01 02... | 3,028 |
def parse_rows(m: utils.Matrix[str]) -> pd.DataFrame:
"""Parse rows to DataFrame, expecting specific columns and types."""
if len(m) < 2:
logger.error('More than one line expected in {}'.format(str(m)))
return pd.DataFrame()
# parse data rows and add type casting
cols = len(m[0])
df... | 3,029 |
def tiny_id(page_id):
"""Return *tiny link* ID for the given page ID."""
return base64.b64encode(struct.pack('<L', int(page_id)).rstrip(b'\0'), altchars=b'_-').rstrip(b'=').decode('ascii') | 3,030 |
def test_smooth_goddard_2013(PM_da_control_3d_full):
"""Test whether Goddard 2013 recommendations are fulfilled by
smooth_Goddard_2013."""
da = PM_da_control_3d_full
actual = smooth_goddard_2013(
da,
)
# test that x, y not in dims
assert "x" not in actual.dims
assert "y"... | 3,031 |
def invert_color(color: str, *, black_or_white: bool = False) -> str:
"""Return a color with opposite red, green and blue values.
Example: ``invert_color('white')`` is ``'#000000'`` (black).
This function uses tkinter for converting the color to RGB. That's
why a tkinter root window must have been cre... | 3,032 |
def pcaImageCube(ref, mask = None, pcNum = None, cube=True, ref3D=True, outputEval = False):
"""Principal Component Analysis,
Input:
ref: Cube of references, 3D;
if ref3D==False, 2D (Flattened and Normalized, with maksked region excluded.)
mask: mask, 2D or 1D;
pcNum: how... | 3,033 |
def get_cross_kerr_table(epr, swp_variable, numeric):
"""
Function to re-organize the cross-Kerr results once the quantum analysis is finished
Parameters:
-------------------
epr : Object of QuantumAnalysis class
swp_variable : the variable swept in data according to w... | 3,034 |
def getSpectra(dataframe, indices):
""" Returns the files for training and testing
Inputs
-----------
dataframe: pd.DataFrame object from which we need to get spectra
indices: row values for which we need the spectra
Returns
-----------
spec_vals: pd.DataFrame object ... | 3,035 |
def config2():
"""Configure for one of the restart tests."""
return Config.load(f"""
id: cbc_binary_toolkit
version: 0.0.1
database:
_provider: tests.component.persistor_fixtures.mock_persistor.MockPersistorFactory
engine:
_provider: tests.component.engine_fixtures.mock_engine.MockLo... | 3,036 |
async def test_hmip_light(hass, default_mock_hap):
"""Test HomematicipLight."""
entity_id = "light.treppe"
entity_name = "Treppe"
device_model = "HmIP-BSL"
ha_entity, hmip_device = get_and_check_entity_basics(
hass, default_mock_hap, entity_id, entity_name, device_model
)
assert ha... | 3,037 |
def _on_process(*args, **kwargs):
"""Process the given function in the current subprocess"""
try:
func = kwargs['__func__']
del kwargs['__func__']
return func(*args, **kwargs)
except KeyboardInterrupt:
sys.exit()
except Exception as e:
raise type(e)(traceback.form... | 3,038 |
def test_make_psfs_overwriteFalse(L_radec):
"""
test that when overwrite=False make_psf() does not update file
"""
L = L_radec
overwrite = False
for band in L.bands:
file = dir_obj+'psf-{0}.fits'.format(band)
if not os.path.isdir(dir_obj):
os.makedirs(dir_obj)
if os.path.isfile(file):
os.remove(... | 3,039 |
def diff_cases(couch_cases, log_cases=False):
"""Diff cases and return diff data
:param couch_cases: dict `{<case_id>: <case_json>, ...}`
:returns: `DiffData`
"""
assert isinstance(couch_cases, dict), repr(couch_cases)[:100]
assert "_diff_state" in globals()
data = DiffData()
dd_count =... | 3,040 |
def rk4(a, b, x0, y0, nu=0, F=0, xdot = x_dot, ydot = y_dot):
"""rk(a, b, x0, y0, nu=0, F=0, xdot = x_dot, ydot = y_dot)
Args:
a (float) : Lower bound, t = a*2*pi
b (float) : Upper bound, t = b*2*pi
x0 (float) : Initial position of ball
y0 (float) : Initial velocity of bal... | 3,041 |
def decode_callbacks(encoded_callbacks):
"""Decode the callbacks to an executable form."""
from furious.async import Async
callbacks = {}
for event, callback in encoded_callbacks.iteritems():
if isinstance(callback, dict):
async_type = Async
if '_type' in callback:
... | 3,042 |
def create_conv_block(
use_depthwise, kernel_size, padding, stride, layer_name, conv_hyperparams,
is_training, freeze_batchnorm, depth):
"""Create Keras layers for depthwise & non-depthwise convolutions.
Args:
use_depthwise: Whether to use depthwise separable conv instead of regular
conv.
... | 3,043 |
def hard_reset():
"""saves an empty pickle [], so you can rerun on all .JSONs"""
instance = event_handler()
instance.pickle_save(database_dir,file_name="daily_list.pkl") | 3,044 |
def select_eps_for_division(dtype):
"""Selects default values for epsilon to make divisions safe based on dtype.
This function returns an epsilon slightly greater than the smallest positive
floating number that is representable for the given dtype. This is mainly used
to prevent division by zero, which produces... | 3,045 |
def train_freezed_model(x, y, x_tk, y_tk, freezed_comp='encoder', use_check_point=False):
"""
train the translation model and save checkpoint
:param x: Preprocessed English data
:param y: Preprocessed French data
:param x_tk: English tokenizer
:param y_tk: French tokenizer
:param freezed_com... | 3,046 |
def bpm_to_mspt(bpm, res=480):
"""
Coverts an integer value of beats per minute to miliseconds per quarter note
"""
return 60000 / res / bpm | 3,047 |
def Test_frcnn(test_images_list,
network_arch,
config_filename,
preprocessing_function = None,
num_rois = None,
final_classification_threshold = 0.8):
"""
Test the object detection network
test_images_list --list: list co... | 3,048 |
def pseudorandom(n, p, key):
""" Pseudorandom array of integer indexes
>>> pseudorandom(5, [0.5, 0.5], key=123)
array([1, 0, 0, 1, 1], dtype=int8)
>>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], key=5)
array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8)
"""
import numpy as np
p = list(p)
... | 3,049 |
def next_hidden(s, A):
"""From a given state s, use the transition matrix A to generate the next
hidden state.
"""
return choose_idx(A[s]) | 3,050 |
def create_network_rcnn(cls, opt):
"""Separate function for rcnn, which always loads weights first, no init."""
net = cls(opt)
net.print_network()
util.load_network_path(net, opt.fastercnn_loc, strict=True, rcnn_load=True)
if len(opt.gpu_ids) > 0:
assert(torch.cuda.is_available())
ne... | 3,051 |
def get_board_frame(window, mqtt_sender):
"""Builds the chessboard GUI."""
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
frame_label = ttk.Label(frame, text="Board")
get_state = ttk.Button(frame, text="Get state")
get_state["command"] = lambda: handle_get_stat... | 3,052 |
def compute_rest_time(gps_data, radius):
"""Compute the duration during which the track stays in a given radius of each
point.
Args:
gps_data (:py:class:`~gps_data_analyzer.gps_data.PoiPoints`): The data used for
computation.
radius (float): The radius in which the rest time is ... | 3,053 |
def add_fundamentals_to_db():
"""
Adds the fundamental data to the database from a json file
:return:None
"""
fundFile = 'sectorAnalysis/fundamentals/combinedFundamentals.json'
funds = pd.read_json(fundFile)
manager = CollectionManager('10y_Fundamentals', 'AlgoTradingDB')
for index, ro... | 3,054 |
def tag_resource(resourceArn=None, tags=None):
"""
Associates the specified tags to a resource with the specified resourceArn . If existing tags on a resource aren\'t specified in the request parameters, they aren\'t changed. When a resource is deleted, the tags associated with that resource are also deleted.
... | 3,055 |
def body():
"""Get map page body.
Returns:
html.Div: dash layout
"""
graph_map = get_graph_map()
if graph_map is None:
return html.Div(
dbc.Alert("Cannot retrieve data! Try again later!", color="danger")
)
# Put everything in a dcc container and return
b... | 3,056 |
def plot_loss(train_loss=None, test_loss=None, epochs=None, figsize=(10, 10)):
"""
Plot the 3 losses (KLD, REC_LOSS, REC_LOSS + KLD) for possibly train and test data
:param train_loss: array where elements are [KLD, REC_LOSS, REC_LOSS + KLD]
:param test_loss: array where elements are [KLD, REC_LOSS, REC... | 3,057 |
def coreg_scalp_surfaces(subject_ids, subjects_dir=None):
"""
Routine to generate high-resolution head surfaces for coordinate alignment
Parameters
----------
subject_ids: list of strings
List of subjects ids
subjects_dir: string
Stri... | 3,058 |
def custom_strftime(formatting: str, date: datetime.datetime) -> str:
"""Custom strftime formatting function, using fancy number suffixes (1st, 2nd, 3rd...)"""
return date.strftime(formatting).replace("{S}", str(date.day) + suffix(date.day)) | 3,059 |
def get_sample_rate() -> int:
"""
Get current sampling rate (it may differ from the frequency specified in sv_init())
""" | 3,060 |
def make_workdir(run_dir, ccp4i2=False, MAX_WORKDIRS=100):
"""Make a work directory rooted at run_dir and return its path
Parameters
----------
run_dir : str
The path to a run directory where the job was started
ccp4i2 : bool, optional
Indicate if we are running under CCP4I2
Ret... | 3,061 |
def setup_twitter(config_file='config.py'):
"""Setup auth keys and session with Twitter client."""
config = {}
execfile(config_file, config)
twitter_obj = Twitter(auth=OAuth(config["access_key"],
config["access_secret"],
config["consumer... | 3,062 |
def create_datediff_test_nulls_df():
"""Create DataFrame with nulls only for DateDifferenceTransformer tests."""
df = pd.DataFrame(
{
"a": [
datetime.datetime(1993, 9, 27, 11, 58, 58),
np.NaN,
],
"b": [
np.NaN,
... | 3,063 |
def business_days_list(start_date: date, end_date: date) -> list[date]:
""" business days """
us_holidays = holidays.UnitedStates()
days: list[date] = []
for the_date in get_list_of_days(start_date, end_date):
if (the_date.weekday() < 5) and (the_date not in us_holidays):
days.app... | 3,064 |
def test_3d():
"""Test FE in 3D"""
def setone(arr):
arr[0, :, (arr.shape[0] - 1) // 2] = 1.0
return arr
assert pipe(
5,
lambda x: np.zeros((1, x, x, x), dtype=int),
setone,
solve_fe(elastic_modulus=(1.0, 10.0), poissons_ratio=(0.0, 0.0)),
lambda x: n... | 3,065 |
def get_xray_edges(elements: List[str], wmin: float, wmax: float):
"""
Using xraydb, return the absorbtion edges
Parameters
----------
elements: List[str]
A list of the element symbols from which to query absorption edges.
wmin: float
The smallest wavelength edge to return
w... | 3,066 |
def register(klass):
"""
Registers a Report Engine Report. This gets the namespace and class's slug, puts them in a tuple, and stores the
report, indexed by the namespace, slug tuple.
:param klass: The class of the report to register.
:return:
"""
_registry[(klass.namespace,klass.slug)] = ... | 3,067 |
def get_mobility_link():
"""Get Apple Mobility data link
"""
# get link
with urllib.request.urlopen(index_url) as url:
json_link = json.loads(url.read().decode())
base_path = json_link['basePath']
csv_path = json_link['regions']['en-us']['csvPath']
link = site_url + \
... | 3,068 |
def test_wizard_requires_valid_ssid(tmpdir, monkeypatch, wizard_answers):
"""
When the board is not a valid esp8266 board, the wizard should reject it
"""
# Given
wizard_answers.insert(3, "") # add an invalid entry for ssid
config_file = tmpdir.join("test.yaml")
input_mock = MagicMock(sid... | 3,069 |
def publish():
"""
Prepares the project locally for HTML publication on GitHub Pages to make
the built document available to the general public.
Only supports the default `output/html` build directory.
Requires Git and a GitHub account.
"""
from . import utils
if not utils.directory_exis... | 3,070 |
def active_shift(app, token, gqlClient):
"""returns the currently active shift if it exists"""
with app.test_request_context():
request.headers = {'authorization': token}
query = '''mutation CreateShift($Active: Boolean!, $StartTime: String) {
createShift(active: $Active, startTime: $Sta... | 3,071 |
def func(arg, kwarg=None):
"""A function for general use."""
pass | 3,072 |
def tff_cc_test_with_tf_deps(name, tf_deps = [], **kwargs):
"""A version of `cc_test` that links against TF statically or dynamically.
Args:
name: A unique name for this target.
tf_deps: List of TensorFlow static dependencies.
**kwargs: `cc_test` keyword arguments.
"""
srcs = kwargs.p... | 3,073 |
def get_batch_size(input):
"""
Infer the mini-batch size according to `input`.
Args:
input (tf.Tensor): The input placeholder.
Returns:
int or tf.Tensor: The batch size.
"""
if input.get_shape() is None:
batch_size = tf.shape(input)[0]
else:
batch_size = int... | 3,074 |
def _order_points(pts: np.ndarray) -> np.ndarray:
"""Extract top left. top right, bottom left, bottom right of region
Args:
pts (np.ndarray[Tuple]): The coordinate of points
Returns:
np.ndarray: The coordinate of points.
"""
x_sorted = pts[np.argsort(pts[:, 0]), :]
left_most =... | 3,075 |
def test_list_time_length_3_nistxml_sv_iv_list_time_length_4_5(mode, save_output, output_format):
"""
Type list/time is restricted by facet length with value 8.
"""
assert_bindings(
schema="nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-length-4.xsd",
instance="nistData/li... | 3,076 |
def to_image(obj):
""" allgemeine funktion zum anschauen von allen objekttypen (work in progress)
gibt image (numpy arry),description zurück
description sagt, was alles gemacht wurde um bild darzustellen
"""
import logging
descr = ""
if (tf.is_tensor(obj)):
obj = obj.numpy()
logger = logging.... | 3,077 |
def start():
"""
Start the daemon.
"""
ret = 0
cfg = 'ludolph.cfg'
cfg_fp = None
cfg_lo = ((os.path.expanduser('~'), '.' + cfg), (sys.prefix, 'etc', cfg), ('/etc', cfg))
config_base_sections = ('global', 'xmpp', 'webserver', 'cron', 'ludolph.bot')
# Try to read config file from ~/.l... | 3,078 |
def matchPP(a_string):
"""assumes a_string is a string
returns re match object if it finds two consecutive words that start with P,
else returns None"""
pattern = "[P|p]\w+\s[P|p]\w+"
result = re.search(pattern, a_string)
return result | 3,079 |
def setBoth(s1, s2):
"""
Sets both servo motors to specified number of degrees
Args:
s1, s2 (number): degrees for left and right servos respectively
must be between -90 and 90 and will be rounded
Raises:
Exception if s1 or s2 is not a number
Returns:
None... | 3,080 |
def test_add_returns_correct_id(db_with_3_mops):
"""Test add_mop() affect on mop_db.count()."""
db = db_with_3_mops
mop_id = db.add_mop(asdict(new_mop))
assert mop_id == 4 | 3,081 |
def transfer_shfe_future_hq(date, file_path, columns_map):
"""
将每天的数据统一标准
:return: pd.DataFrame 统一标准后的数据
"""
ret = pd.DataFrame()
data = json.loads(file_path.read_text())
hq_df = pd.DataFrame(data['o_curinstrument'])
total_df = pd.DataFrame(data['o_curproduct'])
bflag = hq_df.empty... | 3,082 |
def comp_material_bsdf(arg_material_one:bpy.types.Material,
arg_material_two:bpy.types.Material) -> bool:
"""指定マテリアルのBSDFノードを比較する
受け渡したマテリアルの出力ノードに接続されたプリシプルBSDFノードを比較する
比較対象の入力端子のデフォルト値が有効、かつ、全て同一の場合、Trueを返す
Args:
arg_material_one (bpy.types.Material): 比較マテリアル1
arg_material_two (bpy.... | 3,083 |
def run_filters():
"""Runs filters ('PAINS', 'ZINC', 'BRENK', 'NIH')for molecule selected.
Saves the information to the global molecule_info dict and returns the
information as its own dict.
Pass R Group IDs as queries: /filters?r1=A01&r2=B01
:returns: A json dictionary of the molecule, indexed
... | 3,084 |
def read_template(engine, template_name):
"""Read template string from file and get path."""
template_file = get_template_file(engine, template_name)
template_string = template_file.read_text()
return template_string, template_file.parent | 3,085 |
def test_init():
"""Checks the proper imports and initialisation"""
assert True | 3,086 |
def get_qbert_v3_url(qbert_url, project_id):
"""Keystone only hands out a v1 url I need v3."""
qbert_v3_url = "{0}/v3/{1}".format(qbert_url[0:-3], project_id)
return qbert_v3_url | 3,087 |
def gen_all_holds(hand):
"""
Generate all possible choices of dice from hand to hold.
hand: sorted full yahtzee hand
Returns a set of tuples, where each tuple is sorted dice to hold
"""
# start off with the original hand in set
set_holds = set([(hand)])
# now iterate with all... | 3,088 |
def add_features_for_one_doc(features, tokens, segment_ids, input_mask,
masked_lm_positions, masked_lm_labels,
masked_lm_weights, tokenizer, doc_index):
"""Add features for one document in a WikiDocPair example."""
input_ids = tokenizer.convert_tokens_to_ids... | 3,089 |
def events_generators_pool_run(id_):
"""
Periodically activates generators according to generator pool settings.
"""
IOLoop.current().add_callback(_events_generators_pool_run, id_) | 3,090 |
def sndrcv(*args, **kwargs):
# type: (*Any, **Any) -> Tuple[SndRcvList, PacketList]
"""Scapy raw function to send a packet and receive its answer.
WARNING: This is an internal function. Using sr/srp/sr1/srp is
more appropriate in many cases.
"""
sndrcver = SndRcvHandler(*args, **kwargs)
retu... | 3,091 |
def set_project_designer(value: str) -> None:
"""
Args:
value (str): value
""" | 3,092 |
def get_by_name(db_session: Session, *, name: str) -> Optional[Action]:
"""Return action object based on action name.
Arguments:
db_session {Session} -- SQLAlchemy Session object
name {str} -- action name
Returns:
Optional[Action] -- Returns a Action object or nothing if it doesn't... | 3,093 |
def langstring(value: str, language: str = "x-none") -> dict:
"""Langstring."""
return {
"langstring": {
"lang": language,
"#text": value,
}
} | 3,094 |
def chinese_half2full():
"""Convert all halfwidth Chinese characters to fullwidth .
Returns:
"""
def string_op(input_str:str):
rstring = ""
for uchar in input_str:
u_code = ord(uchar)
if u_code == 32:
u_code = 12288
elif 33 <= u_code ... | 3,095 |
def euclidean_distance(p1, p2):
"""
Returns the Euclidean Distance of a particular point from rest of the points in dataset.
"""
distance = 0
for i in range(len(p1)-1):
distance += (p1[i]-p2[i])**(2)
return sqrt(distance) | 3,096 |
def get_arguments():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description="""A simple popup calendar""")
parser.add_argument(
"-p",
"--print",
help="print date to stdout instead of opening a note",
action="store_true",
)
parser.add_argume... | 3,097 |
def default_after_handler(req, resp, resp_validation_error, instance):
"""
default handler called after the response validation
:param req: request provided by the web framework
:param resp: response from the endpoint function (if there is no validation error)
or response validation error
:... | 3,098 |
def img_histogram(file):
"""
Returns an image's histogram in a combined RGB channel and each individual
channel as an array of 256 values.
A 0 means that a tonal value is the max and 255 means there are 0 pixels at that value.
"""
with Image.open(file) as img:
histogram = img.hist... | 3,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.