content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pad_dataset_normal(tokenizer_fn):
"""We will pad the data.
Based on name of the dataset, we will pad it accordingly
Args:
tokenizer_fn ([type]): [A function which returns dict of list of list]
Returns:
[type]: [description]
"""
@wraps(tokenizer_fn)
def pad_fn(*args, **... | 77,200 |
def add_comment(
post: k_models.KookaburraPost, content: str, author: settings.AUTH_USER_MODEL
) -> Optional[k_models.KookaburraComment]:
"""
Add a comment to a post, doing some checks beforehand.
"""
# Check that the post is allowed to comment
if not post.commenting_allowed:
return
... | 77,201 |
def get_profile_name(host, network):
"""
Get the profile name from Docker
A profile is created in Docker for each Network object.
The profile name is a randomly generated string.
:param host: DockerHost object
:param network: Network object
:return: String: profile name
"""
info_raw... | 77,202 |
def S7_parabola(M,S,gamma):
"""
Computes the intial conditions for the disrupting galaxy.
"""
R1 = -55
R2 = 25-(R1**2)/100
vR = np.sqrt((2*gamma*(M+S))/np.linalg.norm([R1,R2]))
if R1 == 0:
vR1,vR2 = vR,0
else:
theta = np.arctan(abs(R1/50))
if R2 > 0:
... | 77,203 |
def on_word_click(index):
"""
Handles the word_click event.
This is fired when a player clicks on a word cell.
"""
# Check that user is not a spymaster
team = current_user.codenames_player.team
# Check game state
room = current_user.room.codenames_room
if not (
(room.state =... | 77,204 |
def test_player_net_worth(test: unittest.TestCase, player: Player, expected: float):
"""Asserts that the net worth of the specified player is the expected value
Parameters
----------
test : unittest.TestCase
the test case to run the test on
player : Player
the player to check the ne... | 77,205 |
def SetGpuClockSpeed(vm, memory_clock_speed, graphics_clock_speed):
"""Sets the memory and graphics clocks to the specified frequency.
Persistence mode is enabled as well. Note that these settings are
lost after reboot.
Args:
vm: virtual machine to operate on
memory_clock_speed: desired speed of the m... | 77,206 |
def reroot_path(root: Union[str, Path], filename: str) -> str:
"""Returns the basename of filename, joined to root."""
return os.path.join(root, os.path.basename(filename)) | 77,207 |
def create_compression_joint(joint, end_parent, description, point_constraint = False):
"""
joint need to be a joint with a child joint. Child joint is automatically found.
"""
end_joint = cmds.listRelatives(joint, c = True, type = 'joint')
parent_transform = cmds.listRelatives(joint, p =... | 77,208 |
def get_simple (ftype, data, alphabet=features.DNA, sparse=False):
"""Return SimpleFeatures.
@param ftype Feature type, e.g. Real, Byte
@param data Train/test data for feature creation
@param alphabet Alphabet for feature creation
@param sparse Is feature sparse?
@return Dict with SimpleFeatures train/test
"""
... | 77,209 |
def checker(func, options=None):
"""Checks for producers methods.
Print:
* Alteration in objects hash.
* Numpy errors.
"""
if options is None:
options = []
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if hasattr(self, 'logger'):
... | 77,210 |
def _absolute_path(repo_root, path):
"""Converts path relative to the repo root into an absolute file path."""
return repo_root + "/" + path | 77,211 |
def run_all():
"""Default function that is called by the runner if nothing else is specified"""
return _make_runner(['test_fails', 'test_skipped', 'test_passes']) | 77,212 |
def psnr(x, y, vmax=-1):
"""
psnr - compute the Peack Signal to Noise Ratio
p = psnr(x,y,vmax);
defined by :
p = 10*log10( vmax^2 / |x-y|^2 )
|x-y|^2 = mean( (x(:)-y(:)).^2 )
if vmax is ommited, then
vmax = max(max(x(:)),max(y(:)))
Copyright (c) 2014 ... | 77,213 |
def srpc(*params, **kparams):
"""Method decorator to tag a method as a remote procedure call. See
:func:`spyne.decorator.rpc` for detailed information.
The initial "s" stands for "static". In Spyne terms, that means no implicit
first argument is passed to the user callable, which really means the
m... | 77,214 |
def get_block_header_munger(module: Any, block_hash: Hash32) -> Tuple[HexStr]:
"""
Normalizes the inputs JSON-RPC endpoints that take a 2-tuple of
`(ContentKey, bytes)`
"""
return (encode_hex(b"\x01" + block_hash),) | 77,215 |
def latlng_to_region(latlng_str):
"""Get region from latlng."""
lat, _, lng = latlng_str.partition(',')
lat_lng = (float)(lat), (float)(lng)
return geodata.get_latlng_regions(lat_lng) | 77,216 |
async def test_flow_import_already_configured(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test an import flow already configured."""
create_entry(hass)
mock_connection(aioclient_mock)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"so... | 77,217 |
def update_node_hpss_outbound(node):
"""Process transfers out of an HPSS tape node."""
log.info("Processing HPSS outbound transfers (%s)" % node.name)
# Fetch requests for transfer onto this node
requests = di.ArchiveFileCopyRequest.select().where(
~di.ArchiveFileCopyRequest.completed,
... | 77,218 |
def plot_sample(sample):
"""Source: https://www.kaggle.com/erelin6613/openvaccine-rna-visualization"""
struct = sample['structure']
seq = sample['sequence']
bg = fgb.BulgeGraph.from_fasta_text(f'>rna1\n{struct}\n{seq}')[0]
plt.figure(figsize=(20,8))
fvm.plot_rna(bg)
plt.title(... | 77,219 |
def truncated_normal(shape, mean=0.0, stddev=1.0, dtype=types.float32,
seed=None, name=None):
"""Outputs random values from a truncated normal distribution.
The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose magnitude is mor... | 77,220 |
def task_pot():
"""Re-create .pot ."""
return {
"actions": ['pybabel extract -F locales/babel-mapping.ini -o jackalify.pot jackalify'],
"file_dep": glob.glob('**/*.py', recursive=True),
"targets": ['jackalify.pot'],
"clean": True,
} | 77,221 |
def env_activate_setup_parser(subparser):
"""set the current environment"""
shells = subparser.add_mutually_exclusive_group()
shells.add_argument(
'--sh', action='store_const', dest='shell', const='sh',
help="print sh commands to activate the environment")
shells.add_argument(
'-... | 77,222 |
def print_summary(results: SimulationStats):
"""Prints a short summary regarding the populations of the simulation."""
for item in [['FOXES', results.foxes],['RABBITS', results.rabbits]]:
animal = item[0]
data = item[1]
print(f"""
[{animal}]
Population
total: {data.total}
min: {min(data.size_pe... | 77,223 |
def set_rigid_link(osi, r_node, c_node, rtype):
"""
Create a multi-point constraint between nodes.
Parameters
----------
r_node: Node
Master node
c_node: Node
Slave node
rtype: str
Either 'bar' or 'beam'
Returns
-------
"""
op_type = 'rigidLink'
... | 77,224 |
def track_timing(collector):
"""Decorator to track statistics on a function's execution time.
Parameters
----------
collector : TimerStatsCollector
"""
def wrap(func):
def timed_(*args, **kwargs):
return _timed_func(collector, func, *args, **kwargs)
return timed_
... | 77,225 |
def GenerateStableDeviceSecret(options):
"""Generates a fresh stable device secret and stores it in the RO VPD."""
GetGooftool(options).GenerateStableDeviceSecret()
event_log.Log('generate_stable_device_secret') | 77,226 |
def UrlsPath()->str:
"""根路由的路径"""
PROJECT_CONFIG = get_configs(CONFIG_PATH)
PROJECT_BASE_DIR = PROJECT_CONFIG['dirname']
return os.path.join(PROJECT_BASE_DIR, PROJECT_CONFIG['project_name'], 'urls.py') | 77,227 |
def aic(L, k):
"""
Akaike information criterion.
:param L: maximized value of the negative log likelihood function
:param k: number of free parameters
:return: AIC
"""
return 2*(k + L) | 77,228 |
def hanging_node_threshold_comparison(pred_tactics, predprob_tactics, pred_techniques, predprob_techniques, known_pred_techniques, permutations):
"""
Using different combinations of thresholds retrieve all the F0.5 score macro-averaged between the
post-processed predictions and the true labels.
"""
f05list = ... | 77,229 |
def build_score_matched_bins(target_scores, full_scores, num_increments=21):
"""build bins
"""
# TODO ideally build intervals for both GC and scores...
# then to build bins, do a nested loop?
# for score interval, for gc interval:
# collect all target that match <- track count as num_target
... | 77,230 |
def identity(x):
"""Return x."""
return x | 77,231 |
def chunkReadPoints(chunk_id=None, chunk_layout=None, chunk_arr=None,
point_arr=None):
"""
Read points from given chunk
"""
log.debug(f"chunkReadPoints - chunk_id: {chunk_id}")
dims = chunk_arr.shape
chunk_coord = getChunkCoordinate(chunk_id, dims)
log.debug(f"chunk_coor... | 77,232 |
def get_columns(invoice_list):
"""return columns based on filters"""
columns = [
_("Company") + ":Company:120",
_("Trans. Group") + ":Data:180",
_("Invoice Type") + ":Data:90",
_("Acct. Head") + ":Data:160",
_("Stock No.") + ":Link/Item:120",
_("Vim Number") + ":Data:150",
_("Details") ... | 77,233 |
def contains_domain(address, domain):
"""Returns True if the email address contains the given domain in the domain position, false if not."""
domain = r'[\w\.-]+@'+domain+'$'
if re.match(domain,address):
return True
return False | 77,234 |
def pycond(cond, *a, **cfg):
""" condition function - for those who don't need meta infos """
return parse_cond(cond, *a, **cfg)[0] | 77,235 |
def list_dir(path):
"""列出某个目录下的文件
:param path: 相对于resources目录的路径,用于查找文件夹
:type path: str
:returns :返回一个包含资源目录下所有文件或者文件下的绝对路径的list
"""
return _current_resmgr_session().list_dir(path) | 77,236 |
def prepare_update_sql(list_columns, list_values, data_code=100):
"""
Creates a string for the update query
:param list_columns: columns that are in need of an update
:param list_values: values where the columns should be updated with
:param data_code: data code to add to the columns
:return: st... | 77,237 |
async def enum_coercer(
result: Any,
info: "ResolveInfo",
execution_context: "ExecutionContext",
field_nodes: List["FieldNode"],
path: "Path",
enum_type: "GraphQLEnumType",
) -> Any:
"""
Computes the value of an enum type.
:param result: resolved value
:param info: information re... | 77,238 |
def db(request):
"""Session-wide test database."""
# create a SQLite DB in memory
_db.engine = create_engine("sqlite://")
# setup models in DB
Base.metadata.create_all(_db.engine)
return _db | 77,239 |
def inference_detector_with_probs(model, img, score_thresh = None):
"""Inference image with the detector.
Args:
model (nn.Module): The loaded detector.
img (str): image file.
Returns:
"""
cfg = model.cfg
cfg.model.test_cfg.rcnn.max_per_img = 50
device = next(model.param... | 77,240 |
def test_ipaddress_getasn(dummy_asndb):
"""Test IPAddress() asn lookup method"""
ipaddr = IPAddress('1.1.1.1', 'Wed Dec 31 16:25:00 2013')
assert ipaddr.get_asn(dummy_asndb) == dummy_asndb.lookup('1.1.1.1')[0] | 77,241 |
def read_test_txt(txt_file):
""" read single-modality txt file
:param txt_file: image list txt file path
:return: a list of image path list, list of image case names
"""
lines = readlines(txt_file)
case_num = int(lines[0])
if len(lines) - 1 != case_num:
raise ValueError('case num do not equal path nu... | 77,242 |
def plot_hist_prop(data, plot_it=False, **histogram_kwargs):
"""Create histogram data (and maybe plot it) which is normalize to be an empirical mass distribution.
:param data: all the relevant solving times that we have observed the mouse take
:type data: list-like
:param plot_it: should this function ... | 77,243 |
def translate(points, x, y, z):
"""Takes a set of coordinates and translates them in three dimensional
space.
The points must be a list (or tuple, or any collection really) of
coordinates in the form ``(x, y, z)``, *or* a list (etc.) of objects with
x(), y() and z() methods.
An example would b... | 77,244 |
def read_rttm_lines(rttm_file_path):
"""
Read rttm files and return the rttm information lines.
Args:
rttm_file_path (str):
Returns:
lines (list):
List containing the strings from the RTTM file.
"""
if rttm_file_path and os.path.exists(rttm_file_path):
f = o... | 77,245 |
def check_connected_balanced(graph):
"""
:type graph: nx.DiGraph
"""
for v in graph.nodes():
assert graph.in_degree(v) == graph.out_degree(v)
sub_graph_list = nx.weakly_connected_component_subgraphs(graph, True)
for sub_graph in sub_graph_list:
print 'connected component:', sub_g... | 77,246 |
def tversky_index(y_true, y_pred, smooth = 1, alpha = 0.7):
"""
Links
1. https://arxiv.org/pdf/1810.07842.pdf
"""
y_true, y_pred = y_cast(y_true, y_pred)
tp = reduce_sum(y_true * y_pred)
fn = reduce_sum(y_true * (1 - y_pred))
fp = reduce_sum((1 - y_true) * y_pred)
return reduce... | 77,247 |
def setup_logging(verbosity: Optional[int]=None,
logger_id: Optional[str]=None) -> None:
"""
Set verbosity of internal and relevant external loggers.
If no logger_id is provided, the verbosity is applied to the root logger.
"""
logging.addLevelName(logging.DEBUG, "DEBUG")
lo... | 77,248 |
def run_logged_redirect_command(cmd,
out,
log_file,
cmd_file=None,
dry_run=False):
"""
Run operating system command via Python ``subprocess`` and
redirect output to a file and capt... | 77,249 |
def iter_tar(arch_f, stream=False):
"""Iter over tar archive, yielding (path, object-like) tuples.
Args:
arch_f: File object of the archive to iterate.
stream: If True, open the archive in stream mode which allows for faster
processing and less temporary disk consumption, but random access to the
... | 77,250 |
def resnet51q(pretrained=False, **kwargs):
"""
"""
return _create_byobnet('resnet51q', pretrained=pretrained, **kwargs) | 77,251 |
def _feature_correlation_num(X, y, feature, n_bins=-1, return_prob=False, model=None):
"""Calculate proportion of true label and distribution predicted probability for a numerical feature using binning
"""
bin_avg = []
probs = []
# Calculating average prob requires model
if return_prob and mode... | 77,252 |
async def list_logs(
hub, ctx, name, container_group, resource_group, tail=None, **kwargs
):
"""
.. versionadded:: 3.0.0
Get the logs for a specified container instance in a specified resource group and container group.
:param name: The name of the container instance.
:param container_group: ... | 77,253 |
def en(s):
"""Returns `s` as an English location string."""
return owlready2.locstr(s, lang='en') | 77,254 |
def davidsonliu_fqe(
hmat: Hamiltonian,
nroots: int,
guess_vecs,
nele,
sz,
norb,
epsilon: float = 1.0e-8,
verbose=False,
):
"""TODO: Add docstring."""
if nroots < 1 or nroots > 2**(hmat.dim() - 1):
raise ValueError("Number of roots is incor... | 77,255 |
def test_validator_from_absolutized(tmp_path, monkeypatch):
"""'from' param: check it's made absolute."""
# change dir to the temp one, where we will have the 'dir1/dir2' tree
dir1 = tmp_path / 'dir1'
dir1.mkdir()
dir2 = dir1 / 'dir2'
dir2.mkdir()
monkeypatch.chdir(tmp_path)
dir2 = path... | 77,256 |
def generate_log_filename() -> str:
"""Generates log filename using time.
Returns:
str: log filename with time.
"""
filename = generate_filename('log-{}.pickle')
return os.path.join(MODELS_DIR, filename) | 77,257 |
def onBoard(top, left=0):
"""Simplifies a lot of logic to tell if the coords are within the board"""
return 0 <= top <= 9 and 0 <= left <= 9 | 77,258 |
def _checkforbidden(l):
"""Check filenames for illegal characters."""
for f in l:
if b'\n' in f or b'\r' in f:
raise error.StorageError(
_(b"'\\n' and '\\r' disallowed in filenames: %r")
% pycompat.bytestr(f)
) | 77,259 |
def guess_first_nonoption(gparser, subcmds_map):
"""Given a global options parser, try to guess the first non-option without
generating an exception. This is used for scripts that implement a
subcommand syntax, so that we can generate the appropriate completions for
the subcommand."""
import copy
... | 77,260 |
def _plot_enn_samples_2d(sample_df: pd.DataFrame,
train_df: pd.DataFrame) -> gg.ggplot:
"""Plot realizations of enn samples."""
p = (gg.ggplot(sample_df)
+ gg.aes(x='x0', y='x1', fill='y')
+ gg.geom_tile()
+ gg.geom_point(data=train_df, size=3, stroke=1.5)
+ gg.s... | 77,261 |
def visit_btn_node_latex(self, node):
"""
create the latex output
:param node: the btn node
"""
# create the macro to display the btn in the latex document
# install 2 packages tcolorbox and fontawesome5
# create a sphinxbtn command
macro = (
"\\usepackage{fontawesome5}\n"
... | 77,262 |
def square2vec(rdm):
"""map 2D distance matrix to [n,1] vector of unique distances. Returns distances in
same order as scipy.spatial.distance.squareform."""
return rdm[np.triu_indices_from(rdm, k=1)][:, None] | 77,263 |
def parse_date_string(dt_string, alexa=False):
"""Parse the date string from the database into a `datetime` object.
:param date_string: the raw date string to parse
:returns: the `datetime` version of the given date string
"""
if(alexa):
return datetime.datetime.strptime(dt_string, ALEXA_TI... | 77,264 |
def run_for_verb(verb, w=None):
"""
Run queries for a verb.
Args:
verb (str): Verb to run queries for.
w (DBWrapper, optional): Default is None, in which case one is loaded
from the cache. If w is provided, it should have the caches loaded
already.
"""
print ... | 77,265 |
def _get_filepath(
dataset_name: str, dir_path: Union[None, str], filename: str
) -> Union[str, ContextManager[Path]]:
"""
Returns the path to a decay dataset file (located either within a sub-package of
``radioactivedecay`` or within a local system directory).
Parameters
----------
dataset... | 77,266 |
def get_frequent_queries(**kwargs):
"""
Gets the most frequent queries
Kwargs:
db: global database instance
redis: global redis instance
"""
db = kwargs["db"]
with db.scoped_session() as session:
q = sqlalchemy.text(
"SELECT query, calls FROM pg_stat_statemen... | 77,267 |
def Bellman_exp_inplace_prt(Qsa, S, action, action_list, ff=0.9, N_A=9, N_Symbols=3, disp_flag=False):
"""Evaluate q(s,a) using ``S`` and ``action``.
Returns q(s,a).
Parameters
----------
S : numpy.ndarray, shape=(N_A,)
State matrix <--> state index, ``S_Idx``
action : int
... | 77,268 |
def add_stream(logger, fh_name, stream=None, level=None, nostderr=False,
syslog_format=False, prefix=False, use_color=False):
"""Set up stream (stdout and stderr) logging"""
if stream is None:
stream = sys.stderr
handle = logging.StreamHandler(stream)
if syslog_format:
... | 77,269 |
def beh_idx_to_2p_idx(beh_indices, cam_line, frame_counter):
"""
This functions converts behaviour frame numbers into the corresponding
2p frame numbers.
Parameters
----------
beh_indices : numpy array
Indices of the behaviour frames to be converted.
cam_line : numpy array
P... | 77,270 |
def num2julian(num):
"""
Convert a Julian days to a matplotlib date.
Parameters
----------
num : numpy.ndarray : int32
Number of days since 0001-01-01 00:00:00 UTC *plus* *one*.
Returns
-------
jd : numpy.ndarray : int32
Julian days.
"""
return num + 1721424.5 | 77,271 |
def get_logger(module_name: str) -> logging.Logger:
"""
Gets a namespaced logger based on the project name and module name
"""
if "" == LOGGING_PROJECT_NAME:
return get_fqn_logger(module_name)
return get_fqn_logger("{}.{}".format(
LOGGING_PROJECT_NAME,
module_name
)) | 77,272 |
async def test_verisure_no_ethernet_status(hass):
"""Test no data from API."""
await setup_verisure(hass, CONFIG, {})
assert len(hass.states.async_all()) == 1
entity_id = hass.states.async_entity_ids()[0]
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE | 77,273 |
def crop_and_resize_instance_masks(masks, boxes, mask_size):
"""Crop and resize each mask according to the given boxes.
Args:
masks: A [N, H, W] float tensor.
boxes: A [N, 4] float tensor of normalized boxes.
mask_size: int, the size of the output masks.
Returns:
masks: A [N, mask_size, mask_siz... | 77,274 |
def compute_source_flags(tod=None, P=None, mask=None, wrap=None,
center_on=None, res=None):
"""Process masking instructions and create RangesMatrix that flags
samples in the TOD that are within the masked region. This
masking makes use of a map with the footprint encoded in P, so
... | 77,275 |
def main(m1=1.4, m2=0.3, r1=10, a0=100, eta=110, rel="off",
max_time=1, out1_path=out1_path_default, out2_path=out2_path_default):
"""
Main function
Final evolution of close neutron star binary, stripping model
input variables:
m1(float): mass of neutron star (NS) in M_solar
m2(float): mass of... | 77,276 |
def _split(df, keepvars, force_numeric=False):
"""
Splits a dataframe into a list of arrays based on a key variable. Pass keepvars
to keep variables other than the key variable
"""
# df = df.sort_values('__key_var__') #now done outside of function
small_df = df[['__key_var__'] + keepvars]
ar... | 77,277 |
def pmg_serialize(method):
"""
Decorator for methods that add MSON serializations keys
to the dictionary. See documentation of MSON for more details
"""
@functools.wraps(method)
def wrapper(*args, **kwargs):
self = args[0]
d = method(*args, **kwargs)
# Add @module and @c... | 77,278 |
def test__from_string():
""" test vmat.from_string
"""
vma = vmat.from_string(CH4O_VMA_STR)
assert vma == CH4O_VMA | 77,279 |
def test_write_network_single_title(view):
""" Test the _write_network_single_title method. """
# set context (meant to be set through render)
view.view_ctx = Mock(**{'format_url.return_value': 'http://addr:port/index.html'})
# replace root structure
mocked_href_mid = Mock(attrib={})
mocked_titl... | 77,280 |
def variable_set_choices(name,values):
"""Set all possible values for a data collection parameter
values: list of values"""
options.variable_choices[name] = values | 77,281 |
def normalize_dataframes(grouped_df, year):
""" Takes a dataframe which has been grouped by phrase and aggregated, and normalizes the
total_occurrences and total_docs columns by dividing them by the total no. of phrases or total no. of
docs in the relevant year and multiplying by 100 to create percentages.
... | 77,282 |
async def setup_file(config_file, cmd_args):
"""Set up control center from config file and command line args.
Parameters
----------
config_file : str
The path to the configuration YAML file.
cmd_args : dict
The dict with the command line arguments.
Returns
-------
Cente... | 77,283 |
def egd_get_user_lang(user=None) -> str:
"""If user logged use gessed language on session beginning or resumption"""
if is_app_for_actual_site():
return frappe.local.lang
else:
return frappe_get_user_lang(user) | 77,284 |
def oldest_youngest():
"""Get JSON Data.
Compile a dictionary of all billionaires' names and ages.
Find the oldest billionaire under 80, and youngest living billionaire."""
data = get_json()
age_dict = {}
for item in data['billionaires']:
if item['age'] >= 80 or item['age'] < 0:
... | 77,285 |
def read_narr_mask(pickle_file_name):
"""Reads NARR mask from Pickle file.
:param pickle_file_name: Path to input file.
:return: mask_matrix: See doc for `check_narr_mask`.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
mask_matrix = pickle.load(pickle_file_handle)
pickle_file_handl... | 77,286 |
def get_imported(context: dict) -> Dict[str, Optional[version_types]]:
"""Create list of imported modules in given context.
Only outputs modules from given context that have
conventional version attributes.
Context is typically globals() or locals().
"""
visited = dict()
def _proc... | 77,287 |
def mpi_reduce(x: np.ndarray, op: Callable) -> np.ndarray:
"""Apply reduce operation over MPI processes."""
buffer = np.zeros_like(x)
MPI.COMM_WORLD.Allreduce(x, buffer, op=op)
return buffer | 77,288 |
def extract_columns_from_table_definition_file(xmltag, table_definition_file):
"""
Extract all columns mentioned in the result tag of a table definition file.
"""
def handle_path(path):
"""Convert path from a path relative to table-definition file."""
if not path or path.startswith("htt... | 77,289 |
def _object_type_getattr(obj, name):
"""Looks up the named attribute on the object's type, resolving descriptors.
Behaves like _PyObject_LookupSpecial."""
_builtin() | 77,290 |
async def calibrate(fps_maker, positioner_id, motors, datums, cogging):
"""Runs a full calibration on a positioner."""
fps_maker.initialise = False
fps_maker.danger = True
async with fps_maker as fps:
await fps.initialise(start_pollers=False)
await calibrate_positioner(
fps... | 77,291 |
def get_det_bbox_with_cls_of_img(all_boxes, img_idx):
"""get_det_bbox_with_cls_of_img
:param all_boxes: det result
:param img_idx: img idx in imageset.txt
:return bboxes: N*6-dim matrix, N is number of bbox, 6 is [x1,y1,x2,y2,score,cls], the cls is the addtion information we get from this function
... | 77,292 |
def _multiply_calculate(a, b): # pragma: no cover
"""
a in GF(2^m), can be represented as a degree m-1 polynomial in GF(2)[x]
b in GF(2^m), can be represented as a degree m-1 polynomial in GF(2)[x]
p(x) in GF(2)[x] with degree m is the primitive polynomial of GF(2^m)
a * b = c
= (a(x) * ... | 77,293 |
def hugoniot_rho(p, rho0, c0, s, min_strain=0.01):
"""
calculate density in g/cm^3 from a hugoniot curve
:param p: pressure in GPa
:param rho0: density at 1 bar in g/cm^3
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param min_strain: defining minimum v/v0 val... | 77,294 |
def scan_with_arp():
"""Komut satırından veriyi çeker. Hızlı yöntemdir. Sadece Linux'da çalışır.
:return: dict --> { "MAC":"IP", "MAC":"IP",. .. }
"""
if platform not in ["linux", "linux2"]:
rapor.warning(scan_with_arp.__name__, "Stopped: This method tested only on Linux")
return {}
... | 77,295 |
def no_pipegraph(request):
"""No pipegraph, but seperate directory per test"""
if request.cls is None:
target_path = Path(request.fspath).parent / "run" / ("." + request.node.name)
else:
target_path = (
Path(request.fspath).parent
/ "run"
/ (request.cls.__... | 77,296 |
def name( path ):
"""Extracts the resource name."""
return path[1+path.rfind('/'):] | 77,297 |
def set_subscriber_name_loop(context: X12ParserContext, segment_data: Dict) -> None:
"""
Sets the Subscriber Name Loop
:param context: The X12Parsing context which contains the current loop and transaction record.
:param segment_data: The current segment data
"""
if context.loop_name == Transac... | 77,298 |
def report_dfa(q_0, dfa, g):
"""
Give a complete description of the DFA as a string
"""
output = ""
output += "----------- DFA ----------- " + "Goal: " + g + " ----------- \n"
transitions = [(i,dfa[(i,sigma)],sigma) for i,sigma in dfa]
transitions.sort()
for i,j,sigma in transitions:
output += (f"delta({i},{s... | 77,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.