content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def example_data():
"""Makes some example objects for db testing"""
user = User(username='testo', password='testo', email='testo@test.com',
age=35, gender='nb_gf')
user2 = User(username='boolean', password='bear', email='bb@test.com',
age=32, gender='nb_gf')
user3 = User... | 11,900 |
def linear_resample(x: Union[ivy.Array, ivy.NativeArray], num_samples: int, axis: int = -1, f: ivy.Framework = None)\
-> Union[ivy.Array, ivy.NativeArray]:
"""
Performs linear re-sampling on input image.
:param x: Input array
:type x: array
:param num_samples: The number of interpolated sam... | 11,901 |
def mysql_settings():
"""Return a list of dict of settings for connecting to postgresql.
Will return the correct settings, depending on which of the environments it
is running in. It attempts to set variables in the following order, where
later environments override earlier ones.
1. Local
... | 11,902 |
def fill (surface, rect, colour):
"""Fill a single colour.
Takes a standard (r, g, b) tuple.
"""
surface.fill(colour, rect) | 11,903 |
def update_milestones(repo, username=None, namespace=None):
"""Update the milestones of a project."""
repo = flask.g.repo
form = pagure.forms.ConfirmationForm()
error = False
if form.validate_on_submit():
redirect = flask.request.args.get("from")
milestones = flask.request.form.ge... | 11,904 |
def installedState(item_pl):
"""Checks to see if the item described by item_pl (or a newer version) is
currently installed
All tests must pass to be considered installed.
Returns 1 if it looks like this version is installed
Returns 2 if it looks like a newer version is installed.
Returns 0 othe... | 11,905 |
def trapezoid_vectors(t, depth, big_t, little_t):
"""Trapezoid shape, in the form of vectors, for model.
Parameters
----------
t : float
Vector of independent values to evaluate trapezoid model.
depth : float
Depth of trapezoid.
big_t : float
Full trapezoid duration.
... | 11,906 |
def get_rules(clf, class_names, feature_names):
"""
Extracts the rules from a decision tree classifier.
The keyword arguments correspond to the objects returned by
tree.build_tree.
Keyword arguments:
clf: A sklearn.tree.DecisionTreeClassifier.
class_names: A list(str) containing the class n... | 11,907 |
def save_repo(repo, target="/run/install"):
"""copy a repo to the place where the installer will look for it later."""
newdir = mkdir_seq(os.path.join(target, "DD-"))
log.debug("save_repo: copying %s to %s", repo, newdir)
subprocess.call(["cp", "-arT", repo, newdir])
return newdir | 11,908 |
def file_parser(localpath = None, url = None, sep = " ", delimiter = "\t"):
"""
DOCSTRING:
INPUT:
> 'localpath' : String (str). Ideally expects a local object with a read() method (such as a file handle or StringIO).
By default, 'localpath=dummy_file' parameter can be passed to auto-detect and ... | 11,909 |
def is_list(var, *, debug=False):
"""
is this a list or tuple? (DOES NOT include str)
"""
print_debug(debug, "is_list: got type %s" % (type(var)))
return isinstance(var, (list, tuple)) | 11,910 |
def zonotope_minimize(avfun, avdom, avdfun):
"""
Minimize a response surface defined on a zonotope.
:param function avfun: A function of the active variables.
:param ActiveVariableDomain avdom: Contains information about the domain of
`avfun`.
:param function avdfun: Returns the gradient of... | 11,911 |
def node_to_truncated_gr(node, bin_width=0.1):
"""
Parses truncated GR node to an instance of the
:class: openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD
"""
# Parse to float dictionary
if not all([node.attrib[key]
for key in ["minMag", "maxMag", "aValue", "bValue"]]):
... | 11,912 |
def nt(node, tag):
""" returns text of the tag or None if the
tag does not exist """
if node.find(tag) is not None and node.find(tag).text is not None:
return node.find(tag).text
else:
return None | 11,913 |
def set_user_favorites(username, **_):
"""
Sets the user's Favorites
Variables:
username => Name of the user you want to set the favorites for
Arguments:
None
Data Block:
{ # Dictionary of
"alert": [
"<name_of_query>": # Named queries
... | 11,914 |
def set_kaggle_dir(kaggle_dir, ctx=None):
""" manually set kaggle directory that contains API key """
if not os.path.exists(kaggle_dir):
click.secho("Error: {} does not exist".format(kaggle_dir), fg="red")
exit(1)
if not os.path.isdir(kaggle_dir):
click.secho("Error: {} is no... | 11,915 |
def corpus():
"""语料生成器
"""
while True:
f = '/root/data_pretrain/data_shuf.json'
with open(f) as f:
for l in f:
l = json.loads(l)
for text in text_process(l['text']):
yield text | 11,916 |
def delete_token(token_id):
"""Revoke a specific token in the application auth database.
:type token_id: str
:param token_id: Token identifier
:rtype: tuple
:return: None, status code
"""
client_data = g.client_data
if not valid_token_id(token_id):
raise Malforme... | 11,917 |
async def update_country(identifier: Optional[str] = None, name: Optional[str] = None, capital: Optional[str] = None,
country: UpdateCountryModel = Body(...), current_user: AdminModel = Depends(get_current_user)):
"""
Update a country by name or capital name:
- **current user** sho... | 11,918 |
def test_api_metrics(mocker, flask_app, api_version):
"""Test Depot ID TBD.
Verify that StatsD is sent statistics about the performance of TAC and IMEI APIs. The
metric name should contain the HTTP status code so that the response times can be
broken down by status code.
"""
# Can't import dirb... | 11,919 |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
"""method-1 time O(n), traverse all, get rest"""
for i in range(len(nums)):
res = target - nums[i]
if res in nums:
return [i, nums.index(res)]
else:
ret... | 11,920 |
def test_model_reset_correctly(tmpdir):
"""Check that model weights are correctly reset after scaling batch size."""
tutils.reset_seed()
model = BatchSizeModel(batch_size=2)
# logger file to get meta
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1)
before_state_dict = deepcopy(model.s... | 11,921 |
def transform_image(image, code_vectors):
"""
Quantize image using the code_vectors (aka centroids)
Return a new image by replacing each RGB value in image with the nearest code vector
(nearest in euclidean distance sense)
returns:
numpy array of shape image.shape
... | 11,922 |
def main():
"""
Main method that collects the ASN from the spine switches using the native model
"""
asn_filter = """
<System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
<bgp-items>
<inst-items>
<asn/>
</inst-items>
</bgp-items>
</System>
"""
for device... | 11,923 |
def create_linking_context_from_compilation_outputs(
*,
actions,
additional_inputs = [],
alwayslink = False,
compilation_outputs,
feature_configuration,
label,
linking_contexts = [],
module_context,
name = None,
swift_toolchain,
... | 11,924 |
def test_ClangFormat_long_line():
"""Test that extremely long lines are not wrapped."""
assert (
java.ClangFormat(
"""
public class VeryVeryLongNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
extends VeryVeryLongNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeBase {
}
"""
)
== """
public clas... | 11,925 |
def wait_until_uds_reachable(uds_path, return_sock=False):
""" Wait until the unix domain socket at `uds_path` is reachable.
Returns
-------
socket.socket
"""
from miniworld.util import ConcurrencyUtil
sock = ConcurrencyUtil.wait_until_fun_returns_true(lambda x: x[0] is True, uds_reachable... | 11,926 |
def get_relation_count_df(
dataset: Dataset,
merge_subsets: bool = True,
add_labels: bool = True,
) -> pd.DataFrame:
"""Create a dataframe with relation counts.
:param dataset:
The dataset.
:param add_labels:
Whether to add relation labels to the dataframe.
:param merge_subs... | 11,927 |
def set_data(group: h5py.Group, name: str, data: Union[np.ndarray, h5py.Dataset], dtype=None):
"""
Creates a dataset in Group with Name for data that is either an np.ndarray or a h5py.Dataset already (if using a
dataset, it will only create a link to that dataset which is good for saving storage space, but ... | 11,928 |
def get_tests(run_id):
"""
Ручка для получения информации о тест (из тест-рана)
Выходящий параметр: test_id
"""
client = APIClient('https://testrail.homecred.it')
client.user = 'dmitriy.zverev@homecredit.ru'
client.password = 'Qwerty_22'
tests = client.send_get('get_tests/%s' % run_id)
... | 11,929 |
def create_ffs():
"""
Create a new Powergate Filecoin Filesystem (FFS)
"""
powergate = PowerGateClient(app.config["POWERGATE_ADDRESS"])
ffs = powergate.ffs.create()
creation_date = datetime.now().replace(microsecond=0)
# TODO salt token id
filecoin_file_system = Ffs(
ffs_id=ffs... | 11,930 |
def cleanup_pools():
"""Removes all storage pools from ScaleIO created by functional tests."""
for pool in StoragePool.all():
if not _is_test_name(pool):
continue
pool.delete()
assert not [p for p in StoragePool.all() if _is_test_name(p)] | 11,931 |
def store_file(bucket, dataset, key, fileobj):
"""
Store a file on S3
Parameters
----------
bucket : str
dataset : str
key : str
fileobj : fileobj
"""
key = parsed_key(dataset, key)
total_sent = 0
logging.info("store_file: {}/{}".format(bucket, key))
def cb(byte... | 11,932 |
def other(player):
"""Return the other player, for a player PLAYER numbered 0 or 1.
>>> other(0)
1
>>> other(1)
0
"""
return 1 - player | 11,933 |
def _explored_parameters_in_group(traj, group_node):
"""Checks if one the parameters in `group_node` is explored.
:param traj: Trajectory container
:param group_node: Group node
:return: `True` or `False`
"""
explored = False
for param in traj.f_get_explored_parameters():
if pa... | 11,934 |
def _execute(query,
data=None,
config_file=DEFAULT_CONFIG_FILE):
"""Execute SQL query on a postgres db"""
# Connect to an existing database.
postgres_db_credentials = postgres_db(config_file)
conn = psycopg2.connect(dbname=postgres_db_credentials["dbname"],
... | 11,935 |
def _construct_out_filename(fname, group_name):
"""
Construct a specifically formatted output filename.
The vrt will be placed adjacent to the HDF5 file, as
such write access is required.
"""
basedir = fname.absolute().parent
basename = fname.with_suffix('.vrt').name.replace(
'wagl',... | 11,936 |
def test_add_record():
"""
"""
groups = groups_description
dataset_size = 3
temporal_context = 3
try:
shutil.rmtree('/tmp/fake_memmmaps/')
except:
pass
# build dataset
memmaps = generate_memmaps(dataset_size, three_groups_record_description,
... | 11,937 |
def _deposit_need_factory(name, **kwargs):
"""Generate a JSON argument string from the given keyword arguments.
The JSON string is always generated the same way so that the resulting Need
is equal to any other Need generated with the same name and kwargs.
"""
if kwargs:
for key, value in en... | 11,938 |
def not_equal(version1, version2):
"""
Evaluates the expression: version1 != version2.
:type version1: str
:type version2: str
:rtype: bool
"""
return compare(version1, '!=', version2) | 11,939 |
def test_lf_acc_with_strict_match_with_prefixes_without_agg(
analysis_corpus,
analysis_corpus_y
):
""" Test expected accuracies across below spans:
Spans:
"name_1": Pierre (B-PERSON), Lison (L-PERSON), Pierre(U-PERSON)
"name_2": Pierre (B-PERSON), Lison (L-PERSON)
"org_1": Norwe... | 11,940 |
def get_sp_list():
"""
Gets all tickers from S&P 500
"""
bs = get_soup('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
sp_companies = bs.find_all('a', class_="external text")
return sp_companies | 11,941 |
def loadNecessaryDatabases():
"""
loads transport and statmech databases
"""
from rmgpy.data.statmech import StatmechDatabase
from rmgpy.data.transport import TransportDatabase
#only load if they are not there already.
try:
getDB('transport')
getDB('statmech')
except Dat... | 11,942 |
def get_params_nowcast(
to, tf,
i, j,
path, nconst,
depthrange='None',
depav=False, tidecorr=tidetools.CorrTides):
"""This function loads all the data between the start and the end date that
contains hourly velocities in the netCDF4 nowcast files in the specified
dept... | 11,943 |
def convert_size(size):
""" Helper function to convert ISPMan sizes to readable units. """
return number_to_human_size(int(size)*1024) | 11,944 |
def get_suppressed_output(
detections,
filter_id: int,
iou: float,
confidence: float,
) -> tuple:
"""Filters detections based on the intersection of union theory.
:param detections: The tensorflow prediction output.
:param filter_id: The specific class to be filtered.
:param iou: The int... | 11,945 |
def tf_nan_func(func, **kwargs):
"""
takes function with X as input parameter and applies function only on
finite values,
helpful for tf value calculation which can not deal with nan values
:param func: function call with argument X
:param kwargs: other arguments for func
:return: executed f... | 11,946 |
def deep_update(original,
new_dict,
new_keys_allowed=False,
allow_new_subkey_list=None,
override_all_if_type_changes=None):
"""Updates original dict with values from new_dict recursively.
If new key is introduced in new_dict, then if new_keys_allo... | 11,947 |
def queued_archive_jobs():
"""Fetch the info about jobs waiting in the archive queue.
Returns
-------
jobs: dict
"""
jobs = pbs_jobs()
return [
job
for job in jobs
if (job["job_state"] == "Q" and job["queue"] == "archivelong")
] | 11,948 |
def main():
"""Start execution of the script"""
MiscUtil.PrintInfo("\n%s (RDK v%s; %s): Starting...\n" % (ScriptName, rdBase.rdkitVersion, time.asctime()))
(WallClockTime, ProcessorTime) = MiscUtil.GetWallClockAndProcessorTime()
# Retrieve command line arguments and options...
Retriev... | 11,949 |
def getCustomKernelSolutionObj(kernelName, directory=globalParameters["CustomKernelDirectory"]):
"""Creates the Solution object for a custom kernel"""
kernelConfig = getCustomKernelConfig(kernelName, directory)
for k, v in kernelConfig.items():
if k != "ProblemType":
checkParametersAreVa... | 11,950 |
def test_experimet_wide_results():
"""Test the wide format of results."""
# Clone and fit experiment
experiment = clone(EXPERIMENT).fit(DATASETS)
ds_names = experiment.results_wide_tbl_.dataset_name.unique()
clfs_names = experiment.results_wide_tbl_.classifier.unique()
metric_names = experimen... | 11,951 |
def get_public_key_permissions(session, public_key):
# type: (Session, PublicKey) -> List[Permission]
"""Returns the permissions that this public key has. Namely, this the set of permissions
that the public key's owner has, intersected with the permissions allowed by this key's
tags
Returns:
... | 11,952 |
def remove_files(file_paths: List[str] = None) -> None:
"""Remove all files in the list of file paths.
Args:
file_paths (List[str]): A list of file paths to be deleted.
Returns:
None: None
"""
if not file_paths:
LOGGER.write('file_paths was None or empty, so not removing fi... | 11,953 |
def _format_breed_name(name):
"""
Format breed name for displaying
INPUT
name: raw breed name, str
OUTPUT
name : cleaned breed name, str
"""
return name.split('.')[1].replace('_', ' ') | 11,954 |
def test_create_receipt_with_no_receipt(session):
"""Try creating a receipt with invoice number."""
payment_account = factory_payment_account()
payment = factory_payment()
payment_account.save()
payment.save()
invoice = factory_invoice(payment.id, payment_account.id)
invoice.save()
fee_s... | 11,955 |
def loadIndianPinesData():
"""
加载数据
:return: data, labels
"""
data_path = os.path.join(os.getcwd( ), '../Indian Pines')
data = sio.loadmat(os.path.join(data_path, 'Indian_pines_corrected.mat'))['indian_pines_corrected']
labels = sio.loadmat(os.path.join(data_path, 'Indian_pines_gt.mat'))['in... | 11,956 |
def _get_attribute_accesses_for_control_flow(node, variable):
"""
..code:: python
Pass | Break | Continue
"""
return
yield | 11,957 |
def _lint_js_and_ts_files(
node_path, eslint_path, files_to_lint, result, verbose_mode_enabled):
"""Prints a list of lint errors in the given list of JavaScript files.
Args:
node_path: str. Path to the node binary.
eslint_path: str. Path to the ESLint binary.
files_to_lint: list... | 11,958 |
def create_pid_redirected_error_handler():
"""Creates an error handler for `PIDRedirectedError` error."""
def pid_redirected_error_handler(e):
try:
# Check that the source pid and the destination pid are of the same
# pid_type
assert e.pid.pid_type == e.destination_p... | 11,959 |
def is_var_name_with_greater_than_len_n(var_name: str) -> bool:
"""
Given a variable name, return if this is acceptable according to the
filtering heuristics.
Here, we try to discard variable names like X, y, a, b etc.
:param var_name:
:return:
"""
unacceptable_names = {}
if len(var_... | 11,960 |
def stacked_L(robot: RobotPlanar, q: list, q_goal: list):
"""
Stacks the L matrices for conviencne
"""
LL = []
LLinv = []
Ts_ee = robot.get_full_pose_fast_lambdify(list_to_variable_dict(q))
Ts_goal = robot.get_full_pose_fast_lambdify(list_to_variable_dict(q_goal))
for ee in robot.end_e... | 11,961 |
async def help() -> Dict:
"""Shows this help message."""
return {
'/': help.__doc__,
'/help': help.__doc__,
'/registration/malaysia': format_docstring(get_latest_registration_data_malaysia.__doc__),
'/registration/malaysia/latest': format_docstring(get_latest_registration_data_m... | 11,962 |
def eliminate_arrays(clusters, template):
"""
Eliminate redundant expressions stored in Arrays.
"""
mapper = {}
processed = []
for c in clusters:
if not c.is_dense:
processed.append(c)
continue
# Search for any redundant RHSs
seen = {}
for... | 11,963 |
def data_generator(batch_size):
"""
Args:
dataset: Dataset name
seq_length: Length of sequence
batch_size: Size of batch
"""
vocab_size = 20000
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)
x_train, y_train, x_test, y_test = tf.ragged.constan... | 11,964 |
def now():
""" Get current timestamp
Returns:
str: timestamp string
"""
current_time = datetime.now()
str_date = current_time.strftime("%d %B %Y, %I:%M:%S %p")
return str_date | 11,965 |
def open_mfdataset(
fname,
convert_to_ppb=True,
mech="cb6r3_ae6_aq",
var_list=None,
fname_pm25=None,
surf_only=False,
**kwargs
):
# Like WRF-chem add var list that just determines whether to calculate sums or not to speed this up.
"""Method to open RFFS-CMAQ dyn* netcdf files.
P... | 11,966 |
def projection(projection_matrix: tf.Tensor,
flattened_vector: tf.Tensor) -> tf.Tensor:
"""Projects `flattened_vector` using `projection_matrix`.
Args:
projection_matrix: A rank-2 Tensor that specifies the projection.
flattened_vector: A flat Tensor to be projected
Returns:
A flat Ten... | 11,967 |
def free_vars(e):
"""Get free variables from expression e.
Parameters
----------
e: tvm.relay.Expr
The input expression
Returns
-------
free : List[tvm.relay.Var]
The list of free variables
"""
return _ir_pass.free_vars(e) | 11,968 |
def evaluate(model, epoch, sess, dev_data, vocab, config):
"""
evaluate model.
"""
src_vocab, tgt_vocab = vocab
print('start evaluate...')
total_acc = 0
gold_num = 0
model.dropout = 0
train_batch_iter = create_batch_iter(dev_data,
co... | 11,969 |
def image_as_uint(im, bitdepth=None):
""" Convert the given image to uint (default: uint8)
If the dtype already matches the desired format, it is returned
as-is. If the image is float, and all values are between 0 and 1,
the values are multiplied by np.power(2.0, bitdepth). In all other
situati... | 11,970 |
def unary_operator(op):
"""
Factory function for making unary operator methods for Factors.
"""
# Only negate is currently supported.
valid_ops = {'-'}
if op not in valid_ops:
raise ValueError("Invalid unary operator %s." % op)
@with_doc("Unary Operator: '%s'" % op)
@with_name(u... | 11,971 |
def get_file(
path: str,
skip_hidden: bool = True,
skip_folder: bool = True,
) -> Iterator[str]:
"""
遍历path下的所有文件(不包括文件夹)
:param path: 待遍历的路径
:return: 一个返回文件名的迭代器
"""
for root, ds, fs in os.walk(path):
for file in fs:
file_path = os.path.join(root, fil... | 11,972 |
def _test_sparsify_densify(self, x, default_value):
"""Test roundtrip via Sparsify and Densify."""
numpy_source = in_memory_source.NumpySource(x, batch_size=len(x))()
(sparse_series,) = sparsify.Sparsify(default_value)(numpy_source[1])
(dense_series,) = densify.Densify(default_value)(sparse_series)
cache =... | 11,973 |
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)
Y -- "true" labels vector, of shape (output size... | 11,974 |
def catalog_area(ra=[], dec=[], make_plot=True, NMAX=5000, buff=0.8, verbose=True):
"""Compute the surface area of a list of RA/DEC coordinates
Parameters
----------
ra, dec : `~numpy.ndarray`
RA and Dec. coordinates in decimal degrees
make_plot : bool
Make a figure.
NMAX : in... | 11,975 |
def cli(geotiff_file, meshmask_file, numpy_file, verbosity):
"""Command-line interface for :py:func:`moad_tools.midoss.geotiff_watermask`.
:param str geotiff_file: File path and name of an AIS ship tracks GeoTIFF file to use the
pixel lons/lats from to calculate water mask;
... | 11,976 |
def main():
"""Calculate metrics from collected data, generate plots and tables."""
# metrics and plots for sidechannels
fr = print_sidechannel(
"reload",
start=0,
end=250,
step=5,
threshold=100,
direction="-",
clusters=[(0, 49), (150, 200), (600, 800)... | 11,977 |
def user_page(num_page=1):
"""Page with list of users route."""
form = SearchUserForm(request.args, meta={'csrf': False})
msg = False
if form.validate():
search_by = int(request.args.get('search_by'))
order_by = int(request.args.get('order_by'))
search_string = str(request.args.g... | 11,978 |
def set_status_label(opened, enabled):
"""update status button label to reflect indicated state."""
if not opened:
label = "closed"
elif enabled:
label = "enabled"
else:
label = "disabled"
status_button.set_label(label) | 11,979 |
def validate_input(data: ConfigType) -> dict[str, str] | None:
"""Validate the input by the user."""
try:
SIAAccount.validate_account(data[CONF_ACCOUNT], data.get(CONF_ENCRYPTION_KEY))
except InvalidKeyFormatError:
return {"base": "invalid_key_format"}
except InvalidKeyLengthError:
... | 11,980 |
def _setup_log():
"""Configure root logger.
"""
import logging
import sys
try:
handler = logging.StreamHandler(stream=sys.stdout)
except TypeError: # pragma: no cover
handler = logging.StreamHandler(strm=sys.stdout)
log = get_log()
log.addHandler(handler)... | 11,981 |
def pypi_archive(
name,
package = None,
version = None,
sha256 = None,
strip_prefix = "",
build_file = None,
build_file_content = None,
workspace_file = None,
workspace_file_content = None,
mirrors = None):
"""Downloads and unpacks a Py... | 11,982 |
def delete_person(person_id):
"""Mark as void a person."""
try:
person_detail = get_object_or_404(RegPerson, pk=person_id)
person_detail.is_void = True
person_detail.save(update_fields=["is_void"])
except Exception, e:
raise e | 11,983 |
def file_and_path_for_module(modulename):
"""Find the file and search path for `modulename`.
Returns:
filename: The filename of the module, or None.
path: A list (possibly empty) of directories to find submodules in.
"""
filename = None
path = []
try:
spec = importlib.u... | 11,984 |
def hello_page(request):
"""Simple view to say hello.
It is used to check the authentication system.
"""
text = "Welcome to test_project"
if not request.user.is_anonymous:
text = "Welcome '%s' to test_project" % request.user.username
return HttpResponse(text, content_type='text/plain') | 11,985 |
def hash_all(bv: Binary_View) -> Dict[str, Function]:
"""
Iterate over every function in the binary and calculate its hash.
:param bv: binary view encapsulating the binary
:return: a dictionary mapping hashes to functions
"""
sigs = {}
for function in bv.functions:
sigs[hash_functio... | 11,986 |
def while_n():
""" Lower case Alphabet letter 'n' pattern using Python while loop"""
row = 0
while row<4:
col = 0
while col<3:
if row==0 and col in (0,1) or row>0 and col%2==0:
print('*', end = ' ')
... | 11,987 |
def apply_deformation(
deformation_indices: Union[List[bool], np.ndarray], bsf: np.ndarray
) -> np.ndarray:
"""Return Hadamard-deformed bsf at given indices."""
n = len(deformation_indices)
deformed = np.zeros_like(bsf)
if len(bsf.shape) == 1:
if bsf.shape[0] != 2*n:
raise ValueE... | 11,988 |
def index(request):
"""Return the index.html file"""
return render(request, 'index.html') | 11,989 |
def execute(cx, stmt, args=(), return_result=False):
"""
Execute query in 'stmt' over connection 'cx' (with parameters in 'args').
Be careful with query statements that have a '%' in them (say for LIKE)
since this will interfere with psycopg2 interpreting parameters.
Printing the query will not pr... | 11,990 |
def parse_custom_builders(builders: Optional[Iterable[str]]) -> Dict[str, Type[AbstractBuilder]]:
"""
Parse the custom builders passed using the ``--builder NAME`` option on the command line.
:param builders:
"""
custom_builders: Dict[str, Type[AbstractBuilder]] = {}
if builders is None:
return custom_builde... | 11,991 |
def construct_user_rnn_inputs(document_feature_size=10,
creator_feature_size=None,
user_feature_size=None,
input_reward=False):
"""Returns user RNN inputs.
Args:
document_feature_size: Integer, length of document features... | 11,992 |
def numpy_read(DATAFILE, BYTEOFFSET, NUM, PERMISSION, DTYPE):
"""
Read NumPy-compatible binary data.
Modeled after MatSeis function read_file in util/waveread.m.
"""
f = open(DATAFILE, PERMISSION)
f.seek(BYTEOFFSET, 0)
data = np.fromfile(f, dtype=np.dtype(DTYPE), count=NUM)
f.close()
... | 11,993 |
def _process_pmid(s: str, sep: str = '|', prefix: str = 'pubmed:') -> str:
"""Filter for PubMed ids.
:param s: string of PubMed ids
:param sep: separator between PubMed ids
:return: PubMed id
"""
for identifier in s.split(sep):
identifier = identifier.strip()
if identifier.start... | 11,994 |
def main(known_file, comparison, output_type):
"""
The main function handles the main operations of the script
:param known_file: path to known file
:param comparison: path to look for similar files
:param output_type: type of output to provide
:return: None
"""
# Check output formats
... | 11,995 |
def _classictautstring_TV1(x, w, y, **kwargs):
"""Classic taut string method for TV1 proximity"""
_call(lib.classicTautString_TV1, x, np.size(x), w, y) | 11,996 |
def _get_import(name, module: ast.Module):
"""
get from import by name
"""
for stm in ast.walk(module):
if isinstance(stm, ast.ImportFrom):
for iname in stm.names:
if isinstance(iname, ast.alias):
if iname.name == name:
retu... | 11,997 |
def load_FIPS_data():
""" Load FIPS ref table """
directory = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
filename = os.path.join(directory, 'ref_data', 'FIPS_ref_data.csv')
df = pd.read_csv(filename)
df['fips'] = df['fips'].astype(str)
return df | 11,998 |
def show_stats(number):
"""
Display stats
@param number number of times we ran the simulation
"""
average = SimInterface.score_total / number
print(f"Average Score: {average:8.3f}")
print(f" Best Score: {SimInterface.minscore:4d}")
print(f" Worst Score: {SimInterface.maxscore:4d}")
... | 11,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.