content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def shuffle_data(data):
"""
Shuffle the data
"""
rng_state = np.random.get_state()
for c, d in data.items():
np.random.set_state(rng_state)
np.random.shuffle(d)
data[c] = d
return data | 25,700 |
def index(current_user=None):
""" Display home page """
return render_template('homepage.html', username=current_user['name'], \
logged_in=current_user['is_authenticated'], \
display_error=request.cookies.get('last_attempt_error') == 'True', \
login_banner=APP.config['LOGIN_BANNER']) | 25,701 |
def save_as_jpeg(img, filename):
"""
Save a numpy array as a jpeg image
Attributes
----------
:param img: Image to be saved
:type img: Numpy array
"""
imsave(filename + '.png', img, 'png') | 25,702 |
def _read_data_file(data_path):
"""
Reads a data file into a :class:`pandas:pandas.DataFrame` object.
Parameters
----------
data_path : str
Path of the data file with extension. Supports ``.csv``, ``.xlsx``/``.xls``, ``.json``, and ``.xml``.
Returns
-------
:class:`pandas:panda... | 25,703 |
def disable_admin_access(session, return_type=None, **kwargs):
"""
Disable Admin acccess
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type return_type: str
:param return_type: If this is set to the string 'json', this function
... | 25,704 |
def _get_bbox_indices(x, y, bbox):
"""
Convert bbox values to array indices
:param x, y: arrays with the X, Y coordinates
:param bbox: minx, miny, maxx, maxy values
:return: bbox converted to array indices
"""
minx, miny, maxx, maxy = bbox
xindices, = np.where((x >= minx) & (x <= maxx))... | 25,705 |
def skill_competencies():
"""
Called by S3OptionsFilter to provide the competency options for a
particular Skill Type
"""
table = s3db.hrm_skill
ttable = s3db.hrm_skill_type
rtable = s3db.hrm_competency_rating
query = (table.id == request.args[0]) & \
(table.skil... | 25,706 |
def test_add_request_names(client, jwt, app):
"""
Setup:
Test:
Validate:
:param client:
:param jwt:
:param app:
:return:
"""
do_test_cleanup()
# Initialize the service
nr_svc = NameRequestService()
"""
Test adding two new names
"""
# We will need a base... | 25,707 |
def calc_field_changes(element, np_id):
"""
Walk up the tree of geo-locations, finding the new parents
These will be set onto all the museumobjects.
"""
fieldname = element._meta.concrete_model.museumobject_set.\
related.field.name
field_changes = {}
field_changes[fieldname] = e... | 25,708 |
def index(request, _):
"""
路由请求
`` request `` 请求对象
"""
if request.method == 'GET' or request.method == 'get':
return index_page(request)
elif request.method == 'POST' or request.method == 'post':
return send_wxmsg(request)
else:
rsp = JsonResponse({'code': -1, 'erro... | 25,709 |
def get_daisy_client():
"""Get Daisy client instance."""
endpoint = conf.get('discoverd', 'daisy_url')
return daisy_client.Client(version=1, endpoint=endpoint) | 25,710 |
def intermediate_statistics(
scores, ground_truth, audio_durations, *,
segment_length=1., time_decimals=6, num_jobs=1,
):
"""
Args:
scores (dict, str, pathlib.Path): dict of SED score DataFrames
(cf. sed_scores_eval.utils.scores.create_score_dataframe)
or a direc... | 25,711 |
def test_get_default_db_uri_from_env(monkeypatch):
"""Default db uri can be set from the env var."""
monkeypatch.setenv("POKEDEX_DB_ENGINE", "/path/to/db")
uri, origin = default.db_uri_with_origin()
assert "environment" == origin
assert "/path/to/db" == uri | 25,712 |
def vnorm(v1):
"""vnorm(ConstSpiceDouble [3] v1) -> SpiceDouble"""
return _cspyce0.vnorm(v1) | 25,713 |
def mean_iou(y_true, y_pred):
"""F2 loss"""
prec = []
for t in np.arange(0.5, 1.0, 0.05):
y_pred_ = tf.to_int32(y_pred > t)
score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
K.get_session().run(tf.local_variables_initializer())
with tf.control_dependencies([up_opt]):
... | 25,714 |
def _encode_string_parts(value, encodings):
"""Convert a unicode string into a byte string using the given
list of encodings.
This is invoked if `encode_string` failed to encode `value` with a single
encoding. We try instead to use different encodings for different parts
of the string, using the enc... | 25,715 |
def get_files(path, pattern):
"""
Recursively find all files rooted in <path> that match the regexp <pattern>
"""
L = []
if not path.endswith('/'): path += '/'
# base case: path is just a file
if (re.match(pattern, os.path.basename(path)) != None) and os.path.isfile(path):
L.append(path)
... | 25,716 |
def SocketHandler(qt):
""" `SocketHandler` wraps a websocket connection.
HTTP GET /ws
"""
class _handler(websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
qt.log("new socket open ...")
qt.register_socket(self... | 25,717 |
def var_swap(asset: Asset, tenor: str, forward_start_date: Optional[str] = None,
*, source: str = None, real_time: bool = False) -> Series:
"""
Strike such that the price of an uncapped variance swap on the underlying index is zero at inception. If
forward start date is provided, then the resul... | 25,718 |
def extract_flow_global_roi(flow_x, flow_y, box):
"""
create global roi cropped flow image (for numpy image)
image:
numpy array image
box:
list of [xmin, ymin, xmax, ymax]
"""
flow_x_roi = extract_global_roi(flow_x, box)
flow_y_roi = extract_global_roi(flow_y, box)
if flo... | 25,719 |
def patch_shell(response=None, error=False):
"""Mock the `AdbDeviceTcpFake.shell` and `DeviceFake.shell` methods."""
def shell_success(self, cmd):
"""Mock the `AdbDeviceTcpFake.shell` and `DeviceFake.shell` methods when they are successful."""
self.shell_cmd = cmd
return response
d... | 25,720 |
def __setAdjacent_square__(self, pos):
"""
Sets all adjacencies in the map for a map with square tiles.
"""
self.__checkIndices__(pos)
i, j = pos; adjacent = []
# Function to filter out nonexistent cells.
def filterfn(p):
do_not_filter = 0 <= p[0] < self.__numrows__ and 0 <= p[1] < s... | 25,721 |
def model_definition_nested_events():
"""Test model for state- and parameter-dependent heavisides.
ODEs
----
d/dt x_1:
inflow_1 - decay_1 * x1
d/dt x_2:
- decay_2 * x_2
Events:
-------
event_1:
trigger: x_1 > inflow_1 / decay_2
bolus: [[ 0],
... | 25,722 |
def status():
"""Show kdump status"""
clicommon.run_command("sonic-kdump-config --status")
clicommon.run_command("sonic-kdump-config --memory")
clicommon.run_command("sonic-kdump-config --num_dumps")
clicommon.run_command("sonic-kdump-config --files") | 25,723 |
async def address_balance_history(
request: Request,
address: Address,
token_id: TokenID = Query(None, description="Optional token id"),
timestamps: bool = Query(
False, description="Include timestamps in addition to block heights"
),
flat: bool | None = Query(True, description="Return d... | 25,724 |
def load(as_pandas=None):
"""
Loads the Grunfeld data and returns a Dataset class.
Parameters
----------
as_pandas : bool
Flag indicating whether to return pandas DataFrames and Series
or numpy recarrays and arrays. If True, returns pandas.
Returns
-------
Dataset
... | 25,725 |
def rule_if_system(system_rule, non_system_rule, context):
"""Helper function to pick a rule based on system-ness of context.
This can be used (with functools.partial) to choose between two
rule names, based on whether or not the context has system
scope. Specifically if we will fail the parent of a ne... | 25,726 |
def find_inactive_ranges(note_sequence):
"""Returns ranges where no notes are active in the note_sequence."""
start_sequence = sorted(
note_sequence.notes, key=lambda note: note.start_time, reverse=True)
end_sequence = sorted(
note_sequence.notes, key=lambda note: note.end_time, reverse=True)
notes... | 25,727 |
def is_connected(G):
"""Returns True if the graph is connected, False otherwise.
Parameters
----------
G : NetworkX Graph
An undirected graph.
Returns
-------
connected : bool
True if the graph is connected, false otherwise.
Raises
------
NetworkXNotImplemented:
... | 25,728 |
def remove_collaborations():
""" Main function that governs the deletion of metadata in a collaborations
within a specified Synergos network
"""
st.title("Orchestrator - Remove existing collaboration(s)")
##################################################
# Step 1: Connect to your specifie... | 25,729 |
def DeleteObjects(objects_to_delete, num_threads=DEFAULT_NUM_THREADS,
show_progress_bar=False):
"""Delete the given Cloud Storage objects.
Uses the appropriate parallelism (multi-process, multi-thread, both, or
synchronous).
Args:
objects_to_delete: list of ObjectDeleteTask
num_threa... | 25,730 |
def setup_routing(app):
"""
Configure url routing for application
:param app: The bottle application object
"""
app.route('/api/access', 'POST', access.login)
app.route('/api/access', 'DELETE', access.logout)
app.route('/api/users', 'GET', users.get_personal_info)
app.route('/api/users'... | 25,731 |
def show_result(img,
result,
skeleton=None,
kpt_score_thr=0.3,
bbox_color=None,
pose_kpt_color=None,
pose_limb_color=None,
radius=4,
thickness=1,
font_scale=0.5,
... | 25,732 |
def D2(X, Y, Y2=None, YT=None):
""" Calculate the pointwise (squared) distance.
Arguments:
X: of shape (n_sample, n_feature).
Y: of shape (n_center, n_feature).
Y2: of shape (1, n_center).
YT: of shape (n_feature, n_center).
Returns:
pointwise distances (n_sample, n... | 25,733 |
def read_table(path):
"""Lee un archivo tabular (CSV o XLSX) a una lista de diccionarios.
La extensión del archivo debe ser ".csv" o ".xlsx". En función de
ella se decidirá el método a usar para leerlo.
Si recibe una lista, comprueba que todos sus diccionarios tengan las
mismas claves y de ser así... | 25,734 |
def spec_from_json_dict(
json_dict: Dict[str, Any]
) -> FieldSpec:
""" Turns a dictionary into the appropriate FieldSpec object.
:param dict json_dict: A dictionary with properties.
:raises InvalidSchemaError:
:returns: An initialised instance of the appropriate FieldSpec
... | 25,735 |
def hyp_pfq(A, B, x, out=None, n=0):
"""
This function is decorated weirdly because its extra params are lists.
"""
out = np_hyp_pfq([a+n for a in A], [b+n for b in B], x, out)
with np.errstate(invalid='ignore'):
out *= np.prod([scipy.special.poch(a, n) for a in A])
out /= np.prod([s... | 25,736 |
def create_new_token(
data: dict,
expires_delta: Optional[timedelta] = None,
page_only: bool = False):
"""Creates a token with the given permission and expiry"""
to_encode = data.copy()
if page_only:
expires = datetime.max
elif expires_delta:
expires = datetime.ut... | 25,737 |
def parse_json_year_date(year: Number, fullpath: Path) -> Union[Path, None]:
"""
Filtra os arquivos json por ano.
"""
if not isinstance(fullpath, Path):
raise TypeError("O parâmetro path deve do tipo Path.")
pattern_finder = re.search(f"_{year}\.json", fullpath.name)
if pattern_finder:
... | 25,738 |
def available_fastspeech2():
"""
List available FastSpeech2, Text to Mel models.
"""
from malaya_speech.utils import describe_availability
return describe_availability(
_fastspeech2_availability,
text = '`husein` and `haqkiem` combined loss from training set',
) | 25,739 |
def solve(A, b, method='gauss', verbose=0, eps=1e-6, max_itration_times=100000, omega=1.9375):
"""
Solve equations in specified method.
:param A: coefficient matrix of the equations
:param b: vector
:param method: the way to solve equations
:param verbose: whether show the running information
... | 25,740 |
def returns_unknown():
"""Tuples are a not-supported type."""
return 1, 2, 3 | 25,741 |
def get_user(
cmd,
app_id: str,
token: str,
assignee: str,
api_version: str,
central_dns_suffix=CENTRAL_ENDPOINT,
) -> User:
"""
Get information for the specified user.
Args:
cmd: command passed into az
app_id: name of app (used for forming request URL)
token... | 25,742 |
def test_gumbel_softmax_transform():
"""Test the gumbel-softmax transform function."""
# Define variables
numActions = 3
batch_size = 3
gumbelTemp = -1
gumbelReturnHard = True
x = torch.randn(batch_size,9)
# Perform transform
(batch_samples_stacked, all_samples_gumbel_softmax_vectors) = gumbel_softmax_trans... | 25,743 |
def run_test(
bess_addr,
ptfdir,
trex_server_addr=None,
extra_args=(),
):
"""
Runs PTF tests included in provided directory.
"""
# create a dummy interface for PTF
if not create_dummy_interface() or not set_up_interfaces([DUMMY_IFACE_NAME]):
return False
pypath = "/upf-... | 25,744 |
def get(fg, bg=None, attribute = 0):
"""
Return string with ANSI escape code for set text colors
fg: html code or color index for text color
attribute: use Attribute class variables
"""
if type(fg) is str:
bg = bg if bg else "#000000"
return by_hex(fg, bg, attribute=attribute)
... | 25,745 |
def get_Qi(Q,i,const_ij,m):
"""
Aim:
----
Equalising two polynomials where one is obtained by a SOS
decomposition in the canonical basis and the other one is expressed
in the Laguerre basis.
Parameters
----------
Q : matrix for the SOS decomposition
i : integer
... | 25,746 |
def run_openlego(analyze_mdao_definitions, cmdows_dir=None, initial_file_path=None,
data_folder=None, run_type='test', approx_totals=False, driver_debug_print=False):
# type: (Union[int, list, str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool], Optional[bool]) -> Union... | 25,747 |
def unzipWorker(filename, forceDownload = False):
"""
Perform decompression of downloaded files.
:param filename
:param forceDownload: A flag indicating that the download should override
the default behavior of the script.
"""
global MSG_BODY
originalName = filename
hourlyGzName ... | 25,748 |
def strToBool(s):
"""
Converts string s to a boolean
"""
assert type(s) == str or type(s) == unicode
b_dict = {'true': True, 'false': False, 'yes': True, 'no': False}
return b_dict[s.lower()] | 25,749 |
def publish_to_sns(topic_name, message, region=None):
"""
Post a message to an SNS topic
"""
AWS = AWSCachedClient(region) # cached client object
partition = None
if region:
partition = partition_from_region(region)
else:
partition = 'aws'
region = 'us-east-1'
... | 25,750 |
def bandpass_voxels(realigned_file, bandpass_freqs, sample_period=None):
"""
Performs ideal bandpass filtering on each voxel time-series.
Parameters
----------
realigned_file : string
Path of a realigned nifti file.
bandpass_freqs : tuple
Tuple containing the bandpass freque... | 25,751 |
def get_subset(
classes: List,
train_data,
train_labels,
val_data,
val_labels,
test_data,
test_labels,
) -> Tuple:
"""
creates a binary subset of training, validation, and testing set using the specified list of classes to select
:param classes: list of classes in the labels that... | 25,752 |
def init_vgg16(model_folder):
"""load the vgg16 model feature"""
if not os.path.exists(os.path.join(model_folder, 'vgg16.weight')):
from torch.utils.serialization import load_lua #only available in torch < 1.0
if not os.path.exists(os.path.join(model_folder, 'vgg16.t7')):
os.system('... | 25,753 |
def to_xyzw(matrix):
"""Convenience/readibility function to bring spatial (trailing) axis to start.
Args:
matrix (...x4 array): Input matrix.
Returns:
4x... array
"""
return np.rollaxis(matrix, -1) | 25,754 |
def do_3d_pooling(feature_matrix, stride_length_px=2,
pooling_type_string=MAX_POOLING_TYPE_STRING):
"""Pools 3-D feature maps.
:param feature_matrix: Input feature maps (numpy array). Dimensions must be
M x N x H x C or 1 x M x N x H x C.
:param stride_length_px: See doc for `do_... | 25,755 |
def logoutUser(request):
"""[summary]
Args:
request ([Logout]): [Metodo herado de logout de django para cerrar sesión]
Returns:
[Redirect template]: [Retorna el template del login]
"""
logout(request)
return redirect('/accounts/login/') | 25,756 |
def assert_allclose(actual: float, desired: numpy.float64, rtol: float):
"""
usage.scipy: 2
usage.sklearn: 7
usage.statsmodels: 12
"""
... | 25,757 |
def sin_wave(freq, duration=1, offset=0):
"""Makes a sine wave with the given parameters.
freq: float cycles per second
duration: float seconds
offset: float radians
returns: Wave
"""
signal = SinSignal(freq, offset=offset)
wave = signal.make_wave(duration)
return wave | 25,758 |
def assign_lpvs(lat):
""" Given lattice type return 3 lattice primitive vectors"""
lpv = zeros((3,3))
if lat=='FCC':
lpv[0,1]=1./sqrt(2)
lpv[0,2]=1./sqrt(2)
lpv[1,0]=1./sqrt(2)
lpv[1,2]=1./sqrt(2)
lpv[2,0]=1./sqrt(2)
lpv[2,1]=1./sqrt(2)
elif lat=='SC':
... | 25,759 |
def flatten_and_batch_shift_indices(indices: torch.LongTensor,
sequence_length: int) -> torch.Tensor:
"""``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor,
which has size ``(batch_size, sequence_length, embedding_size)``. This fun... | 25,760 |
def raveled_affinity_watershed(
image_raveled, marker_coords, offsets, mask, output
):
"""Compute affinity watershed on raveled arrays.
Parameters
----------
image_raveled : 2D array of float(32), shape (npixels, ndim)
The z, y, and x affinities around each pixel.
marker_coo... | 25,761 |
def test_run_job_with_job_requirements_mixed(ee2_port, ws_controller, mongo_client):
"""
Tests running a job where requirements are specified on input, from the catalog, and from
the deploy.cfg file.
"""
_run_job(
ee2_port,
ws_controller,
mongo_client,
job_reqs={"requ... | 25,762 |
def get_spike_times(units: pynwb.misc.Units, index, in_interval):
"""Use bisect methods to efficiently retrieve spikes from a given unit in a given interval
Parameters
----------
units: pynwb.misc.Units
index: int
in_interval: start and stop times
Returns
-------
"""
st = unit... | 25,763 |
def _make_hours(store_hours):
"""Store hours is a dictionary that maps a DOW to different open/close times
Since it's easy to represent disjoing hours, we'll do this by default
Such as, if a store is open from 11am-2pm and then 5pm-10pm
We'll slice the times in to a list of floats representing 30 minut... | 25,764 |
def mul_time(t1, factor):
"""Get the product of the original Time and the number
time: Time
factor: number
returns: Time
"""
assert valid_time(t1)
secods = time_to_int(t1) * factor
return int_to_time(secods) | 25,765 |
def create_pmf_from_samples(
t_samples_list, t_trunc=None, bin_width=None, num_bins=None):
"""
Compute the probability distribution of the waiting time from the sampled data.
Parameters
----------
t_samples_list : array-like 1-D
Samples of the waiting time.
t_trunc: int
... | 25,766 |
def __add_click_for_argument(db_user, db_argument):
"""
Add click for a specific argument
:param db_user: User
:param db_argument: Argument
:return: None
"""
db_conclusion = DBDiscussionSession.query(Statement).get(db_argument.conclusion_uid)
# set vote for the argument (relation), its... | 25,767 |
def box_corner_to_center(boxes):
"""从(左上,右下)转换到(中间,宽度,高度)"""
x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
cx = (x1 + x2) / 2
cy = (y1 + y2) / 2
w = x2 - x1
h = y2 - y1
boxes = paddle.stack((cx, cy, w, h), axis=-1)
return boxes | 25,768 |
def test_iterate_with_multiple_selected_items(setup_analysis_iterator):
""" Test iterating over analysis objects with multiple selections. """
# Setup
KeyIndex, _, test_dict = setup_analysis_iterator
# Create the iterator
object_iter = generic_config.iterate_with_selected_objects(
analysis_... | 25,769 |
def irrelevant(condition=None, library=None, weblog_variant=None, reason=None):
""" decorator, allow to mark a test function/class as not relevant """
skip = _should_skip(library=library, weblog_variant=weblog_variant, condition=condition)
def decorator(function_or_class):
if not skip:
... | 25,770 |
def test_localdockerinterface_get_info_disconnected(caplog, responses):
"""No daemon to talk to (see responses used as fixture but no listening)."""
caplog.set_level(logging.DEBUG, logger="charmcraft")
ldi = LocalDockerdInterface()
resp = ldi.get_image_info("test-digest")
assert resp is None
e... | 25,771 |
def ec_test():
"""
Tests the ec-multiply sections. Cases taken from the bip38 document.
"""
seed = "dh3409sjgh3g48"
seed2 = "asdas8729akjbmn"
cases = [[
'btc',
'TestingOneTwoThree',
'passphrasepxFy57B9v8HtUsszJYKReoNDV6VHjUSGt8EVJmux9n1J3Ltf1gRxyDGXqnf9qm',
'6PfQ... | 25,772 |
def get_all_approved(self) -> list:
"""Get all appliances currently approved
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliance
- GET
- /appliance/approved
:return: Returns approved appliances
:rtype: l... | 25,773 |
def get_project_root() -> str:
"""Get the path to the project root.
Returns:
str: the path to the project root.
"""
return os.path.abspath(os.path.dirname(os.path.dirname(__file__))) | 25,774 |
def bokeh_hover_tooltip(
label=False,
text=False,
image=False,
audio=False,
coords=True,
index=True,
custom=None,
):
"""
???+ note "Create a Bokeh hover tooltip from a template."
- param label: whether to expect and show a "label" field.
- param text: whether to expe... | 25,775 |
def plot_tuning_curves(direction_rates, title):
"""
This function takes the x-values and the y-values in units of spikes/s
(found in the two columns of direction_rates) and plots a histogram and
polar representation of the tuning curve. It adds the given title.
"""
#plots
plt... | 25,776 |
def constant_xavier_initializer(shape, dtype=tf.float32, uniform=True):
"""Initializer function."""
if not dtype.is_floating:
raise TypeError('Cannot create initializer for non-floating point type.')
# Estimating fan_in and fan_out is not possible to do perfectly, but we try.
# This is the right t... | 25,777 |
def upload_script(name: str, permission_type: str, content: str, entry_id: str) -> Dict:
"""
Uploads a script by either given content or file
:param name: Script name to upload
:param permission_type: Permissions type of script to upload
:param content: PowerShell script content
... | 25,778 |
def create_orthogonal(left, right, bottom, top, znear, zfar):
"""Create a Mat4 orthographic projection matrix."""
width = right - left
height = top - bottom
depth = zfar - znear
sx = 2.0 / width
sy = 2.0 / height
sz = 2.0 / -depth
tx = -(right + left) / width
ty = -(top + bottom) /... | 25,779 |
def update_image_version(name: str, new_version: str):
"""returns the passed image name modified with the specified version"""
parts = name.rsplit(':', 1)
return f'{parts[0]}:{new_version}' | 25,780 |
def test_argument_conversion_error():
"""
If a conversion does not work, we pass the unconverted string (like in python2)
"""
instances = ClassA.from_string("ClassD[12.4]")
assert isinstance(instances[0].arg1, str) | 25,781 |
def compute_entanglement(theta):
"""Computes the second Renyi entropy of circuits with and without a tardigrade present.
Args:
- theta (float): the angle that defines the state psi_ABT
Returns:
- (float): The entanglement entropy of qubit B with no tardigrade
initially present
... | 25,782 |
def parse_CDS_info(CDS_info):
"""
Args:
CDS_info (python d):
'aliases' (list<alias_list (multiple)>):
alias_list
list<'locus_tag', str> AND/OR
list<'old_locus_tag', str> AND/OR
list<'protein_id', str>
'd... | 25,783 |
def send_sessions():
"""
Delivers all currently undelivered sessions to Bugsnag
"""
default_client.session_tracker.send_sessions() | 25,784 |
def recover_original_schema_name(sql: str, schema_name: str) -> str:
"""Postgres truncates identifiers to 63 characters at parse time and, as pglast
uses bits of PG to parse queries, image names like noaa/climate:64_chars_of_hash
get truncated which can cause ambiguities and issues in provenance. We can't
... | 25,785 |
def on_method_not_allowed(error):
"""Override the HTML 405 default."""
content = {"msg": "Method not allowed"}
return jsonify(content), 405 | 25,786 |
def dir_name(dir_path):
"""
转换零时文件夹、输入文件夹路径
:param dir_path: 主目录路径
:return:[tmp_dir, input_dir, res_dir]
"""
tmp_dir = dir_path + "tmp\\"
input_dir = dir_path + "input\\"
res_dir = dir_path + "result\\"
return tmp_dir, input_dir, res_dir | 25,787 |
def test_can_combine_sgr_codes():
"""Multiple SGR escape codes can be combined in one SGR code."""
assert sgr.create(code.BLACK, code.BG_RED) == \
code.CSI + code.BLACK + code.DELIMITER + code.BG_RED + 'm'
assert sgr.create(code.UNDERLINE, code.BLACK, code.BG_RED) == \
code.CSI + code.UNDERL... | 25,788 |
def profile_binning(
r,
z,
bins,
z_name="pm",
z_clip=None,
z_quantile=None,
return_bin=True,
plot=True,
):
"""Bin the given quantity z in r.
Parameters
----------
r: 1d array, binned x values
z: 1d array, binned y values
bins: 1d array, bins
Returns
... | 25,789 |
def sequence_to_synergy_sims(inputs, params):
"""same as sequence to synergy, but prep some other tensors first
"""
# set up orig seq tensor
inputs[DataKeys.ORIG_SEQ] = inputs[DataKeys.FEATURES]
# set up thresholds tensor
num_interpretation_tasks = len(params["importance_task_indices"])
... | 25,790 |
def create_invalid_points_feature_class(access_feature_class, invalid_reach_table, invalid_points_feature_class):
"""
Create a feature class of centroid points for the invalid reaches.
:param access_feature_class: Point feature class of all accesses.
:param invalid_reach_table: Table of reaches not ... | 25,791 |
def _gen_roi_func_constant(constant_roi):
"""
Return a RoI function which returns a constant radius.
See :py:func:`map_to_grid` for a description of the parameters.
"""
def roi(zg, yg, xg):
""" constant radius of influence function. """
return constant_roi
return roi | 25,792 |
def less_important_function(num: int) -> str:
"""
Example which is documented in the module documentation but not highlighted on the main page.
:param num: A thing to pass
:return: A return value
"""
return f'{num}' | 25,793 |
def main():
"""
Entry point.
"""
if os.geteuid() == 0:
sys.stdout.write("Please do not run poezio as root.\n")
sys.exit(0)
sys.stdout.write("\x1b]0;poezio\x07")
sys.stdout.flush()
from poezio import config
config.run_cmdline_args()
config.create_global_config()
... | 25,794 |
def weth_asset_data(): # pylint: disable=redefined-outer-name
"""Get 0x asset data for Wrapped Ether (WETH) token."""
return asset_data_utils.encode_erc20(
NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token
) | 25,795 |
def test_access_cli_list(script_info_cli_list):
"""Test of list cli command."""
runner = CliRunner()
result = runner.invoke(
access, ['list'],
obj=script_info_cli_list
)
assert result.exit_code == 0
assert result.output.find("open") != -1 | 25,796 |
def GetAudioFiles(config):
"""Print a list of audio files across all models
The output is one line for the source file and one line for the install file,
e.g.:
ucm-config/bxtda7219max.reef.BASKING/bxtda7219max.reef.BASKING.conf
/usr/share/alsa/ucm/bxtda7219max.basking/bxtda7219max.basking.conf
Args:... | 25,797 |
def print_depth_recursive(data, depth=1):
"""
Depth-first search algorithm (recursive) for printing all dictionary
keys with their depth.
"""
if not isinstance(data, Mapping):
raise TypeError("Input should be a dictionary.")
for key, val in data.items():
print("{0} {1}".format(k... | 25,798 |
def match_known_module_name(pattern):
"""
Matching with know module name.
Args:
pattern (Pattern): To be replaced pattern.
Returns:
str, matched module name, return None if not matched.
"""
matched_result = []
for ptn, module_name in BUILT_IN_MODULE_NAME.items():
if... | 25,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.