content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cell_test(U,count,max_kpd_=None):
"""Tests the ability of the niggli basis to preserve the symmetry of
the parent cell under action of the HNF.
Args:
U (numpy array): The parent lattice as columns of vector.
count (dict): A dictionary to count how many times each niggli
cel... | 54,600 |
def declare_attackers(game):
"""
Perform the :ref:`declare-attackers-step`.
"""
game.events.trigger(
event=events.STEP_BEGAN, phase="combat",
step="declare attackers", player=game.turn.active_player
)
possible_attackers = {c for c in game.battlefield if c.can_attack}
targ... | 54,601 |
def get_engine(path: str) -> create_engine:
"""
Function for connecting to the database-file
:param path: path to the file
:return: sqlmodel's engine
"""
return create_engine(path, echo=False) | 54,602 |
def mri_signal_inversion_recovery_function(input_data: dict) -> np.ndarray:
""" Function that calculates the inversion recovery signal """
t1: np.ndarray = input_data["t1"].image
t2: np.ndarray = input_data["t2"].image
m0: np.ndarray = input_data["m0"].image
mag_enc: np.ndarray = input_data["mag_en... | 54,603 |
def replace_in_files(files_map: Mapping[str, str], replace_map: Mapping[str, str]):
"""
Replaces a series of matches in a collection of files
Args:
file_paths (dict): A dictionary where the key is the file source and the value is a file target.
If the target is set to an empty string, t... | 54,604 |
def moveZeroes(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
count = i = 0
while count < length:
if nums[i] != 0:
i += 1
else:
nums.pop(i)
nums.append(0)
c... | 54,605 |
def test_datarouter_basic(agent, output):
"""Test data router."""
# router with only default output.
agent.register_plugin("test", output)
router = agent.router
router.emit("test", time.time(), {"k": "v"})
agent.flush()
assert len(output.bulks) == 1 | 54,606 |
def clip_grads(grad_tree, max_norm):
"""Clip gradients stored as a pytree of arrays to maximum norm `max_norm`."""
norm = l2_norm(grad_tree)
normalize = lambda g: np.where(norm < max_norm, g, g * (max_norm / norm))
return layers.nested_map(grad_tree, normalize) | 54,607 |
def get_all_facility_users(admin: Client, facility_id: int) -> dict: # noqa: unused client
"""Query for users related to the given facility."""
disallow_parameters(request)
return {
'user': [
user.to_json()
for user in Facility.from_id(facility_id).users()
]
} | 54,608 |
def test_in_operator_expression_numerical(forest_fires):
"""
Test using in operator in a sql query
:return:
"""
my_table = query(
"""
select * from forest_fires where X in (5, 9)
"""
)
ibis_table = forest_fires[forest_fires.X.isin((ibis.literal(5), ibis.literal(9)))]
asse... | 54,609 |
def setup_platform(
hass, config, add_entities, discovery_info):
"""Set up Huawei LTE sensor devices."""
data = hass.data[DATA_KEY].get_data(config)
sensors = []
for path in config.get(CONF_MONITORED_CONDITIONS):
data.subscribe(path)
sensors.append(HuaweiLteSensor(data, path, SEN... | 54,610 |
def rpkm(count, length, nb_read):
""" Return the rpkm value """
length /= 10**3
return rpm(count, length, nb_read) / length | 54,611 |
def center(self):
"""Centers the window
Keyword arguments:
self -- main window being displayed i.e. the current instance of the mainWindow class
Returns:
None
With information from the user's desktop, the screen resolution is gotten
and the center point is figured out... | 54,612 |
def cleanup_password_reset_tokens():
""" Remove expired tokens """
cutoff = now() - timedelta(seconds=PASSWORD_RESET_TOKEN_EXPIRATION)
PasswordResetToken.objects.filter(created__lt=cutoff).delete() | 54,613 |
def usm_make(sequence, A=None, seed='centroid'):
"""
Calculates USM coordinates of a categorical sequence of arbitrary alphabet size.
Parameters
----------
sequence : LIST OR ARRAY TYPE;
CATEGORICAL SEQUENCE OF DATA
d : LIST, optional;
LIST CONTAINING ALL POSSIBLE SYMBO... | 54,614 |
def single_dataset_variableselect(c=cmdc.Client()):
"""
This example loads a subset of the demographic data by selecting
a few variables and a few fips codes
"""
c.demographics(
variable=[
"Total population",
"Fraction of population over 65",
"Median age",... | 54,615 |
def validate_min_python_version(major, minor, error_msg=None, exit_on_fail=True):
"""If python version does not match AT LEAST requested values, will throw non 0 exit code."""
version = sys.version_info
result = False
if version.major > major:
return True
if major == version.major:
r... | 54,616 |
def _get_total_sizes(graph_tensor: gt.GraphTensor) -> SizeConstraints:
"""Returns the total number of items in the `graph_tensor`."""
return SizeConstraints(
total_num_components=graph_tensor.total_num_components,
total_num_nodes={
name: node_set.total_size
for name, node_set in grap... | 54,617 |
def _lookup_credentials_data_workspace_access(access_key_id):
"""
Raises HawkFail if the access key ID is not of Data workspace
"""
if access_key_id != settings.HAWK_LITE_DATA_WORKSPACE_CREDENTIALS:
raise HawkFail(f"Incorrect Hawk ID ({access_key_id}) for Data workspace")
return _lookup_cre... | 54,618 |
def get_arg_parser():
"""Allows arguments to be passed into this program through the terminal.
Returns:
argparse.Namespace: Object containing selected options
"""
def dir_path(string):
if os.path.isfile(string):
return string
else:
raise NotADirectoryErro... | 54,619 |
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making final data set from raw data')
# SAR call data pre-processi... | 54,620 |
def generate_2d_data(func, size=100, data_range=(-2., 2.),
validation=False, visualize=False, seed=100):
"""Generates 2d data according to function.
Args:
func: (function) function that takes (x, y) and return a scalar
size: (int) size of training sample to generate
... | 54,621 |
def sphere_line_intercept(l, o, r):
"""Calculate intercept point between line y = l.x + o
and a sphere around the center of origin of the
coordinate system: c=0
Parameters:
------------
l ... vector of line of sight
o ... observer position
r ... vector of dis... | 54,622 |
def mesh_extrude(structure, guid, layers, thickness, mesh_name='', links_name='', blocks_name='', points_name='',
plot_mesh=False, plot_links=False, plot_blocks=False, plot_points=False):
"""
Extrudes a Rhino mesh and adds/creates elements.
Parameters
----------
structure : obj
... | 54,623 |
def compress_pulses(schedules: List[Schedule]) -> List[Schedule]:
"""Optimization pass to replace identical pulses.
Args:
schedules: Schedules to compress.
Returns:
Compressed schedules.
"""
existing_pulses = []
new_schedules = []
for schedule in schedules:
new_sc... | 54,624 |
def get_localhost_info() -> dict:
"""Get information about the specifications of localhost.
Returns:
dict: Current dict keys: 'os', 'cpu_cores', 'memory', 'python_version', 'workspace_version', 'gpus'.
"""
info = {
"os": _get_os_on_localhost(),
"cpu_cores": _get_cpu_count_on_loc... | 54,625 |
def locations(db, instance_path):
"""File system location."""
default = Location(
name='default',
uri=instance_path,
default=True
)
archive = Location(
name='archive',
uri=os.path.join(instance_path, 'archive'),
default=False
)
db.session.add(defau... | 54,626 |
def load(ckpt: int, exp_name: str) -> BaseModel:
"""Load pre-trained language model instance by checkpoint and experiment name.
Load pre-trained language model from path ``project_root/exp/exp_name``.
Parameters
----------
ckpt: int
Saving checkpoint number. Set to ``-1`` to load the last checkpoint.
... | 54,627 |
def _castep_scrape_phonon_frequencies(flines, castep):
""" Iterate through flines to scrape the phonon frequencies
from this CASTEP calculation. Will only scrape the *final* set
of frequencies in the CASTEP file, ignoring any others.
"""
phonons = {}
phonons['phonon_fine_kpoint_list'] = []
... | 54,628 |
def check_cluster_ready(params: str = None, max_seconds: int = 60, interval: int = 5):
"""
Wait that elasticsearch cluster is connected and ready
"""
# override default connection
if params:
connections.set("default", json.loads(params))
for i in range(0, max_seconds, interval):
... | 54,629 |
def predictions(logits):
"""Class prediction from logits."""
inner_dim = logits.get_shape().as_list()[-1]
with tf.name_scope('predictions'):
# For binary classification
if inner_dim == 1:
pred = tf.cast(tf.greater(tf.squeeze(logits, -1), 0.), tf.int64)
# For multi-class classification
else:
... | 54,630 |
def clean_string_dots(str_to_clean=None):
"""
this function try to clean a string like "Media. . . . . . . . . . . "
it will eliminate all the dots and blanck spaces
:param str_to_clean: <string>
:return: <string>
"""
if str_to_clean is None:
raise("Error, We need a string... | 54,631 |
def raw_cli():
"""Raw Accretion commands. Not recommended for direct use.""" | 54,632 |
def delete_multiple( request ):
"""
Delete multiple posts.
Variables required in the POST request:
- api_key : User identifier.
- id[] : A list with the posts identifiers.
"""
posts = _get_post_list( request )
if isinstance( posts, HttpResponse ):
ret... | 54,633 |
def current_umask() -> int:
"""Get the current umask which involves having to set it temporarily."""
mask = os.umask(0)
os.umask(mask)
return mask | 54,634 |
def get_seresnext(blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
root=os.path.join('~', '.keras', 'models'),
**kwargs):
"""
Create SE-ResNeXt model with specific parameters.
... | 54,635 |
def plot_round(logs):
"""
Plot round growth
"""
dfs = {k : v.round for k,v in logs.items() if not v.round.empty}
#
fig,ax = figure_with_legend()
plt.title("Round vs T")
plt.grid()
plt.xlabel("Time")
plt.ylabel("Round")
for k,v in dfs.items():
plt.plot(v['at'], v['R'],... | 54,636 |
def r_example(y0=None, ymax=None, xi=0.01):
"""https://rdrr.io/rforge/bvpSolve/f/inst/doc/bvpTests.pdf"""
L = np.eye(1, 2)
R = np.eye(1, 2)
y0 = np.array([1.0]) if y0 is None else y0
ymax = np.array([1.5]) if ymax is None else ymax
t0 = 0.0
tmax = 1.0
return BoundaryValueProblem(
... | 54,637 |
def get_languages() -> dict[str, str]:
"""
This method is used to get all the languages available
for translation with googletrans
:return: dict of languages
"""
return LANGUAGES | 54,638 |
def train(sound_dir, noise_dir=None, neural_network=None, n_files=None, val_split=0.15, ext='mp4',
**train_kwargs):
"""
Train model using a simpler pipeline that is mostly automated for the user.
The user simply has to point to the directory with pure sound videos and directory
with noise-cont... | 54,639 |
def _numeric_logic_check(self, mag, expr):
"""
If this node is a Compare or BoolOp node, sees if the logic in expr (a javascript string being a logical
statement) matches the logic of self. This assumes that we are only comparing numerical values to a single
variable
TODO: modify this to take multi... | 54,640 |
def publish(obj,eventkey):
"""publish a """
obj['endpoint'] = f"racelog.public.live.state.{eventkey}"
runner = ApplicationRunner(url=obj['url'], realm=obj['realm'], extra=obj)
runner.run(PublishState) | 54,641 |
def get_random(building_list: List[str]) -> Tuple[str, str]:
"""
Get 2 random element from the given list.
Parameters
----------
building_list: List[str]
A list containing all the remaining building that haven't been placed by the user.
Returns
... | 54,642 |
def build_basetools(cmd=''):
"""build the C-Lang executable binaries in BaseTools."""
if cmd[:2] == ['build', 'clean']:
return 0
home_dir = os.environ['EDK_TOOLS_PATH']
cmds = [UDKBUILD_MAKETOOL]
if UDKBUILD_MAKETOOL == 'make':
cmds += [
'--jobs', '%d' % multiprocessing.... | 54,643 |
def mass_kernel(data: np.ndarray, ct: str, num_cells: int, is_affine: bool, block_size: int, num_dofs_per_cell: int,
num_dofs_x: int, x_dofs: np.ndarray, x: np.ndarray, gdim: int, tdim: int,
q_p: np.ndarray, q_w: np.ndarray, c_tab: np.ndarray, phi: np.ndarray,
e_transform... | 54,644 |
def cmd_gather(cmd: Union[str, List], set_env: Optional[Dict[str, str]] = None, realtime=False, strip=False, log_stdout=False, log_stderr=True) -> Tuple[int, str, str]:
"""
Runs a command and returns rc,stdout,stderr as a tuple.
If called while the `Dir` context manager is in effect, guarantees that the
... | 54,645 |
def forward_request(req_data: bytes, req_addr: Tuple[str, int],
endpoint: Tuple[str, int]):
"""Forwards a request to a search endpoint keeping the requester's source
IP and source port"""
log.info("Sending from %s to %s", repr(req_addr), repr(endpoint))
pkt = IP(src=req_addr[0],
... | 54,646 |
def perturb_explanation(image='images/flute.jpg',
arch='alexnet',
layer='input',
perturbation='blur',
perturbation_dimension='spatial',
interpolate=False,
num_perturbations=-1,... | 54,647 |
def exec_cmd(argv):
"""
Execute the command with some arguments
"""
print("Executing %s" % " ".join(argv))
output_str = tokiotest.run_bin(tokio.cli.summarize_tts, argv)
assert len(output_str) > 0
if 'json' in ''.join(argv):
output_json = json.loads(output_str)
verify_json(o... | 54,648 |
def convert_vgg(model, ucf_weights):
"""
Converts VGG MatConvNet model to keras
"""
ucf_w_count = 0 # bottom_layer_count = 35 # Number of keras layers until the top (fc layers) is reached, in vgg16 its 35
for layer in model.layers:
config = layer.get_config()
name = config['name']
... | 54,649 |
def average_over_transforms(func, geometric_transforms, state):
"""Average a function over transformations to achive rotation invariance."""
result_list = collections.defaultdict(list)
for transform in geometric_transforms:
output = transform.inverse(func(transform.forward(state)))
for k, v in output.ite... | 54,650 |
def test_tabulation(capsys):
"""Test the tabulation."""
td = TextDirectory(directory='textdirectory/data/testdata/')
td.load_files(True, 'txt')
td.print_aggregation()
out, err = capsys.readouterr()
assert 'path' in out | 54,651 |
def translate_reweight_dict(reweight_dict: Dict) -> Dict:
"""
Checks a dict assigning desired weight changes in the matrix and if needed translates the
exterrnal db xrefs to internal db ids
:param reweight_dict: dict of instructions to re-assign weights
:return: reweigt_dict translated into interna... | 54,652 |
def update_aliens(ai_settings,stats,screen,ship,bullets,aliens,sb):
"""Verifies if the fleet reached one edge and updates the positions of all
aliens in the fleet"""
check_fleet_edges(ai_settings,aliens)
aliens.update()
#Verifies if there is a colision between aliens and spaceship
if py... | 54,653 |
def encode_json(struct):
"""Encode a structure as JSON bytes."""
return bytes(json.dumps(struct), "utf-8") | 54,654 |
def test_wf_ndst_1(plugin):
""" workflow with one task, a splitter on the task level"""
wf = Workflow(name="wf_spl_1", input_spec=["x"])
wf.add(add2(name="add2", x=wf.lzin.x).split("x"))
wf.inputs.x = [1, 2]
wf.set_output([("out", wf.add2.lzout.out)])
wf.plugin = plugin
checksum_before = wf... | 54,655 |
def test_ipv6_string():
"""Test IPv6 string representation"""
assert str(IPv6()) == '0:0:0:0:0:0:0:1'
assert str(IPv6('2606:4700:4700::1111')) == '2606:4700:4700::1111'
assert str(IPv6('2606:4700:4700::1111', 80)) == '[2606:4700:4700::1111]:80'
assert str(IPv6('[2606:4700:4700::1111]:80')) == '[260... | 54,656 |
def categories_to_errors_dict():
"""Categories to error dictionary function maps common error substrings to categories.
The categories are keys in the dictionary and the values are arrays of strings
or arrays of list.
Some error categories, such as User Errors, has many subcategories. Thus,
... | 54,657 |
def extract_comments(filename, mime=None):
"""Extracts and returns the comments from the given source file.
Args:
filename: String name of the file to extract comments from.
mime: Optional MIME type for file (str). Note some MIME types accepted
don't comply with RFC2045. If not give... | 54,658 |
def cov(arr : np.ndarray):
"""Compute the sample covariance matrix for
a matrix arr, assumed to be given in (samples x features)
form for data fitting applications.
Parameters
----------
arr : np.ndarray
matrix in (samples x features) form
"""
n, _ = arr.shape
return... | 54,659 |
def test_use_base_exception(
assert_errors,
parse_ast_tree,
code,
default_options,
):
"""Testing that `except ValueError or TypeError:` is restricted."""
tree = parse_ast_tree(code)
visitor = WrongExceptHandlerVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor,... | 54,660 |
def insert_tables(cur, conn):
"""
- Specifies fields to be loaded with data from 'staging_events' and 'staging_songs' tables
- Filters out records from 'staging_events' table by NextSong to eliminate invalid song plays
- Inserts records into fact and dimension tables
"""
for query in insert_tabl... | 54,661 |
def tern_plot_branch_lines(tax):
"""
Plot line of random assignment of nodes to branches to a branch ternary tax.
Line positions taken from NetworkGT open source code.
Credit to:
https://github.com/BjornNyberg/NetworkGT
:param tax: Ternary axis to plot to
:type tax: ternary.TernaryAxesSubp... | 54,662 |
def is_rdn_equal(rdn1, rdn2):
"""Returns True if and only if the RDNs are equal.
* RDNs must have the same number of AVAs.
* Each AVA of the RDNs must be the equal for the same attribute type. The
order isn't significant. Note that an attribute type will only be in one
AVA in an RDN, otherwise ... | 54,663 |
def _host_user_uid(zz, ret):
"""Ensure host_user's uid is what we expect.
Fedora:23 Vagrant image has user vagrant 1001, which is a
change from previous releases (1000) so we have to change
the uid/gid to keep it consistent. This operation can't
be executed with salt-call, because you'll be logged ... | 54,664 |
def cub_inat2018(root, config):
"""This meta-task is the concatenation of CUB-200 (first 25 tasks) and iNat (last 207 tasks).
- The first 10 tasks are classification of the animal species inside one of 10 orders of birds in CUB-200
(considering all orders except passeriformes).
- The next 15 tasks ... | 54,665 |
def load_wlist(datadir_path:str):
"""Given the path of the directory containing the simulation files,
load the kernel-integrals file aka "w_list.txt" and return a dataframe"""
print("finished loading kernel-integrals file.")
return pd.read_csv(os.path.join(datadir_path,"w_list.txt"), header=None, dtype... | 54,666 |
def EMetaclass(cls):
"""Class decorator for creating PyEcore metaclass."""
superclass = cls.__bases__
if not issubclass(cls, EObject):
sclasslist = list(superclass)
if object in superclass:
index = sclasslist.index(object)
sclasslist.insert(index, EObject)
... | 54,667 |
def _first_defined(*args):
"""Return the first non-null argument (PRIVATE)."""
for arg in args:
if arg is not None:
return arg
return None | 54,668 |
def register():
"""Let DeepOBS and BackOBS know about the existence of the toy problem."""
# DeepOBS
deepobs.pytorch.testproblems.scalar_deep = scalar_deep
# for CockpitPlotter
if "scalar" in deepobs.config.DATA_SET_NAMING.keys():
assert deepobs.config.DATA_SET_NAMING["scalar"] == "Scalar"
... | 54,669 |
def max_min(vetor, minimo, maximo, indice):
"""
Imprime os valores máximo e mínimo de um vetor
"""
if vetor[indice] < minimo:
minimo = vetor[indice]
if vetor[indice] > maximo:
maximo = vetor[indice]
if indice < len(vetor) - 1:
max_min(vetor, minimo, maximo, indice + 1)
... | 54,670 |
def get_token(yamlName = "token.yaml"):
"""
从token.yaml读取token值
:param yamlName: 配置文件名称
:return: token值
"""
path = os.path.join(current_path, yamlName)
file = open(path)
text_read = file.read()
t = yaml.load(text_read)
file.close()
return t | 54,671 |
def rhyme_analyser(str, rhyme_db):
"""
Rhyme Analyzer - Print out the rhyme scheme of a poem.
Given: A string - like
If you want to smell a rose
You must put it to your nose.
If you want to eat some bread
You must not eat it in bed
Or I will eat your toes.
Output: Rhyme scheme of the... | 54,672 |
async def main(url: str) -> None:
"""GET some data"""
obj = await get_json(url)
print(obj) | 54,673 |
def show_log() -> list:
"""
Отоброжает содержимое log_tab.
:return: список кортежей со всеми данными из таблицы.
"""
try:
with DatabaseConnection(app.config['log_db_config']) as cursor:
_SQL = """SELECT * FROM log_tab ORDER BY ts DESC LIMIT 1000;"""
cursor.execute(... | 54,674 |
def gate_neighbours(current, grid, path):
"""
Generate a heatmap for gates so that A star can avoid gates. This consists of all direct neighbours,
diagonal neighbours, and every coordinate straight above the gate in question
"""
neighbours = list()
# Generate all other coordinates around the ... | 54,675 |
def prevent_duplicate_commits(oldrev, newrev, refname):
"""Pre-receive hook to check for duplicate SVN commits."""
try:
commit_list = subprocess.check_output([
"git", "rev-list", newrev, "-n", GIT_COMMIT_LIST_LENGTH
])
except Exception as e:
print("Exception: %s" % e)
... | 54,676 |
def test_logout(browser):
"""
Log out from an account.
Check if a home page changes its appearance accordingly.
"""
# Test Set Up
home_page = HomePage(driver=browser)
home_page.go()
# Test Actions
home_page.login_button.click()
home_page.switch_to_pop_up()
login_popup = Lo... | 54,677 |
def parse_arguments(parser: argparse.ArgumentParser):
"""
Method which parses all arguments and executes the corresponding command
:param parser: Parser which handles the arguments
"""
arguments = parser.parse_args()
# look for JPGs inside the input directory
directory = arguments.input
... | 54,678 |
def check_dust_database() -> str:
"""
Function to check if the dust data is present in the database and
add the data if needed.
Returns
-------
str
The database path from the configuration file.
"""
config_file = os.path.join(os.getcwd(), "species_config.ini")
config = con... | 54,679 |
def _NeedANewAnalysis(normalized_test,
original_test,
flake_key,
bug_id=None,
allow_new_analysis=False,
force=False,
user_email='',
triggering_source=triggering_sourc... | 54,680 |
def is_chosen(bbox, area_threshold=None) -> bool:
"""
Calculate area of bounding boxes and return True if area >= threshold
Args:
bbox: (x1, y1, width, heigh)
area_threshold:
Returns:
True/False
"""
are = bbox[2] * bbox[3]
if area_threshold is not None:
if ... | 54,681 |
def InsertOrganisationOfEvent(cur, con, event_id: int):
""" Inserts the organised relationship into the database """
# Get information about the organiser
row = {}
row["OrganisationID"] = input(
"Enter the Organisation ID of the Organisation "
"which is conducting the event: ") or None
... | 54,682 |
def test_increasing_trend() -> None:
"""Average of second arg > average of first arg."""
assert increasing_trend([2.0], [100.0])
assert increasing_trend([4.0, 3.0, 2.0, 20.0], [2.0, 101.0])
assert not increasing_trend([4.0, 3.0, 2.0, 20.0], [2.0, 3.0]) | 54,683 |
def test_create_definition():
"""
Scenario. A collection definition is created.
Expected result. Definition should be successfully created.
"""
name = "collection"
definition = CollectionDefinition(name)
assert definition is not None
assert definition.name == name
assert type(defin... | 54,684 |
def pymess_dae2_cnt_riccati(mmat=None, amat=None, jmat=None,
bmat=None, wmat=None, z0=None, mtxoldb=None,
transposed=False, aditol=5e-10, nwtn_res2_tol=5e-8,
maxit=20, verbose=False, linesearch=False, **kw):
""" solve the projected ... | 54,685 |
def is_unary_operator(oper):
"""returns True, if operator is unary operator, otherwise False"""
# definition:
# memeber in class
# ret-type operator symbol()
# ret-type operator [++ --](int)
# globally
# ret-type operator symbol( arg )
# ret-type operator [++ --](X&, int)
symbols = [... | 54,686 |
def map_advanced_param(param, value):
"""
Maps an advanced parameter value to
the value expected on the krdict website.
"""
return _get_advanced_param(_ADVANCED_PARAM_MAP[param], str(value), True) | 54,687 |
def basin_to_gridcell_dict(df_reference):
"""Generate a dictionary of gridcell id to basin id {grid_id: basin_id}
:param df_reference: Input data reference dataframe containing grid to basin info
:type df_reference: dataframe
:return: dict. {grid_id: basin... | 54,688 |
def fitness_coeff_constant(N_site,N_state,h_0,J_0):
"""
creating the mutational fitness coefficients for the simulated sequences
in the case of constant fields and constant couplings
Parameters:
N_site: int
sequence length
N_state: int
number of states per site
... | 54,689 |
def isort_test(code: str, expected_output: str = "", **config):
"""Runs isort against the given code snippet and ensures that it
gives consistent output accross multiple runs, and if an expected_output
is given - that it matches that.
"""
expected_output = expected_output or code
output = isort... | 54,690 |
def sendToKafka(producer, topic_out, list):
"""
Save idea messages to kafka topic
:param producer: producer for output topic
:param topic_out: topic to which will be messages sent
:param list: list with idea messages
"""
for idea in list:
if idea:
producer.send... | 54,691 |
def add_to_user_path(new_path: str, ):
"""
Add **one** path into PATH of current user
"""
assert ';' not in new_path
old_fixed_paths = get_user_path()
for p in old_fixed_paths:
if is_same_file(p, new_path):
return
old_paths = get_user_path()
return set_user_path([new_... | 54,692 |
def generate_1d_scatter(data, variables, class_data=None,
class_names=None, nrows=None, ncols=None,
sharex=False, sharey=False, show_legend=True,
outliers=False, cmap_class=None, **kwargs):
"""Generate 1D scatter plots from the given data and v... | 54,693 |
def methods_context(interface, component_info):
"""Creates a list of Jinja template contexts for methods of an interface.
Args:
interface: An interface to create contexts for
component_info: A dict containing component wide information
Returns:
A dictionary with 3 keys:
'it... | 54,694 |
def create_translator_instance():
"""Create IBM Translator Instance."""
authenticator = IAMAuthenticator(apikey)
language_translator = LanguageTranslatorV3(
version='2018-05-01',
authenticator=authenticator
)
language_translator.set_service_url(url)
return language_translator | 54,695 |
def shot(**kwargs):
"""
Adds a shot entity under the shots table in the `wgid` database.
Args:
kwargs(dict): Reference alfred configs
Returns:
True if successful
"""
key = "shot"
cmd = _create_from_config(key)
cmd += _create_entity(key, **kwargs)
# Submit SQL ... | 54,696 |
def symmAndRefl(t, ipt=False):
""" Return the transducer t | t.inverse, if ipt is True;
return the transducer t | t.inverse | id, otherwise
:type t: SFT
:type ipt: bool
:rtype: SFT"""
t1 = t | t.inverse()
if ipt is True:
return t1
t2 = SFT()
s0 = t2.addState()
... | 54,697 |
def display_options(screen: pygame.Surface, options: list) -> None:
"""Display a list of numbered options."""
for i, option in enumerate(options, 1):
number_position = (constants.OFFSET, (2 + i) * constants.OFFSET)
make_aligned_text(screen, f'{i}.', number_position)
option_position = (c... | 54,698 |
def approvewitness(witness, account):
"""Approve a witnesses"""
stm = shared_steem_instance()
if stm.rpc is not None:
stm.rpc.rpcconnect()
if not account:
account = stm.config["default_account"]
if not unlock_wallet(stm):
return
acc = Account(account, steem_instance=stm)
... | 54,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.