content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def solver_wrapper(term_spec_list, solver_opts, chain_opts, **kwargs):
"""A Python wrapper for the solvers written in Numba.
This wrapper facilitates getting values in and out of the Numba code and
creates a dictionary of results which can be understood by the calling
Dask code.
Args:
**kw... | 49,700 |
def POST(request):
"""Add a new Topology to the specified project and return it"""
request.check_required_parameters(path={'projectId': 'string'}, body={'topology': {'name': 'string'}})
project = Project.from_id(request.params_path['projectId'])
project.check_exists()
project.check_user_access(re... | 49,701 |
def do_host_evacuate_live(cs, args):
"""Live migrate all instances off the specified host
to other available hosts.
"""
response = []
migrating = 0
for server in _hyper_servers(cs, args.host, args.strict):
response.append(_server_live_migrate(cs, server, args))
migrating = migrat... | 49,702 |
def die(msg='Something bad happened'):
"""log a critical message() and exit with error"""
logging.critical(msg)
sys.exit(1) | 49,703 |
def deconvolve_channel(channel):
"""Deconvolve a single channel."""
y_pad = jax.device_put(ray.get(y_pad_list)[channel])
psf = jax.device_put(ray.get(psf_list)[channel])
mask = jax.device_put(ray.get(mask_store))
M = linop.Diagonal(mask)
C0 = linop.CircularConvolve(
h=psf, input_shape=ma... | 49,704 |
def seg_ventricles(paths: dict, settings: dict, verbose: bool = True) \
-> tuple[dict, dict]:
"""
This function performs the ventricle segmentation.
It has two variations, one of which is the FreeSurfer
based implementation, which builds upon previously run
FreeSurfer output. The other varia... | 49,705 |
def sell():
"""Sell shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol").upper()
shares = request.form.get("shares")
stock = lookup(symbol)
if (stock == None) or (symbol == ''):
return apology("Stock was not found.")
elif not sha... | 49,706 |
def _compute_third(first, second):
""" Compute a third coordinate given the other two """
return -first - second | 49,707 |
def sides(poly: Geometry) -> Iterable[Geometry]:
""" Returns a sequence of Geometry[Line] objects.
One for each side of the exterior ring of the input polygon.
"""
XY = poly.exterior.points
crs = poly.crs
for p1, p2 in zip(XY[:-1], XY[1:]):
yield line([p1, p2], crs) | 49,708 |
def decipher(criptotext):
"""
Descifra el mensaje recuperando el texto plano siempre y cuando haya
sido cifrado con XOR.
Parámetro:
cryptotext -- el mensaje a descifrar.
"""
messagedecrip = ""
for elem in criptotext:
code = ord(elem)^1
messagedecrip += chr(code)
return messaged... | 49,709 |
def call_jiffy(jiffy, fam_file, outdir=None):
"""
This function was designed to call the perl script defined by the jiffy
parameter. Used in Rfam 12.1 with jiffies writeAnnotatedCM.pl,
writeAnnotatedSeed.pl and writeAnnotatedTree.pl to generate CM, SEED
and seed_Tree files for the FTP server
ji... | 49,710 |
def mag(initial, final):
"""
calculate magnification for a value
"""
return float(initial) / float(final) | 49,711 |
def fetch_ids(product: str, use_usgs_ftp: bool = False) -> [str]:
"""Returns all ids for the given product."""
if use_usgs_ftp:
return _fetch_ids_from_usgs_ftp(product)
else:
return _fetch_ids_from_aws(product) | 49,712 |
def to_be_implemented(request):
"""
A notice letting the user know that this particular feature hasn't been
implemented yet.
"""
pagevars = {
"page_title": "To Be Implemented...",
}
return render(request, 'tbi.html', pagevars) | 49,713 |
def unet_brain_connector(wf, cfg, strat_pool, pipe_num, opt):
"""
UNet
options (following numbers are default):
input_slice: 3
conv_block: 5
kernel_root: 16
rescale_dim: 256
"""
unet_mask = pe.Node(util.Function(input_names=['model_path', 'cimg_in'],
... | 49,714 |
def ganache_second_account(smart_contracts_dir: str):
"""
Returns the second ganache account.
Useful for doing transfers so you can transfer to an
ethereum address that doesn't have anything to do with
paying gas fees.
"""
return ganache_accounts(smart_contracts_dir)["accounts"][1].lower() | 49,715 |
def _parse_list_of_lists(string, delimiter_elements=',', delimiter_lists=':', delimiter_pipelines=';', dtype=float):
""" Parses a string that contains single or multiple lists.
Args:
delimiter_elements <str>: delimiter between inner elements of a list.
delimiter_lists <str>: delimiter between l... | 49,716 |
def get_available_dictionaries() -> List[str]:
"""
Return a list of all available dictionaries
Returns
-------
List[str]
Saved dictionaries
"""
return get_available_models("dictionary") | 49,717 |
def get_unscoped_token(os_auth_url, access_token, username, tenant_name):
"""
Get an unscoped token from an access token
"""
url = get_keystone_url(os_auth_url,
'/v3/OS-FEDERATION/identity_providers/%s/protocols/%s/auth' % (username, tenant_name))
response = requests.post(... | 49,718 |
def ppg_at_multiple_frequency_test():
"""
Place the finger/wrist on the optical window
:return:
"""
capture_time = 40
freq_list_hz = [500, 100, 50]
common.easygui.msgbox('Make sure watch is on the wrist and press OK', 'PPG')
# ADPD Stream with AGC ON
append_report = False
for i,... | 49,719 |
def _pfa_check_stdeskew(PFA, Grid):
"""
Parameters
----------
PFA : sarpy.io.complex.sicd_elements.PFA.PFAType
Grid : sarpy.io.complex.sicd_elements.Grid.GridType
Returns
-------
bool
"""
if PFA.STDeskew is None or not PFA.STDeskew.Applied:
return True
cond = True
... | 49,720 |
def get_user(home_at=('/home', '/var', '/opt', '/usr')):
"""Try to find the user who executed the script originally.
:param home_at: List of directories containing home directories
:return: User who probably run the script as pwd struct
It will look the process tree up until it finds a uid that is not... | 49,721 |
def flastgame(cli, rawnick, chan, rest):
"""Disables starting or joining a game, and optionally schedules a command to run after the current game ends."""
nick, _, ident, host = parse_nick(rawnick)
chan = botconfig.CHANNEL
if var.PHASE != "join":
for decor in (COMMANDS.get("join", []) + COMMAND... | 49,722 |
async def test_update_device(dyn_bridge):
"""Test a successful setup."""
async_dispatch = Mock()
with patch(
"homeassistant.components.dynalite.bridge.async_dispatcher_send", async_dispatch
):
dyn_bridge.update_device(CONF_ALL)
async_dispatch.assert_called_once()
assert ... | 49,723 |
def get_peers_for_info_hash_s3(
info_hash,
limit=50
):
"""
Get current peers, S3.
"""
remote_object = s3.Object(BUCKET_NAME, info_hash + '/peers.json').get()
content = remote_object['Body'].read().decode('utf-8')
torrent_info = json.loads(content)
... | 49,724 |
def RGB_to_Lab(RGB, colourspace):
"""
Converts given *RGB* value from given colourspace to *CIE Lab* colourspace.
Parameters
----------
RGB : array_like
*RGB* value.
colourspace : RGB_Colourspace
*RGB* colourspace.
Returns
-------
bool
Definition success.
... | 49,725 |
def ltl2ba(formula):
"""Convert LTL formula to Buchi Automaton using ltl2ba.
@type formula: `str(formula)` must be admissible ltl2ba input
@return: Buchi automaton whose edges are annotated
with Boolean formulas as `str`
@rtype: [`Automaton`]
"""
ltl2ba_out = ltl2baint.call_ltl2ba(str(... | 49,726 |
def count_org_active_days(odf_day):
"""Return count of active days in org history"""
odf_not_null = org_active_days(odf_day)
return len(odf_not_null) | 49,727 |
def test_load_yml(stream, ref_loader):
"""The load function should read data from stream and construct correct proxy."""
doc = load(stream, ref_loader)
assert doc == MappingProxy(FLATTENED_DICT, ref_loader=ref_loader) | 49,728 |
def test_post_releases_are_kept_by_default():
"""Test postXXX versions are truncated to release"""
pin = 'pycodestyle==2.3.1.post2231 # via flake8'
env = Environment('')
result = env.fix_pin(pin)
assert result == pin | 49,729 |
async def update_zigbee_firmware(host: str, custom: bool):
"""Update zigbee firmware for both ZHA and zigbee2mqtt modes"""
sh = TelnetShell()
try:
if not await sh.connect(host) or not await sh.run_zigbee_flash():
return False
except:
pass
finally:
await sh.close(... | 49,730 |
def allow_agent(manager_container, package_agent):
"""Allow installing an agent on the manager container.
Agent installation scripts have all kinds of assumptions about
sudo and su, so those need to be available.
"""
docker.execute(manager_container.container_id, [
'bash', '-c',
"ec... | 49,731 |
def underdog(df):
"""
Filter the dataframe of game data on underdog wins
(games where the team with lower odds won).
Returns: tuple (string reason, pd dataframe)
"""
reason = 'underdog'
filt = df.loc[df['winningOdds']<0.46]
filt = filt.sort_values(['runDiff', 'winningScore'], ascending=[... | 49,732 |
def plot_sino_coverage(theta, h, v, dwell=None, bins=[16, 8, 4],
probe_grid=[[1]], probe_size=(0, 0)):
"""Plots projections of minimum coverage in the sinogram space."""
# Wrap theta into [0, pi)
theta = theta % (np.pi)
# Set default dwell value
if dwell is None:
dwell... | 49,733 |
def print_star_dates(
counter: dict[datetime.datetime, int],
repository: str,
*,
console: Console,
interval: datetime.timedelta,
) -> None:
"""Print the star dates for a repository."""
table = Table(title=repository)
table.add_column("Date")
table.add_column("Stars", justify="right")... | 49,734 |
def android_example():
"""A basic example of how to use the android agent."""
env = holodeck.make("AndroidPlayground-MaxDistance")
# The Android's command is a 94 length vector representing torques to be applied at each
# of his joints
command = np.ones(94) * 10
for i in range(10):
env.... | 49,735 |
def divisors(n):
"""Returns the all divisors of n"""
if n == 1: return 1
factors = list(distinct_factors(n))
length = int(log(n, min(factors))) + 1
comb = [item for item in product(list(range(length + 1)), repeat=len(factors))]
result = []
for e in comb:
tmp = []
for p, c in zip(factors, e):
tmp.append(in... | 49,736 |
def run():
"""Reads city/road graphs. Computes the cost to restore library access."""
for _ in range(read_value()):
city_count, road_count, library_cost, road_cost = read_record()
if road_cost < library_cost:
sets = DisjointSets(city_count + 1) # +1 for 1-based indexing
... | 49,737 |
def compute_features_levels(features, base_level=0):
"""Adapted from dnafeaturesviewer, see https://github.com/Edinburgh-Genome-Foundry/DnaFeaturesViewer
Author: Zulko
Compute the vertical levels on which the features should be displayed
in order to avoid collisions.
`features` must be a list of `d... | 49,738 |
def normalize_answer(s):
"""Lower text and remove extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
def remove_punc(text):
return re_punc.sub(' ', text) # convert punctuation to spaces
def white_space_fix(text):
return ' '.join(text.split())
def... | 49,739 |
def bq_db_dtype_to_dtype(db_dtype: str) -> StructuredDtype:
"""
Given a db_dtype as returned by BigQuery, parse this to an instance-dtype.
Note: We don't yet support Structs with unnamed fields (e.g. 'STRUCT<INT64>' is not supported.
:param db_dtype: BigQuery db-dtype, e.g. 'STRING', or 'STRUCT<column... | 49,740 |
def getPixelSize(lat, latsize, lonsize):
""" Get the pixel size (in m) based on latitude and
pixel size in degrees
"""
# Set up parameters for elipse
# Semi-major and semi-minor for WGS-84 ellipse
ellipse = [6378137.0, 6356752.314245]
radlat = np.deg2rad(lat)
Rsq = (ellips... | 49,741 |
def success_response( message, code = 200 ):
"""Returns a JSON response containing `success_message` with a given success code"""
return jsonify( { 'success_message' : message } ), code | 49,742 |
def sensorsuite(w,q,Parameters):
""" Measurements by onboard sensors """
w_actual = w
q_actual = q
Q_actual = utils.quat_to_rot(q_actual)
bias = np.array([0.5,-0.1,0.2]) #np.zeros(3)
# Measurement of reference directions by Sun Sensor
rNSunSensor = Parameters['Sensors']['SunSenso... | 49,743 |
def get_task_response(taskurl):
"""Check a task url to get it's status. Will return SUCCESS or FAILED, or timeout after 10 minutes (600s)
if the task is still pending
Parameters
----------
taskurl: str
URL to ping
Returns
-------
status: str
SUCCESS or FA... | 49,744 |
def align(gt, noise, gap_char=GAP_CHAR):
"""Align two text segments via sequence alignment algorithm
**NOTE**: this algorithm is O(N^2) and is NOT efficient for longer text.
Please refer to `genalog.text.anchor` for faster alignment on longer strings.
Arguments:
gt (str) : ground true text (sh... | 49,745 |
def get_similarity_order(labels, label_means, rank_proximity):
"""
This function take a dictionary of numeric data, and return the i-th closest data point
Parameters
----------
base_statistics : dict {label: (mean, covariance)}
each label is summurized by a mean and a covariance in the featu... | 49,746 |
def api_v1_votes_put():
"""Records user vote."""
# extract and validate post data
json_string = flask.request.form.get('vote', None)
if not json_string:
abort_user_error('Missing required parameter "vote".')
vote = json.loads(json_string)
post_uid = vote.get('uid')
if not post_uid:
abort_user_err... | 49,747 |
def interpolate(vertices, target_vertices, target_triangles):
""" Interpolate missing data.
Parameters
----------
vertices: array (n_samples, n_dim)
points of data set.
target_vertices: array (n_query, n_dim)
points to find interpolated texture for.
target_triangles: array (n_qu... | 49,748 |
def parse_phot_table(table, rows):
"""
Retrieve filter information from the photometric file
Parameters
----------
path : str
path to LSST light curve file
rows : slice
range of rows for this SN
Returns
-------
dict
dictionary of filter data for the light cu... | 49,749 |
def XOR(a: bool, b: bool) -> bool:
"""XOR logical gate
Args:
a (bool): First input signal
b (bool): Second input signal
Returns:
bool: Output signal
"""
return OR(AND(NOT(a), b), AND(a, NOT(b))) | 49,750 |
def install_wllvm(force: bool) -> None:
"""
Installs wllvm
:param force: force installation if package is already installed
"""
conf = ProgramParser()
conf.read([os.path.join(constants.CONF_PATH, "utils/wllvm.conf")])
Installer.factory(conf["WLLVM"], force).run() | 49,751 |
def test_object_method():
""" JIT-based inference of fields at call time. """
class MyObject:
def __init__(self) -> None:
self.my_a = np.random.rand(20)
@dace.method
def something(self, B: dace.float64[20]):
self.my_a += B
obj = MyObject()
acopy = np.cop... | 49,752 |
def create_list_from_dict(mydict):
"""
Converts entities dictionary to flat list.
Args:
mydict (dict): Input entities dictionary
Returns:
list
"""
outputs = []
for k, v in mydict.items():
if len(v) > 0:
for i in v:
outputs.append(i)
... | 49,753 |
def recode(
_x: Iterable,
*args: Any,
_default: Any = None,
_missing: Any = None,
**kwargs: Any,
) -> Iterable[Any]:
"""Recode a vector, replacing elements in it
Args:
x: A vector to modify
*args: and
**kwargs: replacements
_default: If supplied, all values n... | 49,754 |
def get_details_for_all_categories(categories: List[str]) -> List[Dict[str, Any]]:
"""Get all api details for categories
:param categories List of all categories returned from server
:returns List of api details
"""
api_details = []
for category in categories:
total_count, data = get_de... | 49,755 |
def remove_event_listener_breakpoint(
eventName: str, targetName: Optional[str] = None
) -> dict:
"""Removes breakpoint on particular DOM event.
Parameters
----------
eventName: str
Event name.
targetName: Optional[str]
EventTarget interface name.
"""
return {
... | 49,756 |
def iirnotch(w0, Q):
"""
Design second-order IIR notch digital filter.
A notch filter is a band-stop filter with a narrow bandwidth
(high quality factor). It rejects a narrow frequency band and
leaves the rest of the spectrum little changed.
Parameters
----------
w0 : float
Nor... | 49,757 |
def update_one(collection_name, _id, **kwargs):
"""
Update document in mongo
"""
collection = getattr(database, collection_name)
return collection.update_one({'_id': ObjectId(_id)}, {'$set': kwargs}) | 49,758 |
def AAPIEnterVehicle(idveh, idsection):
"""Execute command once a vehicle enters the Aimsun instance."""
global entered_vehicles
entered_vehicles.append(idveh)
return 0 | 49,759 |
def check_if_layer_weights_are_updating(trainer, model):
"""
:param trainer: The handler function's first argument is the 'Engine' object it is bound to
:param model: model
"""
# Creating an alias for easier reference
f = check_if_layer_weights_are_updating
print("")
print("checking wei... | 49,760 |
def get_predictionnet(args, model, unlabeled_dataloader):
"""Get predictions using a server client setup with POW on the server side."""
initialized = False
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
timequery = 0
start1 = time.time()
... | 49,761 |
async def get_history_care_plan(
api_key: str, doctor: Doctor = Depends(get_current_doctor)
):
"""Get all care plan for client"""
service = TestService()
return service.get_history_care_plan(api_key, doctor) | 49,762 |
def delete_integration_response(restApiId=None, resourceId=None, httpMethod=None, statusCode=None):
"""
Represents a delete integration response.
See also: AWS API Documentation
:example: response = client.delete_integration_response(
restApiId='string',
resourceId='string',
... | 49,763 |
def bode(sys_list,w=None,x_lim=None,y_lim=None,dB=True,Hz=False,deg=True,log_x=True):
"""
Returns the impulse response of the continuous or discrete-time systems `sys_list`.
Parameters
----------
sys_list : system or list of systems
A single system or a list of systems to analyse
w ... | 49,764 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["white", "black"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
----------
im
The AxesImage to be labeled.
data
Data used to annotate. If N... | 49,765 |
def _extract_body(payload, embedded_newlines):
"""
Extract HTTP headers and body
"""
headers_str, body = payload.split('\r\n\r\n',1)
headers = {}
for line in headers_str.splitlines():
line = line.rstrip()
if line.find(':') > -1:
key, value = line.split(':',1)
... | 49,766 |
def connect(db_url, *, external=False):
"""Connect to the database using an environment variable.
"""
logger.info("Connecting to SQL database %r", db_url)
kwargs = {}
if db_url.startswith('sqlite:'):
kwargs['connect_args'] = {'check_same_thread': False}
engine = create_engine(db_url, **k... | 49,767 |
def containsDuplicate(nums: List[int]) -> bool:
"""
Time: O(n)
Space: O(n)
"""
visited = set()
for n in nums:
if n in visited:
return True
else:
visited.add(n)
return False | 49,768 |
def test_downsample_in_time_varying_int_time_partial_flags(hera_uvh5):
"""Test downsample_in_time handling of file with integration time changing
within a baseline and partial flagging.
"""
uv_object = hera_uvh5
uv_object.phase_to_time(Time(uv_object.time_array[0], format="jd"))
# reorder to mak... | 49,769 |
def test_auto_negotiation_dut_advertises_each_speed(enum_dut_portname_module_fixture):
"""Test all candidate ports to advertised all supported speeds one by one and verify
that the port operational status is up after auto negotiation
"""
dutname, portname = enum_dut_portname_module_fixture
duthos... | 49,770 |
def getbans(chain = 'INPUT'):
""" Gets a list of all bans in a chain """
banlist = []
# Get IPv4 list
for i in range(0,MAX_IPTABLES_TRIES):
out = None
try:
out = subprocess.check_output([IPTABLES_EXEC, '--list', chain, '-n', '--line-numbers'], stderr = subprocess.STDOUT)
excep... | 49,771 |
def run_all(relaxation, no_setup_times):
"""Runs a bunch of instances in the benchmark."""
for n in [8, 16, 32, 64]: #, 128]:
for q in [2**i for i in range(0, 10) if 2**i <= n]:
# Problem scneario (with or without setup times)
pscenario = "scheduling" if no_setup_times else "rou... | 49,772 |
def getROC(detector = 0, methods = ['BDT']):
"""Get the ROC curve for a dectector given a set of methods testes
Keyword arguments:
detector -- detector used (default 0)
methods -- list of methods used (default ['BDT'])
"""
# retrive root tree as datafram
df= read_root('resultsDet{0}.root'... | 49,773 |
def validate_command(command):
"""Returns an error if there are not exactly 5 commands."""
if len(command) != 5:
print("Error parsing file. Command may not be properly formatted.")
sys.exit() | 49,774 |
def classify_dtypes_using_TF2_in_test(data_sample, idcols, verbose=0):
"""
If you send in a batch of Ttf.data.dataset with the name of target variable(s), you will get back
all the features classified by type such as cats, ints, floats and nlps. This is all done using TF2.
"""
print_features = ... | 49,775 |
def cs2coords(start, qstart, length, strand, cs, offset=1,
splice_donor=['gt', 'at'], splice_acceptor=['ag', 'ac']):
"""
# From minimap2 manual this is the cs flag definitions
Op Regex Description
= [ACGTN]+ Identical sequence (long form)
: [0-9]+ Identical sequence length
* [acgtn... | 49,776 |
def gatherAnnotations(model):
"""Gathers custom properties annotating elements of the robot
across the model. These annotations were created in the model.py
module and are marked with a leading '$'.
Args:
model(dict): The robot model dictionary.
ignore_keys(list): Ignored annotation categor... | 49,777 |
def get_learner_goals_from_model(learner_goals_model):
"""Returns the learner goals domain object given the learner goals
model loaded from the datastore.
Args:
learner_goals_model: LearnerGoalsModel. The
learner goals model from the datastore.
Returns:
LearnerGoals. The le... | 49,778 |
def prepare_metadata_for_build_wheel(
metadata_directory, config_settings, _allow_fallback):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined,
unless _allow_fallback is False in which case HookMissing is raised.
... | 49,779 |
def get_modtime(ftp, filename):
"""
Get the modtime of a file.
:rtype : datetime
"""
resp = ftp.sendcmd('MDTM ' + filename)
if resp[:3] == '213':
s = resp[3:].strip()
mod_time = datetime.strptime(s,'%Y%m%d%H%M%S')
return mod_time
return datetime.min | 49,780 |
def rotor_between_objects_root(X1, X2):
"""
Lasenby and Hadfield AGACSE2018
For any two conformal objects X1 and X2 this returns a rotor that takes X1 to X2
Uses the square root of rotors for efficiency and numerical stability
"""
X21 = (X2 * X1)
X12 = (X1 * X2)
gamma = (X1 * X1).value[0... | 49,781 |
def propose_time_step(
dt: float, scaled_error: float, error_order: int, limits: LimitsType
):
"""
Propose an updated dt based on the scheme suggested in Numerical Recipes, 3rd ed.
"""
SAFETY_FACTOR = 0.95
err_exponent = -1.0 / (1 + error_order)
return jnp.clip(
dt * SAFETY_FACTOR * ... | 49,782 |
def cross_column(columns, hash_backet_size=1e4):
"""
generate cross column feature from `columns` with hash bucket.
:param columns: columns to use to generate cross column, Type must be ndarray
:param hash_backet_size: hash bucket size to bucketize cross columns to fixed hash bucket
:return: cross ... | 49,783 |
def conform_json_response(api, json_response):
"""Get the right data from the json response. Expects a list, either like [[],...], or like [{},..]"""
if api=='cryptowatch':
return list(json_response['result'].values())[0]
elif api=='coincap':
return json_response['data']
elif api in {'po... | 49,784 |
def failOnException(wrapped_function):
"""sys.exit(1) on any exception"""
@wraps(wrapped_function)
def failOnException_wrapper(*args, **kwargs):
"""wrapper function"""
try:
return wrapped_function(*args, **kwargs)
except Exception: # pylint: disable=W0703
sy... | 49,785 |
def find_matching(root_path,
relative_paths_to_search,
file_pattern):
"""
Given an absolute `root_path`, a list of relative paths to that
absolute root path (`relative_paths_to_search`), and a `file_pattern`
like '*.sql', returns information about the files. For examp... | 49,786 |
def test_no_extension():
"""Test a datafile with a comment section, labels and integer and floats."""
test_file = os.path.join(TEST_DIR, 'input_files', 'datafile')
with open(test_file, "rb") as file:
info = fleep.get(file.read(128))
assert not info.type
assert not info.extension
assert... | 49,787 |
def parse_content(content):
"""
解析网页
:param content:
:return:
"""
movie = {}
html = etree.HTML(content)
try:
info = html.xpath("//div[@id='info']")[0]
movie['director'] = info.xpath("./span[1]/span[2]/a/text()")[0]
movie['screenwriter'] = info.xpath("./span[2]/spa... | 49,788 |
def model_save(self, commit=True):
"""
Creates and returns model instance according to self.clean_data.
This method is created for any form_for_model Form.
"""
if self.errors:
raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name)
... | 49,789 |
def count_items(item_list: list) -> (list, list):
"""
Essa função lista as categorias de itens e as suas respetivas quantidades.
:param item_list: lista de itens
:return: uma tupla contendo lista de tipos e lista com a contagem de elementos dos tipos
"""
item_types = set(item_list)
count_ite... | 49,790 |
def run_tests(args=None, plugins=None):
"""
Perform in-process test run using pytest. See help(pytest.main) for
details about arguments.
"""
if args is None:
my_path = os.path.realpath(__file__)
my_dir = os.path.dirname(my_path)
args = ["-x", os.path.dirname(my_dir)]
im... | 49,791 |
def test_publish_volume_idempotency(setup):
"""publish volume idempotency""" | 49,792 |
def find_adjacent_citations(adfix, uuid_ctd_mid_map, backwards=False):
""" Given text after or before a citation, find all directly adjacent
citations.
"""
if backwards:
perimeter = adfix[-50:]
else:
perimeter = adfix[:50]
match = CITE_PATT.search(perimeter)
if not match... | 49,793 |
def defineTrendingObjects(subsystem):
""" Defines trending histograms and the histograms from which they should be extracted.
Args:
subsystem (subsystemContainer): Current subsystem container
subsystem (str): The current subsystem by three letter, all capital name (ex. ``EMC``).
"""
fun... | 49,794 |
def staff_beers():
"""
This method is used to return 3 beer
"""
return Beer.query.limit(3) | 49,795 |
def gen_curves(gen_data, file_path="", plot=True):
"""
Generates all parameters/values needed to produce an IV surface. No actual computations done
except to compute relevant values for the drift.
"""
num_gen_days = len(gen_data)
tau = DEFAULT_TAU
pis, mus, sigs, As, lams = construct_p... | 49,796 |
def mm2phi(mm):
"""Convert a mm float to phi-scale.
Attributes:
mm <float64>: A float value for conversion"""
return(-math.log2(mm)) | 49,797 |
def IV_action(arr, iv=None, action="extract"):
"""Extract or store IV at the end of the arr."""
if action == "store" and iv != None:
arr.append(iv)
elif action == "extract" and iv == None:
iv = arr.pop()
return iv
else:
return "Error: No action assigned." | 49,798 |
def get_tty_width():
"""
:return: Terminal width as a string
"""
return str(get_terminal_size()[0]) | 49,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.