content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_raises_without_scheme() -> None:
"""Ensure that `chrome_cookies("domain.com")` raises.
The domain must specify a scheme (http or https).
"""
with pytest.raises(URLError):
chrome_cookies("n8henrie.com") | 5,325,400 |
def user_has_registered(userID):
"""Checks if a particular user has been registered in database"""
database = sqlite3.connect("users.db")
cursor = database.cursor()
cursor.execute(f"SELECT user_id FROM profile WHERE user_id = {userID}")
result = cursor.fetchone()
if result is None:
... | 5,325,401 |
def prepare_ocp(
biorbd_model_path: str,
final_time: float,
n_shooting: int,
marker_velocity_or_displacement: str,
marker_in_first_coordinates_system: bool,
control_type: ControlType,
ode_solver: OdeSolver = OdeSolver.RK4(),
) -> OptimalControlProgram:
"""
Prepare an ocp that targets... | 5,325,402 |
def add_dependencies(dependencies, script_path, encountered_internal_modules, prefix="", debug=False):
"""
This function ...
:param dependencies:
:param script_path:
:param encountered_internal_modules:
:param prefix:
:return:
"""
# Skip files that are not python scripts
if not... | 5,325,403 |
def key_gen(**kwargs):
"""
Key generator for linux. Determines key based on
parameters supplied in kwargs.
Keyword Parameters:
@keyword geounit1: portable_id of a geounit
@keyword geounit2: portable_id of a geounit
@keyword region: region abbreviation
"""
if 'geounit1' in kwargs and... | 5,325,404 |
def find(bindings: List[Binding], name: str) -> Optional[Binding]:
"""
Returns a Binding with a given name. Comparison is case-insensitive.
:param bindings: the Bindings to find in
:param name: the name of the Binding to find
:return: the Binding with a given name if it exists, None otherwise
... | 5,325,405 |
def computeResult():
"""Allows download of asset data result file.
---
tags:
- services
consumes:
- application/json
parameters:
- name: consumerAddress
in: query
description: The consumer address.
required: true
type: string
- name: jobId
... | 5,325,406 |
async def test_upgraded_extended_version_async_analysis_module(manager):
"""Tests the ability of an analysis module to update extended version data."""
#
# in this case the first call to get_next_analysis_request fails
# but the module.upgrade() is called
# since the work task is not acquired it st... | 5,325,407 |
async def init_menu_perms(request: Request) -> Dict:
"""
初始化菜单和权限
"""
return await services.init_menu_perms(request) | 5,325,408 |
def bert_process_sentence(example_tokens, max_seq_length, tokenizer):
"""
Tokenization and pre-processing of text as expected by Bert
Parameters
----------
example_tokens
max_seq_length
tokenizer
Returns
-------
"""
# Account for [CLS] and [SEP] with "- 2"
if len(examp... | 5,325,409 |
def executor_callback(future):
"""The callback function called when a job has completed."""
ticket, result, job_type, success, comment = future.result()
if result is not None:
rel_path = datetime.now().strftime("%y%m%d")
rel_path = path.join(rel_path, ticket)
output_path: str = path.... | 5,325,410 |
def neighbors():
"""Show vnet neighbors information"""
config_db = ConfigDBConnector()
config_db.connect()
header = ['<vnet_name>', 'neighbor', 'mac_address', 'interfaces']
# Fetching data from config_db for interfaces
intfs_data = config_db.get_table("INTERFACE")
vlan_intfs_data = config_... | 5,325,411 |
async def test_config_entry_authentication_failed(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_tailscale: MagicMock,
) -> None:
"""Test trigger reauthentication flow."""
mock_config_entry.add_to_hass(hass)
mock_tailscale.devices.side_effect = TailscaleAuthenticationError
... | 5,325,412 |
def weight_diff(w1, w2):
""" Calculates the array of differences between the weights in arrays """
# Expand and flatten arrays
_w1 = np.hstack([x.flatten() for x in w1])
_w2 = np.hstack([x.flatten() for x in w2])
return _w1 - _w2 | 5,325,413 |
def get_root_modules():
"""
Returns a list containing the names of all the modules available in the
folders of the pythonpath.
"""
rootmodules_cache = XSH.modules_cache
rootmodules = list(sys.builtin_module_names)
start_time = time()
for path in sys.path:
try:
modules... | 5,325,414 |
def copy_fillmem_to_rootfs(rootfs_path):
"""Build and copy the 'memfill' program to the rootfs."""
subprocess.check_call("gcc ./host_tools/fillmem.c -o fillmem", shell=True)
subprocess.check_call("mkdir tmpfs", shell=True)
subprocess.check_call("mount {} tmpfs".format(rootfs_path), shell=True)
subpr... | 5,325,415 |
def advect_salinity(vs):
"""
integrate salinity
"""
return advect_tracer(vs, vs.salt[..., vs.tau], vs.dsalt[..., vs.tau]) | 5,325,416 |
def lafferty_wyatt_point(lowedge, highedge, expo_slope):
"""calculates the l-w point for a bin where the true distribution is an
exponential characterized by expo_slope.
"""
import math
rhs = (math.exp(expo_slope*highedge) - math.exp(expo_slope*lowedge))
rhs /= expo_slope
rhs /= (highedge -... | 5,325,417 |
def _event_loop() -> Iterator[asyncio.AbstractEventLoop]:
"""Yield an event loop.
This is necessary because pytest-asyncio needs an event loop with a with an equal or higher
pytest fixture scope as any of the async fixtures. And remember, pytest-asynio is what allows us
to have async pytest fixtures.
... | 5,325,418 |
def init_critical_cases_20():
"""
Real Name: b'init Critical Cases 20'
Original Eqn: b'0'
Units: b'person'
Limits: (None, None)
Type: constant
b''
"""
return 0 | 5,325,419 |
def view_last_build_times():
"""Find build manifests and display to stdout."""
build_manifests = dict()
for root, _dirs, files in os.walk(SCRIPT_DIR):
if 'manifest.json' in files and 'box_info.json' in files:
box_info = os.path.join(root, 'box_info.json')
try:
... | 5,325,420 |
def preview_on():
"""Turn the preview on """
print
print preview_on.__doc__
command_send('camera', 'PV', '02') | 5,325,421 |
def build_doc(pic_dic):
"""
Gets dict {'image-name':['image-path',text]} ==> doc obj
"""
doc = word_obj()
# Add footer
doc.sections[0].footer.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
add_page_number(doc.sections[0].footer.paragraphs[0].add_run())
# Started Page
starter... | 5,325,422 |
async def register(app: web.Application):
"""Register routes."""
app.add_routes(
[web.post("/connections/{id}/start-introduction", introduction_start)]
) | 5,325,423 |
def save_object(obj, filename, tries=2, sleep_delay=3):
"""
Serialize an object
Parameters
----------
obj : object
object, that shall be serialized and stored
filename : str
absolute path, name and extension of the created file
tries : int
number of attempts to sto... | 5,325,424 |
def dispatch_every_hour(one_time_password):
""" This is the receiving point of start_every_hour's post request. It
checks that the one time password is correct and then dispatches
every_hour. """
EveryHourOTP.check_password(one_time_password)
Process(target=every_hour).start()
return "s... | 5,325,425 |
def check_list(data):
"""check if data is a list, if it is not a list, it will return a list as [data]"""
if type(data) is not list:
return [data]
else:
return data | 5,325,426 |
def test_to_float(input_value: FixedPoint, correct_output: float) -> None:
"""
Test whether the __float__ function works correctly
:param input_value: fixed-point number
:param correct_output: correct float cast of the fixed-point number
"""
output = float(input_value)
assert output == corr... | 5,325,427 |
def nfvi_reinitialize(config):
"""
Re-initialize the NFVI package
"""
global _task_worker_pools
init_complete = True
compute_plugin_disabled = (config.get('compute_plugin_disabled',
'False') in DISABLED_LIST)
if not compute_plugin_disabled:
... | 5,325,428 |
def parse_freqs(lines, parameters):
"""Parse the basepair frequencies.
"""
root_re = re.compile("Note: node (\d+) is root.")
branch_freqs_found = False
base_freqs_found = False
for line in lines:
# Find all floating point numbers in this line
line_floats_res = line_floats_re.find... | 5,325,429 |
def student2nation(id_num):
"""
Takes student id, returns nation id of the student.
"""
return school2nation(id_num) | 5,325,430 |
def get_projects_with_builds(only_public=True, only_active_versions=True):
"""Returns a queryset of Projects with active only public by default builds."""
builds = Build.objects.filter(
success=True,
state='finished',
version__active=True
)
if only_public:
builds = builds... | 5,325,431 |
def encode_base64(filename):
"""encode image to string.
Args
filename: image file path.
Returns:
a bites string.
"""
with open(filename, "rb")as f:
bs64 = base64.b64encode(f.read()).decode()
return bs64 | 5,325,432 |
def transfer_from_taoyuanagrichannel_to_taoyuanagriwaterdemand():
"""
Real Name: Transfer From TaoYuanAgriChannel To TaoYuanAgriWaterDemand
Original Eqn: (Transfer From ShiMenReservoir To HouChiWeir*Ratio AgriWater ShiMenReservoir To HouChiWeir In TaoYuanAgriChannel)*(1-Channel Transfer Loss Rate )
Unit... | 5,325,433 |
async def test_update_attributes(update_requests_mock_fixture, hass):
"""Test the drycontact binary sensor attributes are updated."""
await setup_platform(hass, BINARY_SENSOR_DOMAIN)
state = hass.states.get("binary_sensor.main_door_drycontact")
assert state.state == STATE_ON
assert state.attributes... | 5,325,434 |
def Doxyfile_emitter(target, source, env):
"""
Modify the target and source lists to use the defaults if nothing
else has been specified.
Dependencies on external HTML documentation references are also
appended to the source list.
"""
doxyfile_template = env.File(env['DOXYFILE_FILE'])
source.in... | 5,325,435 |
def test_cli_token_file():
"""Test the token command."""
runner = CliRunner()
path = os.path.dirname(os.path.abspath(__file__))
key_file = os.path.join(path, 'auth', 'test.key')
result = runner.invoke(btutils.main, args=['-f', key_file, 'token'])
assert result.exit_code == 0 | 5,325,436 |
def _recursive_make_immutable(o):
"""Recursively transform an object into an immutable form
This is a cdev core specific transformation that is used to convert Dict and List and other native python
types into frozendict, frozenset, etc. The purpose is that the later set of objects are immutable in python
... | 5,325,437 |
def retry_condition(exception):
"""Return True if we should retry (in this case when it's an IOError), False otherwise"""
if isinstance(exception, (HTTPError, AttributeError)):
print(f'HTTP error occurred: {exception}') # Python 3.6
return True
return False | 5,325,438 |
def mergesort(input_arr):
"""
Sort the array by application of merge sort
Time complexity: O(n log(n))
Space Complexity: O(n)
Args:
input_arr(array): Input array with numbers to be sorted
Returns:
sorted_arr(array) Sorted array with numbers in ascending order
... | 5,325,439 |
def _clean_annotated_text(text):
"""Cleans text from the format that it was presented to annotators in the
S.M.A.R.T data annotation tool. Splits the title from the abstract text
and strips any trailing whitespace.
Returns:
title (str): The project title
text (str): The project abstra... | 5,325,440 |
def build_test_costs():
"""
Build test costs
"""
extra_layers = {'layers':
{'transmission_barrier':
os.path.join(TESTDATADIR, 'xmission',
'ri_trans_barriers.tif')}}
XmissionCostCreator.run(BASELINE_H5, ISO_REGIONS_F, excl_h5=... | 5,325,441 |
def get_or_create_event_loop():
"""
Tries to get the current event loop. If not found creates a new one.
Returns
-------
event_loop : ``EventThread``
"""
try:
event_loop = get_event_loop()
except RuntimeError:
event_loop = create_event_loop(daemon=False)
ret... | 5,325,442 |
def tnaming_Displace(*args):
"""
* Application de la Location sur les shapes du label et de ses sous labels.
:param label:
:type label: TDF_Label &
:param aLocation:
:type aLocation: TopLoc_Location &
:param WithOld: default value is Standard_True
:type WithOld: bool
:rtype: void
... | 5,325,443 |
def main():
""" Set up the game and run the main game loop """
pygame.init() # Prepare the pygame module for use
surfaceSize = 480 # Desired physical surface size, in pixels.
clock = pygame.time.Clock() #Force frame rate to be slower
# Create surface of (width, height), and its w... | 5,325,444 |
def temp_database(con, test_data_db: str) -> typing.Generator[str, None, None]:
"""Create a temporary database.
Parameters
----------
con : ibis.heavyai.HeavyDBClient
test_data_db : str
Yields
------
str
"""
name = _random_identifier('database')
con.create_database(name)
... | 5,325,445 |
def get_capital_np(markets,signals,size,commiRate,climit = 4, wlimit = 2, op=True):
"""使用numpy回测,标签的盈亏, op 表示是否延迟一个tick以后撮合"""
postions = np.zeros(len(signals))
actions = np.zeros(len(signals))
costs = np.zeros(len(signals))
pnls = np.zeros(len(signals))
lastsignal = 0
l... | 5,325,446 |
def slicename_to_hostname(vs_name):
"""Converts a vserver slice name into a canonical FQDN.
Slice names use a pattern like: <some site>_<some name>.
Example:
If vs_name is 'mlab_utility' and the system hostname is
'mlab4.nuq01.measurement-lab.org', then slicename_to_hostname will return
'utility.m... | 5,325,447 |
def unregister_server(zkclient, hostname):
"""Unregister server."""
_LOGGER.info('Unregistering server %s', hostname)
server_presence_path = find_server(zkclient, hostname)
if server_presence_path:
zkutils.ensure_deleted(zkclient, server_presence_path) | 5,325,448 |
def swim_for_a_day(life_counts: Dict[int, int]):
"""Process the shoal, decrement the life_counts:
any that get to -1 have procreated in the last day, their offspring are
created with 8 day life_counts, whilst they get reset to 6 days… and are
added to the count of any fish that moved down from 7 days.
... | 5,325,449 |
def page_not_found (error):
"""
Generic Error Message
"""
return "Unable to find Distill." | 5,325,450 |
def dict_to_obj(our_dict):
"""
Function that takes in a dict and returns a custom object associated with
the dict. This function makes use of the "__module__" and "__class__"
metadata in the dictionary to know which object type to create.
"""
if "__class__" in our_dict:
# Pop ensures we... | 5,325,451 |
def test_generate_model_circuit_seed():
"""Test that a model circuit is determined by its seed ."""
model_circuit_1 = quantum_volume.generate_model_circuit(
3, 3, random_state=np.random.RandomState(1))
model_circuit_2 = quantum_volume.generate_model_circuit(
3, 3, random_state=np.random.Rand... | 5,325,452 |
def soup(path):
"""
分解新聞
"""
print('-' * 75)
nsoup = NewsSoup(path)
print('原始路徑: {}'.format(path))
print('最終路徑: {}'.format(nsoup.path))
print('頻道: {}'.format(nsoup.channel))
print('標題: {}'.format(nsoup.title()))
ndt = nsoup.date()
if ndt is not None:
print('日期: {}'.fo... | 5,325,453 |
def display_fips( collection_of_fips, fig, **kwargs ):
"""
Method that is very similar to :py:meth:`display_fips_geom <covid19_stats.engine.viz.display_fips_geom>`, except this *also* displays the FIPS code of each county. For example, for `Rhode Island`_, this is.
.. _viz_display_fips_rhodeisland:
... | 5,325,454 |
def write_html_header(file):
"""Write HTML header."""
message = """
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="./resources/kanban.css">
<title>KanbanView for Things 3</tit... | 5,325,455 |
def _apply_constraints(password_hash, size, is_non_alphanumeric):
"""
Fiddle with the password a bit after hashing it so that it will
get through most website filters. We require one upper and lower
case, one digit, and we look at the user's password to determine
if there should be at least one alph... | 5,325,456 |
def SplitLineRecursive(linepts,i,j,THRESHOLD=5.0,ds_min=50.0):
"""
Choose best point at which to split a line to minimize total reprojection error
"""
max_err = np.max(ProjectionError(np.stack((linepts[:,i],linepts[:,j])).T, linepts[:,i:j]))
if max_err < THRESHOLD:
ds = np.cumsum(np.sqrt(np.... | 5,325,457 |
def create_report() -> FlaskResponse:
"""Creates a new report.
Note: This is the existing implementation, currently used for the v1 endpoint.
Returns:
FlaskResponse: details of the report just created or a list of errors with the corresponding HTTP status code.
"""
logger.info("Creating a ... | 5,325,458 |
def get_arguments():
"""Parsing the arguments"""
parser = argparse.ArgumentParser(description="",
usage='''
______________________________________________________________________
BiG-MAP map: maps the reads to the predicted MGCs
______________________________________________________________________
Gen... | 5,325,459 |
def sample_exercise():
"""Create a sample exercise"""
return ExerciseModel.objects.create(
name='exercise name',
duration=10,
calories=10
) | 5,325,460 |
def test_message_defaults():
"""
Test that message defaults are applied when the corresponding arguments have been omitted.
"""
mailer = DummyMailer(subject='default_subject', sender='default_sender@example.org',
to='default_recipient@example.org', cc='default_cc@example.org',
... | 5,325,461 |
def der_kinetic_integral(a,bfi,bfj):
"""
The kinetic energy operator does not depend on the atomic position so we only
have to consider differentiating the Gaussian functions. There are 4 possible
cases we have to evaluate
Case 1: Neither of the basis functions depends on the position of... | 5,325,462 |
def get_celeba():
"""Get and preprocess the CelebA dataset.
"""
transform = transforms.Compose([
transforms.Resize((64, 64)),
transforms.ToTensor()])
# Use only 18/40 labels as described in Appendix C.1
mask = torch.tensor(
[False, True, False, True, False, True, False, False... | 5,325,463 |
def waa_adjust_baseline(rsl, baseline, wet, waa_max, delta_t, tau):
"""Calculate baseline adjustion due to wet antenna
Parameters
----------
rsl : iterable of float
Time series of received signal level
baseline : iterable of float
Time series of ... | 5,325,464 |
def linear_warmup_decay(learning_rate, warmup_steps, num_train_steps):
""" Applies linear warmup of learning rate from 0 and decay to 0."""
with fluid.default_main_program()._lr_schedule_guard():
lr = fluid.layers.tensor.create_global_var(
shape=[1],
value=0.0,
dtype=... | 5,325,465 |
def _save_name(name):
"""Saves the dictionary as intervalTree files"""
for letter in name:
directory = './pkl/name/' + letter + '.pkl'
with open(directory, 'wb') as f:
pickle.dump(name[letter], f, -1)
print("Saved to " + directory) | 5,325,466 |
def update_mailing_list_extended(mailing_list):
"""
Your docstring documentation starts here.
For more information on how to proper document your function, please refer to the official PEP8:
https://www.python.org/dev/peps/pep-0008/#documentation-strings.
"""
# Checks it ... | 5,325,467 |
def poll(server):
"""
Function for polling the LP servers and getting the results
calls handle for everything it recieves
"""
while True:
try:
#Figure out everthing we need
url = known[server]
username, password = get_single_worker(server)
... | 5,325,468 |
def space2():
"""Create a Space with two real dimensions."""
space = Space()
space.register(Real("lr", "uniform", 0, 1))
space.register(Real("weight_decay", "uniform", 0, 1))
return space | 5,325,469 |
def calculate_thresh(twindow, pctile, skipna):
"""Calculate threshold for one cell grid at the time
Parameters
----------
twindow: xarray DataArray
Stacked array timeseries with new 'z' dimension representing
a window of width 2*w+1
pctile: int
Threshold percentile used to d... | 5,325,470 |
def current_url(request, driver, login_action, login_page):
"""Use login button element depends from browser and get current page url"""
browser_name = request.config.getoption("--browser")
print(browser_name)
if browser_name == "firefox":
login_page.login()
driver.implicitly_wait(1)
... | 5,325,471 |
def iterparshios(year, israel=False):
"""Generate all the parshios in the year.
Parameters
----------
year : int
The Hebrew year to get the parshios for.
israel : bool, optional
``True`` if you want the parsha according to the Israel schedule
(with only one day of Yom Tov). Defau... | 5,325,472 |
def test():
"""Test code."""
# Baud rate of 14500000 seems about the max
spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))
x, y = 0, 0
angle = 0.0
# Loop all angles from 0 to 2 * PI radians
while angle < PI2:
#... | 5,325,473 |
def edit_car(item_id):
"""
Edit item
:param item_id:
:return mix:
"""
# get user
user = get_user_by_id(session['uid'])
# Get car
car = get_item_by_id(item_id)
# Check the user is the owner
if int(session['uid']) != int(car.author):
flash('You don\'t have permissio... | 5,325,474 |
def preprocess_until_max_index(nw_name, max_index, number_cores = 1, network_dynamics_file = None):
""" computes the preprocessed travel time tables for all different travel time files
creates the travel time tables "tt_matrix" and "dis_matrix" and stores them
in the network-folder
:param network_name: ... | 5,325,475 |
def replace_ensembl_ids(expression_df, gene_id_mapping):
"""
Replaces ensembl gene ids with hgnc symbols
Arguments
---------
expression_df: df
gene expression data matrix (sample x gene)
gene_id_mapping: df
Dataframe mapping ensembl ids (used in DE_stats_file) to hgnc symbols,
... | 5,325,476 |
def MPC_SelectModulationGeneration(pattern_index: int,
mode: ModulationShapeMode) -> None:
"""Selects the customizable modulation mode or the classical linear mode
Parameters
----------
pattern_index : int
Pattern index
mode : ModulationShapeMode
M... | 5,325,477 |
async def get_latency(ctx: Context) -> dict[str, str]:
"""
Get the bot's latency and database latency.
Parameters
----------
ctx : Context
The context.
"""
now = perf_counter()
collection = ctx.bot.db['test']['TESTS']
if await collection.find_one({'_id': PAYLOAD['_id']}) ... | 5,325,478 |
def ssl_allowed(fn):
"""
Decorator - marks a route as allowing ssl, but not requiring it. It can be served over http and https.
NOTE: This must go BEFORE the route!
"""
fn.ssl_allowed = True
return fn | 5,325,479 |
def _get_visible_photos(browser, known_urls):
"""
extracts all *currently visible* photo URLs from a Flickr photoset/album
page, converts them into "embed code compatible" (i.e. sanctioned by
Flickr) URLs and returns them.
Parameters
----------
browser : TODO ???
a selenium webdrive... | 5,325,480 |
def get_parser():
""" return a parser """
parser = argparse.ArgumentParser("cli")
parser.add_argument('registryimage', help="registry/image:tag - tag is optional")
# Username and password come last to make them optional later
parser.add_argument('username', help='username')
parser.add_argument('... | 5,325,481 |
def fold_with_enum_index(xtypes, x):
"""
see MixedIntegerContext.fold_with_enum_index
"""
x = np.atleast_2d(x)
xfold = np.zeros((x.shape[0], len(xtypes)))
unfold_index = 0
for i, xtyp in enumerate(xtypes):
if xtyp == FLOAT or xtyp == INT:
xfold[:, i] = x[:, unfold_index]
... | 5,325,482 |
def unlock(arguments):
"""Unlock the database."""
import redis
u = coil.utils.ask("Redis URL", "redis://localhost:6379/0")
db = redis.StrictRedis.from_url(u)
db.set('site:lock', 0)
print("Database unlocked.")
return 0 | 5,325,483 |
def unzip_recursive(zipped_file, to_folder, set_remove=True):
"""
Function that recursively goes through folders and unpacks zips inside them.
All unzipped files are stored in the same folder (output_folder)
"""
logger.debug("Unzipping {} to {}".format(zipped_file, to_folder))
with zipfile.ZipFi... | 5,325,484 |
def filter_atom_tokens(entity: SerializableEntity) -> bool:
"""
When locating tokens for equations, only detect atom tokens (i.e., skipping affix tokens like
arrows and hats), because affixes be colorized by wrapping them in colorization commands.
"""
token = cast(SerializableToken, entity)
retu... | 5,325,485 |
def handle_subliminal_download(video, video_path, languages_to_retrieve):
""" # Download the best subtitles in french and english
Args:
video : Name of video
video_path: absolute path to videos
languages_to_retrieve : dict of subtitles languages to retrieve
return : two dicts... | 5,325,486 |
def xmp_extract(fns, type_map):
"""xmp_extract
:param fns:
:param type_map:
"""
logger.info("Extracting raw XMP data.")
func = partial(xmp_to_vec, type_map=type_map)
xmp_to_vec(fns[0], type_map=type_map)
xmp_data = imap_unordered_bar(func, fns, n_proc=2)
xmp_data = pd.DataFrame(xmp_... | 5,325,487 |
def fisbUnavailable(db):
"""Create string containing any FIS-B Unavailable messages.
Args:
db (object): Handle to database connection.
Returns:
str: Containing any FIS-B Unavailable information.
"""
if SHOW_UNAVAILABLE == False:
return ''
fisbStr = ''
for r in... | 5,325,488 |
def log_get():
""" Parses JSON log file and sends it to the web server """
log(bottle.request)
logbuf = []
try:
if os.path.exists('log.json'):
with open('log.json') as infile:
logbuf = json.load(infile)
except (ValueError, IOError) as e:
error(e)
... | 5,325,489 |
def rotate_file(filename, copy=False):
"""
Rotate file like logrotate.
If given filename already exists, rename it to "filename".n, n=1...
Filename with larger n is older one.
"""
# If not exist,
if not os.path.isfile(filename):
return
# make list [ [filename, number], ... ]
... | 5,325,490 |
def change_master(host, confirm=False):
"""
Change to different master host.
Arguments:
- host (str): Hostname of the new master to change to.
Optional arguments:
- confirm (bool): Acknowledge the execution of this command. Default is 'False'.
"""
if not confirm:
raise sal... | 5,325,491 |
def decode_text(s):
"""
Decodes a PDFDocEncoding string to Unicode.
Adds py3 compatability to pdfminer's version.
"""
if type(s) == bytes and s.startswith(b'\xfe\xff'):
return six.text_type(s[2:], 'utf-16be', 'ignore')
else:
ords = (ord(c) if type(c) == str else c for c in s)
... | 5,325,492 |
def normalize_bound(sig, lb=0, ub=1):
"""
Normalize a signal between the lower and upper bound.
Parameters
----------
sig : ndarray
Original signal to be normalized.
lb : int, float, optional
Lower bound.
ub : int, float, optional
Upper bound.
Returns
------... | 5,325,493 |
def test_create_publish_new_revision(
client_with_login,
location,
minimal_record,
identity_simple,
headers,
):
"""Test draft creation of an existing record and publish it."""
client = client_with_login
recid = _create_and_publish(client, minimal_record, headers)
# # FIXME: Allow ES... | 5,325,494 |
def get_chisqr3d(res3d):
"""Extract fit3d result chisqr attribute into a 3d volume
Args:
res3d -- 3d numpy array of model.ModelResult; output of fit3d
Return:
attr3d -- numpy arrays of chi-square statistics of fit
"""
# create empty array
data_type = type(res3d[0,0,0].chisqr)
... | 5,325,495 |
def detect_Telephony_SMS_abuse(x) :
"""
@param x : a VMAnalysis instance
@rtype : a list of formatted strings
"""
formatted_str = []
structural_analysis_results = x.tainted_packages.search_methods("Landroid/telephony/SmsManager","sendTextMessage", ".")
#structural_analysis_results = x.tainted_packa... | 5,325,496 |
def depth_map_to_point_cloud(
depth_map: torch.Tensor,
valid_map: Optional[torch.Tensor],
focal_x: float,
focal_y: float,
center_x: float,
center_y: float,
trunc_depth_min: Optional[float],
trunc_depth_max: Optional[float],
flip_h: bool = True,
device: Optional[torch.device] = None,
_validate_args... | 5,325,497 |
async def admin_cmd_ping(message: discord.Message, args: str, isDM: bool):
"""admin command testing bot latency.
:param discord.Message message: the discord message calling the command
:param str args: ignored
:param bool isDM: Whether or not the command is being called from a DM channel
"""
st... | 5,325,498 |
def symbol_definitions(goto, wkdir, srcdir=None):
"""Symbol definitions appearing in symbol table.
Source file path names in symbol table are absolute or relative to
wkdir. If srcdir is given, return only symbols defined in files
under srcdir.
"""
wkdir = srcloct.abspath(wkdir)
srcdir = s... | 5,325,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.