content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_cycle_time(string):
"""
Extract the cycle time text from the given string. None if not found.
"""
return _search_in_pattern(string, CYCLE_TIME_PATTERN, 1) | 47,400 |
def main():
"""
Main function.
"""
"""Initialization"""
set_random_seed(2021)
opt = _config_parser()
output_dir, ckpt_output_dir = config_log(opt, get_output_path(opt))
nodata_value = get_nodata_value(opt.scene)
trainset, trainset_loader, mean = config_dataloader(opt.scene, opt.ta... | 47,401 |
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)
hass.data[DOMAIN].pop(config_entry.entry_id, None)
if not hass.data[DOMAIN]:
has... | 47,402 |
def showFileOrFolder(pathUrl):
"""
Send the binary content of a file on the X drive
"""
#showRequest(pathUrl, request)
pathLocal = abfBrowse.getLocalPath("X/"+pathUrl)
print(" serving", os.path.basename(pathLocal))
if os.path.isdir(pathLocal):
return f"directory index of [{pathLocal... | 47,403 |
def get_scale_factor(unit: Union[str, float]) -> float:
"""
Get how many pts are in a unit.
:param unit: A unit accepted by fpdf.FPDF
:return: The number of points in that unit
:raises FPDFException
"""
if isinstance(unit, (int, float)):
return float(unit)
k = FPDF_UNITS.get(unit... | 47,404 |
def create_html_from_md(cfg):
"""Creation of webpages from md files."""
logging.info("4/4 Creating html files.")
out_path = cfg["out_path"]
md_files = find_files(cfg, cfg["out_path"], ".md")
# This section goes through 'input' and 'split' directories collecting md files
# and creating html fi... | 47,405 |
def r2_score(y_true,y_pred):
"""Calculate the coefficient of determination."""
assert len(y_true)==len(y_pred)
rss = sum_square_residuals(y_true,y_pred)
tss = total_sum_squares(y_true)
return 1 - rss/tss | 47,406 |
def give_name(fname):
"""
return name.csv
"""
if fname[:len( AUX_FILE) ] != AUX_FILE: # hide file
# renaming with correct extension
if fname[ -4: ]!= '.csv':
if fname.find('.') > -1:
fname = fname[: fname.find('.')]+'.csv'
else:
fname += '.csv'... | 47,407 |
def categorize(document):
"""Categorize a document.
Categorizes a document into the following categories
[business, entertainment, politics, sport, tech].
Takes a string object as input and returns a string object.
"""
doc = clean(document)
vector = doc2vec_model.infer_vector(doc.split(' '... | 47,408 |
def test_python3_binary_which(host):
"""
Tests the output to confirm python3's binary location.
"""
assert host.check_output('which python3') == PACKAGE_BINARY | 47,409 |
def delete_intent(token, aiid, intent_name):
"""Delete an Intent"""
return fetch_api(
'/intent/{aiid}?intent_name={intent_name}',
token=token,
aiid=aiid,
intent_name=intent_name,
method='delete'
) | 47,410 |
def report_all(df_select):
"""
report all values to a defined template
"""
if len(df_select) == 0:
report_all = 'No similar events were reported on in online media'
else:
report_all = """
Similar events were reported on in online media.
Below we provide a tabulated s... | 47,411 |
def api():
"""Generates the API viewer for the current project"""
profile = Profile.Profile(session)
profile.registerPart("kernel", className="core.apibrowser.Kernel")
profile.registerPart("main", className="core.apibrowser.Browser")
profile.setField("debug", False)
profile.setCopyAssets(True)
... | 47,412 |
def get_filename_from_headers(response):
"""Extract filename from content-disposition headers if available."""
content_disposition = response.headers.get("content-disposition", None)
if not content_disposition:
return None
entries = content_disposition.split(";")
name_entry = next((e.strip... | 47,413 |
def names(as_object=False, p5_connection=None):
"""
Syntax: ArchiveIndex names
Description: Returns the list of names of archive indexes.
Return Values:
-On Success: a list of names. If no archive indexes are configured,
the command returns the string "<empty>"
"""
met... | 47,414 |
def regionvit_base_w14_224(pretrained=False, progress=True, **kwargs):
"""
Constructs the RegionViT-Base-w14-224 model.
.. note::
RegionViT-Base-w14-224 model from `"RegionViT: Regional-to-Local Attention for Vision Transformers" <https://arxiv.org/pdf/2106.02689.pdf>`_.
The required input ... | 47,415 |
def describe_load_balancer_target_groups(AutoScalingGroupName=None, NextToken=None, MaxRecords=None):
"""
Describes the target groups for the specified Auto Scaling group.
See also: AWS API Documentation
Exceptions
Examples
This example describes the target groups attached to the specified ... | 47,416 |
def create_executor_list(suites):
"""
Looks up what other resmoke suites run the tests specified in the suites
parameter. Returns a dict keyed by suite name / executor, value is tests
to run under that executor.
"""
memberships = collections.defaultdict(list)
test_membership = resmokelib.pa... | 47,417 |
def calculate_great_circle(args):
"""one step of the great circle calculation"""
lon1,lat1,lon2,lat2 = args
radius = 3956.0
x = np.pi/180.0
a,b = (90.0-lat1)*(x),(90.0-lat2)*(x)
theta = (lon2-lon1)*(x)
c = np.arccos((np.cos(a)*np.cos(b)) +
(np.sin(a)*np.sin(b)*np.co... | 47,418 |
def divide(x,y):
"""div x from y"""
return x/y | 47,419 |
def execute(compile_state: CompileState, string: StringResource) -> NullResource:
""" Executes the string at runtime and returns Null"""
compile_state.ir.append(CommandNode(string.static_value))
return NullResource() | 47,420 |
def run_scrapers(start, end):
"""
Run the scrapers in blocks of {step}.
"""
ids = get_ids_from_tarball()
num_max_ids = len(ids[start:end])
for ix in range(start, start+num_max_ids, step):
imdb = ImdbScraper(ix, ix+step, step, ids=ids)
imdb.update() | 47,421 |
def fakeLabels(lth):
"""
lth (int): no of labels required
"""
label=torch.tensor([])
for i in range(lth):
arr=np.zeros(c_dims)
arr[0]=1
np.random.shuffle(arr)
label=torch.cat((label,torch.tensor(arr).float().unsqueeze(0)),dim=0)
return label | 47,422 |
def load_canadian_senators(**kwargs):
"""
A history of Canadian senators in office.::
Size: (933,10)
Example:
Name Abbott, John Joseph Caldwell
Political Affiliation at Appointment Liberal-Conservative
Pro... | 47,423 |
def _get_md5(filename):
"""Return the MD5 checksum of the passed file"""
data = open(filename, "rb").read()
r = md5(data)
return r.hexdigest() | 47,424 |
def registerPlayer(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
with get_curs... | 47,425 |
def splitIntoDirs(dirfmt, num, files):
"""Splits the given set of files into directories.
dirfmt defines the naming scheme of the directories (it's used as dirfmt % i), and num
is the max number per directory"""
cur = 0
total = len(files)
tomove = {}
# first figure out how many files to move... | 47,426 |
def implements(numpy_func_string, func_type):
"""Register an __array_function__/__array_ufunc__ implementation for Quantity
objects.
"""
def decorator(func):
if func_type == "function":
HANDLED_FUNCTIONS[numpy_func_string] = func
elif func_type == "ufunc":
HANDL... | 47,427 |
def r2(data1, data2):
"""Return the r-squared difference between data1 and data2.
Parameters
----------
data1 : 1D array
data2 : 1D array
Returns
-------
output: scalar (float)
difference in the input data
"""
ss_res = 0.0
ss_tot = 0.0
mean = sum(data1) / l... | 47,428 |
def fio_color_hist_fio(image_fio):
"""Generate a fileIO with the color histogram of an image fileIO
:param image_fio: input image in fileIO format
:type image_fio: fileIO
:return: color histogram of the input image in fileIO format
:rtype: fileIO
"""
image_fio.seek(0)
bkp = fio_to_b(ima... | 47,429 |
def read_adj_list(path: str, new_graph: "GraphBase[V, E]", delimiters: str = r",\s*|\s+") -> None:
"""Reads an adjacency list from a text file and populates ``new_graph``.
The ``new_graph`` is cleared and then :term:`vertices <vertex>` and :term:`edges <edge>` are
added from the adjacency list. The adj... | 47,430 |
async def test_player_sync(player, other_player, broken_player):
"""Test sync functions."""
async def unsync_test(test_player):
await test_player.async_unsync()
await test_player.async_update()
assert not test_player.synced
assert not test_player.sync_group
assert not te... | 47,431 |
def store_list(request, user_id):
"""
Verify user has the access to enlist store.
"""
logger.debug('calling store.views.store_list()')
user_name = request.user.username
menu = MenuService.new_user_menu(request.user)
context = {
'menu':menu,
'page_title': 'Profile',
... | 47,432 |
def lattice2d_fixed_env():
"""Lattice2DEnv with a fixed sequence"""
seq = 'HHHH'
return Lattice2DEnv(seq) | 47,433 |
def expected_full(
clr,
view_df=None,
smooth_cis=False,
aggregate_smoothed=False,
smooth_sigma=0.1,
aggregate_trans=False,
expected_column_name="expected",
ignore_diags=2,
clr_weight_name='weight',
chunksize=10_000_000,
nproc=4,
... | 47,434 |
def nmgy2abmag(flux, flux_ivar=None):
"""
Conversion from nanomaggies to AB mag as used in the DECALS survey
flux_ivar= Inverse variance oF DECAM_FLUX (1/nanomaggies^2)
"""
lenf = len(flux)
if lenf > 1:
ii = np.where(flux>0)
mag = 99.99 + np.zeros_like(flux)
mag[ii] = 22.... | 47,435 |
def rnn_decoder(dec_input, init_state, cell, infer, dnn_hidden_units, num_feat):
"""Decoder for RNN cell.
Given list of LSTM hidden units and list of LSTM dropout output keep
probabilities.
Args:
dec_input: List of tf.float64 current batch size by number of features
matrix tensors input to the decod... | 47,436 |
def l1_loss(pre, gt):
""" L1 loss
"""
return torch.nn.functional.l1_loss(pre, gt) | 47,437 |
def run_tnscope(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Call variants with Sentieon's TNscope somatic caller.
"""
if out_file is None:
out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0]
if not utils.file_exists(out_file)... | 47,438 |
def get_product(product_id):
"""
Read a single Product
This endpoint will return a product based on it's id
"""
app.logger.info("Request for product with id: %s", product_id)
product = Product.find(product_id)
if not product:
raise NotFound("product with id '{}' was not found.".forma... | 47,439 |
def _unwrapx(input, output, repeat):
"""
Unwrap the X format column into a Boolean array.
Parameters
----------
input
input ``Uint8`` array of shape (`s`, `nbytes`)
output
output Boolean array of shape (`s`, `repeat`)
repeat
number of bits
"""
pow2 = np.ar... | 47,440 |
def aips_bintable_fortran_fields_to_dtype_conversion(aips_type):
"""Given AIPS fortran format of binary table (BT) fields, returns
corresponding numpy dtype format and shape. Examples:
4J => array of 4 32bit integers,
E(4,32) => two dimensional array with 4 columns and 32 rows.
"""
intv = np.ve... | 47,441 |
def test_directive1_raw_md():
"""The copy of .md file in fenced code block is the same as the file."""
check_first_block(
markdown_path="doc/directive1_raw.md", contents_path="doc/directive1.md"
) | 47,442 |
def account_list():
"""获取账户列表"""
rps = {}
rps["status"] = True
account_list = query_account_list(db)
if account_list:
rps["data"] = account_list
else:
rps["status"] = False
rps["data"] = "账户列表为空"
return jsonify(rps) | 47,443 |
def sample_points_in_range(min_range, max_range, origin, directions, n_points):
"""Sample uniformly depth planes in a depth range set to [min_range,
max_range]
Arguments
---------
min_range: int, The minimum depth range
max_range: int, The maximum depth range
origin: tensor(shape=(4, 1),... | 47,444 |
def normalize(vectorOrCounter):
"""
normalize a vector or counter by dividing each value by the sum of all values
"""
normalizedCounter = Counter()
if type(vectorOrCounter) == type(normalizedCounter):
counter = vectorOrCounter
total = float(counter.totalCount())
if total == 0... | 47,445 |
def IsStringInt(string_to_check):
"""Checks whether or not the given string can be converted to an int."""
try:
int(string_to_check)
return True
except ValueError:
return False | 47,446 |
def read(*parts):
"""
Build an absolute path from *parts* and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *parts), 'rb', 'utf-8') as f:
return f.read() | 47,447 |
def build_ewc_posterior(data_handlers, mnet, device, config, shared, logger,
writer, num_trained, task_id=None):
"""Build a normal posterior after having trained using EWC.
The posterior is constructed as described in function :func:`test`.
Args:
(....): See docstring of fu... | 47,448 |
def initialize_model(model, initializer, bias_initializer=None):
"""
Recursively initializes all parameters of the model. It accepts two
initializer functions: one for (main) weights and one for biases. The
latter defaults to constant zero.
"""
if not bias_initializer:
bias_initializer =... | 47,449 |
def get_roc_curve(y_gold_standard,y_predicted):
"""
Computes the Receiver Operating Characteristic.
Keyword arguments:
y_gold_standard -- Expected labels.
y_predicted -- Predicted labels
"""
return roc_curve(y_gold_standard, y_predicted) | 47,450 |
def test_target_fixedIh():
"""Test the target function for targeted scaling (where Ih is fixed)."""
target = ScalingTargetFixedIH()
Ih_table = mock_Ih_table().blocked_data_list[0]
R, _ = target.compute_residuals(Ih_table)
expected_residuals = flex.double([-1.0, 0.0, 1.0])
assert list(R) == pyte... | 47,451 |
def get_image_unixtime2(ibs, gid_list):
""" alias for get_image_unixtime_asfloat """
return ibs.get_image_unixtime_asfloat(gid_list) | 47,452 |
def _wait_for_stop(self, name, version=None, exclude_version=None,
timeout=None, check_retries=None, search_params=None):
"""
Wait for deployment to be stopped
:param name: Name of application
:type name: str
:param version: Version of application.
:type version: str
:key... | 47,453 |
def create_sql_query(mogrify, data_set_id, user_query):
"""
Creates a sql query and a funtion which transforms the output into a list
of dictionaries with correct field names.
>>> from tests.support.test_helpers import mock_mogrify
>>> query, fn = create_sql_query(mock_mogrify, 'some-collection', Q... | 47,454 |
def patch_hass():
"""
Patch the Hass API and returns a tuple of:
- The patched functions (as Dict)
- A callback to un-patch all functions
"""
class MockInfo:
"""Holds information about a function that will be mocked"""
def __init__(self, object_to_patch, function_name, autospec=F... | 47,455 |
def iter_function_annotations(obj):
"""Iterates over annotations of function and it's default values."""
for name, param in signature(obj).parameters.items():
if param.annotation is _empty:
continue
yield name, param.annotation, param.default | 47,456 |
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:
----... | 47,457 |
def parallax_angle(sc, **kw) -> DEG:
"""Compute parallax angle from skycoord.
Parameters
----------
sc: SkyCoord
** warning: check if skycoord frame centered on Earth
Returns
-------
p: deg
parallax angle
"""
return np.arctan(1 * AU / sc.spherical.distance) | 47,458 |
def formatting_dates(dates_list):
""" Formatting of both the start and end dates of a historical period.
dates = [period_start_date, period_end_date]"""
new_dates = dates_list
# Change all "BCE" into "BC":
for index1 in range(len(new_dates)):
if " BCE" not in new_dates[index1]:
... | 47,459 |
def exp_days_f(cppm_class, current_user):
"""
User's password expiration and check force change password function.
1. Calculates days to expiry password for particular user
2. Checks change password force checkbox.
Returns:
exp_days: Number of days until a password expired
... | 47,460 |
def test_single_backtest_sanity(period, df_nans_with_noise):
"""Test that _SingleDifferencingTransform correctly works in backtest."""
transform = _SingleDifferencingTransform(in_column="target", period=period, inplace=True)
check_single_backtest_sanity(transform, period, df_nans_with_noise) | 47,461 |
def test_config_expand1():
"""Expand shell commands from string to list."""
test_config = config.expand(fixtures.expand1.before_config)
assert test_config == fixtures.expand1.after_config | 47,462 |
def setup_login():
""" run login node setup """
setup_network_storage()
mount_fstab()
util.run("systemctl restart munge")
try:
util.run(str(dirs.scripts/'custom-compute-install'))
except Exception:
# Ignore blank files with no shell magic.
pass
log.info("Done setting... | 47,463 |
def isinteger(x):
"""
determine if a string can be converted to an integer
"""
try:
a = int(x)
except ValueError:
return False
except TypeError:
return False
else:
return True | 47,464 |
def get_economic_parameters():
"""
Extracts and returns the parameters for the economic model
This function returns a dictionary with all parameters needed to run the economic model.
Returns
-------
pars_dict : dictionary
contains the values of all economic parameters
Paramet... | 47,465 |
def recommend(docs_path, dict_path, use_fos_annot=False, pp_dict_path=None,
np_dict_path=None, lda_preselect=False,
combine_train_contexts=True):
""" Recommend
"""
test = []
train_mids = []
train_texts = []
train_foss = []
train_ppann = []
train_nps = []
... | 47,466 |
def setup():
"""Installs all Python package dependencies."""
local("pip install -r pip-requirements.txt") | 47,467 |
def _get_hash(x):
"""Generate a hash from a string, or dictionary."""
if isinstance(x, dict):
x = tuple(sorted(pair for pair in x.items()))
return hashlib.md5(bytes(repr(x), "utf-8")).hexdigest() | 47,468 |
def insert_single_bone(pmx: pmxstruct.Pmx, newbone: pmxstruct.PmxBone, newindex: int):
"""
Wrapper function to make inserting bones simpler.
(!) No existing bones should refer to this bone before it is inserted. (!) When constructing newbone, it should
refer to already-existing bones by using their indices BEFORE t... | 47,469 |
def wrap_arr(arr, wrapLow=-90.0, wrapHigh=90.0):
"""Wrap the values in an array (e.g., angles)."""
rng = wrapHigh - wrapLow
arr = ((arr-wrapLow) % rng) + wrapLow
return arr | 47,470 |
def task_fail_slack_alert(context):
"""
Callback task that can be used in DAG to alert of failure task completion
Args:
context (dict): Context variable passed in from Airflow
Returns:
None: Calls the SlackWebhookOperator execute method internally
"""
if ENV != "data":
re... | 47,471 |
def largest_negative_number(seq_seq):
"""
Returns the largest NEGATIVE number in the given sequence of
sequences of numbers. Returns None if there are no negative numbers
in the sequence of sequences.
For example, if the given argument is:
[(30, -5, 8, -20),
(100, -2.6, 88, -40, -... | 47,472 |
def align_quaternion_frames(target_skeleton, frames):
"""align quaternions for blending
src: http://physicsforgames.blogspot.de/2010/02/quaternions.html
"""
ref_frame = None
new_frames = []
for frame in frames:
if ref_frame is None:
ref_frame = frame
else:
... | 47,473 |
def do_round(precision=0, method='common'):
"""
Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
... | 47,474 |
def create_paths(dir_list):
""" Create directories if they do not exist already, given path """
for new_dir in dir_list:
if new_dir is not None:
new_path = Path(new_dir)
new_path.mkdir(parents=True, exist_ok=True) | 47,475 |
def test_message_failed_terminedia_import(cli_arg: Callable[..., str]) -> None:
"""It raises a user-friendly warning message if import fails."""
output = cli_arg("--image-drawing=block")
expected_output = (
"Usage: main [OPTIONS] [FILE]..."
"\nTry 'main --help' for help."
"\n\nError:... | 47,476 |
def scale_invariant_signal_distortion_ratio(preds: Tensor, target: Tensor, zero_mean: bool = False) -> Tensor:
"""Calculates Scale-invariant signal-to-distortion ratio (SI-SDR) metric. The SI-SDR value is in general
considered an overall measure of how good a source sound.
Args:
preds:
... | 47,477 |
def create_db(name):
"""Creates database with tables"""
os.system('createdb {}'.format(name))
db.create_all()
print("{} has been successfully created.".format(name)) | 47,478 |
def is_token_valid():
"""Check whether the stored token is still valid.
:returns: A bool.
"""
try:
with open('/tmp/tngcli.txt', 'r') as file:
for line in file:
payload = json.loads(line)
except:
return False, 'no token file found'
exp_t = paylo... | 47,479 |
def DB_getQanswer(question):
"""
Calls the function in the database that gets the question answer to the
input question.
"""
return DB.get_question_answer(question) | 47,480 |
def _state_senate_slide_preview(slug):
"""
Preview a state slide outside of the stack.
"""
context = make_context()
resp = _state_senate_slide(slug)
if resp.status_code == 200:
context['body'] = resp.data
return render_template('slide_preview.html', **context)
else:
... | 47,481 |
def tensor_network_tt_einsum(inputs, states, output_size, rank_vals, bias, bias_start=0.0):
# print("Using Einsum Tensor-Train decomposition.")
"""tensor train decomposition for the full tenosr """
num_orders = len(rank_vals)+1#alpha_1 to alpha_{K-1}
num_lags = len(states)
batch_size = tf.shape(in... | 47,482 |
def fight(log, qqnum):
"""
挑战指定qq号
:param log:
:param qqnum: QQ号
:return:
"""
qqfight = "https://fight.pet.qq.com/cgi-bin/petpk?cmd=fight&puin=%(puin)s"
response = req.get(qqfight % {"puin": str(qqnum)})
# result = jiexifanhuixiaoxi(response,"result") | 47,483 |
def test_h_cmd(vim_bot, text, cmd_list, cursor_pos):
"""Test h command."""
_, _, editor, vim, qtbot = vim_bot
editor.set_text(text)
cmd_line = vim.get_focus_widget()
for cmd in cmd_list:
qtbot.keyClicks(cmd_line, cmd)
assert cmd_line.text() == ""
assert editor.textCursor().position... | 47,484 |
def case(
mapper: Callable[[], _TKey],
sources: Mapping[_TKey, Observable[_T]],
default_source: Optional[Union[Observable[_T], "Future[_T]"]] = None,
) -> Observable[_T]:
"""Uses mapper to determine which source in sources to use.
.. marble::
:alt: case
--1---------------|
... | 47,485 |
def group_to_stats(request, project_id) -> Tuple:
"""
Combining the same actions for grouping data for chart
"""
filters = json.loads(request.query_params.get('filters', '{}')) # date time, issue type, method
group_by = request.query_params.get('groupBy', 'hours')
requests_stats = RequestStat.... | 47,486 |
def retrieve_link(bash_command):
""" Gets room link retrieved from the CLI """
import tkinter
global link
global curr_dir
print(curr_dir)
subprocess.Popen(bash_command)
while not os.path.exists(curr_dir + "/invite_link.txt"):
root.after(2000)
f = open("invite_link.txt", "r")
... | 47,487 |
def build_delete(table, where):
"""
Build a delete request.
Parameters
----------
table : str
Table where query will be directed.
where: iterable
The list of conditions to constrain the query.
Returns
-------
str
Built query.
"""
sql_q = "DELETE "
... | 47,488 |
def filter_resources_sets(used_resources_sets, resources_sets, expand_resources_set, reduce_resources_set):
""" Filter resources_set used with resources_sets defined.
It will block a resources_set from resources_sets if an used_resources_set in a subset of a resources_set"""
resources_expand = [expand_... | 47,489 |
def get_index_base():
"""获取上海及深圳指数代码、名称表"""
url_fmt = 'http://quotes.money.163.com/hs/service/hsindexrank.php?host=/hs/service/'
url_fmt += 'hsindexrank.php&page={page}&query=IS_INDEX:true;EXCHANGE:CNSE{ex}&fields=no,SYMBOL,NAME&'
url_fmt += 'sort=SYMBOL&order=asc&count={count}&type=query'
one_big_i... | 47,490 |
def test_ccr_zero():
"""
Tests to see that the zero bit is set correctly
Example case used:
MOVE.B #$0,D0
ORI.B #0,D0
"""
sim = M68K()
sim.set_program_counter_value(0x1000)
sim.set_register(Register.D0, MemoryValue(OpSize.BYTE, unsigned_int=0))
params = [AssemblyPara... | 47,491 |
def merge_list_of_dicts(old, new, key):
"""
Merge a list of dictionary items based on a specific key.
Dictionaries inside the list with a matching key get merged together.
Assumes that a value for the given key is unique and appears only once.
Example:
list1 = [{"name": "one", "data": "stuff"... | 47,492 |
def pull_metrics():
"""Call a scrape for each enabled data source plugin."""
trigger_latest_scrapes(
model_class=Uri,
task_function=trigger_plugins_by_doi
)
trigger_latest_scrapes(
model_class=UriPrefix,
task_function=trigger_plugins_by_prefix
) | 47,493 |
def get_kpoints_data_max4(xmltree, schema_dict, logger=None, convert_to_angstroem=True):
"""
Get the kpoint sets defined in the given fleur xml file.
.. note::
This function is specific to file version before and including the
Max4 release of fleur
:param xmltree: etree representing th... | 47,494 |
def permission_required_on_object(
perm, object_getter, login_url=None, handle_access_error=None, raise_exception=False
):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
If the raise_exception parameter is given th... | 47,495 |
def convert_jsonlines_to_conll_format(input_file_path, output_file_path, cluster_key_name='predicted_clusters'):
"""
Args:
input_file_path: string
output_file_path: string
cluster_key_name: string
"""
with open(input_file_path) as fopen, open(output_file_path, 'w') as fwrite:
... | 47,496 |
def contains_badwords(string):
"""
Return whether a string contains bad words
"""
return any([x in string for x in bad_words]) | 47,497 |
def get_cluster_info(metadata, consensus_subjects=None):
"""
Construct cluster centroids and tractograms in MNI space from test session
so can run `match_clusters`
Identify `consensus_subject` for the test session n_clusters using `metadata['algorithm']`.
The consensus subject is use to align clust... | 47,498 |
def probe_all_devices(driver_config_fname):
"""
Acquiring states of all devies, added to config.
States could be:
alive - device is working in normal mode and answering to modbus commands
in_bootloader - device could not boot it's rom
disconnected - a dummy-record in config
"""
... | 47,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.