content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_slice(dimspins, y):
"""
Get slice of variable `y` inquiring the spinboxes `dimspins`.
Parameters
----------
dimspins : list
List of tk.Spinbox widgets of dimensions
y : ndarray or netCDF4._netCDF4.Variable
Input array or netcdf variable
Returns
-------
ndarr... | 39,600 |
def wrinkleContext(*args, **kwargs):
"""
This command creates a context that creates wrinkles.
Returns: `string` The name of the context created
"""
pass | 39,601 |
def query_real_confs(body=None): # noqa: E501
"""
query the real configuration value in the current hostId node
query the real configuration value in the current hostId node # noqa: E501
:param body:
:type body: dict | bytes
:rtype: List[RealConfInfo]
"""
if connexion.request.is_jso... | 39,602 |
def Run(get_initial_items,
switch_to_good,
switch_to_bad,
test_script,
test_setup_script=None,
iterations=50,
prune=False,
pass_bisect=None,
ir_diff=False,
noincremental=False,
file_args=False,
verify=True,
prune_iterations=... | 39,603 |
def validate_role_definition_body(cmd, ns):
""" Extracts role definition body """
import os
from azure.cli.core.util import get_file_json, shell_safe_json_parse
from azure.mgmt.cosmosdb.models import Permission, RoleDefinitionType
if ns.role_definition_body is not None:
if os.path.exists(ns... | 39,604 |
def purge_buffers(ft_handle: FtHandle, purge_type_mask: BufferType) -> None:
"""This function purges receive and transmit buffers in the device.
Args:
ft_handle: Handle to an opened D2XX device
purge_type_mask: Which buffers to purge (Tx and/or Rx)
Raises:
FtException: ... | 39,605 |
def is_data(data):
""" Check if a packet is a data packet. """
return len(data) > 26 and ord(data[25]) == 0x08 and ord(data[26]) in [0x42, 0x62] | 39,606 |
def _bool_value(ctx, define_name, default, *, config_vars = None):
"""Looks up a define on ctx for a boolean value.
Will also report an error if the value is not a supported value.
Args:
ctx: A Starlark context. Deprecated.
define_name: The name of the define to look up.
default: The val... | 39,607 |
def get_tf_metric(text):
"""
Computes the tf metric
Params:
text (tuple): tuple of words
Returns:
tf_text: format: ((word1, word2, ...), (tf1, tf2, ...))
"""
counts = [text.count(word) for word in text]
max_count = max(counts)
tf = [counts[i]/max_count for i in range(0, len(counts))]
return text, tf | 39,608 |
def R_transform_th(R_src, R_delta, rot_coord="CAMERA"):
"""transform R_src use R_delta.
:param R_src: matrix
:param R_delta:
:param rot_coord:
:return:
"""
if rot_coord.lower() == "model":
R_output = torch.matmul(R_src, R_delta)
elif rot_coord.lower() == "camera" or rot_coord.lo... | 39,609 |
def calculate_UMI_with_mismatch(UMIs):
"""
Corrected the mismatches in UMIs
input: UMI sequences and their counts;
return: Corrected unique UMI sequences
"""
if len(UMIs.keys()) == 1:
return [x for x in UMIs if UMIs[x]>0]
UMIs = sorted(UMIs.items(), key=lambda k: k[1], reverse=True)... | 39,610 |
def save_all_data(all_data, genes, analysis_name):
"""
Save all data components to results/all-data.csv.
:param all_data: dict
:param genes:
:param analysis_name:
:return:
"""
rows = list()
for mirna, values in all_data.items():
rows.append((mirna,) + values)
data_path = utils.get_path(f"analyses/{analysis_... | 39,611 |
def task_reformat_data():
"""Reformats all raw files for easier analysis"""
for data_type in data_sets:
yield {
'actions': ['python reformat_weather_data.py %(dependencies)s > %(targets)s'],
'file_dep': ['UK_{}_data.txt'.format(data_type)],
'targets': ['UK_{}_data.re... | 39,612 |
def create_import_data(properties):
"""
This function collects and creates all the asset data needed for the import process.
:param object properties: The property group that contains variables that maintain the addon's correct state.
:return list: A list of dictionaries containing the both the mesh an... | 39,613 |
def test_appendleft_child_after_appendleft_child_on_deque():
"""Testing appendleft_child after appending to deque."""
test_deque = Deque()
test_deque.appendleft_child('s')
test_deque.appendleft_child('tring')
assert test_deque.dll.head.data == ('tring') | 39,614 |
def get_data(URL, pl_start, pl_end):
"""Generic function. Should be called only when
it is checked if the URL is a cached playlist.
Returns a tuple containing the songs and name of
the playlist.
"""
logger.debug("Extracting Playlist Contents")
cached_playlist = CachedIE(URL, pl_start, pl_en... | 39,615 |
def create_master_trackbars(window):
"""Create trackbars for master window
Args:
window (Window): window that will be the master with trackbar conrols
"""
cv2.namedWindow(
window.name, cv2.WINDOW_NORMAL|cv2.WINDOW_KEEPRATIO|cv2.WINDOW_GUI_EXPANDED)
for t in window.transforms:
... | 39,616 |
def _parse_vertex_tuple(s):
"""Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k'.
...).
"""
vt = [0, 0, 0]
for i, c in enumerate(s.split("/")):
if c:
vt[i] = int(c)
return tuple(vt) | 39,617 |
def getKeyFromValue(dictionary, value):
"""
dictionary内に指定したvalueを持つKeyを検索して取得
"""
keys = [key for key, val in dictionary.items() if val == value]
if len(keys) > 0:
return keys[0]
return None | 39,618 |
def withdraw(dest):
"""
This function defines all the FlowSpec rules to be withdrawn via the iBGP Update.
////***update*** Add port-range feature similar to announce() - ADDED in TBowlby's code.
Args:
dest (str): IP Address of the Victim host.
Calls:
send_requests(messages): Calls ... | 39,619 |
def get_prefix(node):
"""
Strips off the name in the URI to give the prefixlabel...
:param node: The full URI string
:return: (prefix, label) as (string, string)
"""
if '#' in node:
name = node.split("#")[-1]
else:
# there must be no # in the prefix e.g. schema.org/
n... | 39,620 |
def test_interaction_run_phonon_solver_at_gamma_NaCl(nacl_pbe: Phono3py):
"""Test run_phonon_solver_at_gamma with nac_q_direction on NaCl.
Phonon calculation at Gamma without NAC is peformed at itr.init_dynamical_matrix().
The phonons at Gamma without NAC are saved in dedicated variables.
Phonon calcu... | 39,621 |
def test_find_repository_target_equivalent_fallback_to_default(monkeypatch,
mapping_data_for_find_repository_equiv):
"""
Test for the RepoMapDataHandler._find_repository_target_equivalent method.
Verifies that the method will find a target equi... | 39,622 |
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
"""Return the Pauli sigma_Y operator acting on the given qubit"""
return Pauli.sigma(qubit, 'Y', coefficient) | 39,623 |
async def main():
"""
Example for fetching each profile that is linked to a Bungie.net account, then
finds the light level for each character of the account.
"""
myAccount = await client.get_user("4611686018464828555")# for example
for profile in myAccount.destinyMemberships:
print("{0}:... | 39,624 |
def load_data_and_labels(filename):
"""Load sentences and labels"""
df = pd.read_csv(filename, compression='zip', dtype={'faits': object}, encoding = 'utf8')
selected = [ATTRIBUTE_TO_PREDICT, 'faits']
non_selected = list(set(df.columns) - set(selected))
df = df.drop(non_selected, axis=1) # Drop non selected colum... | 39,625 |
def ovc_search(request):
"""Method to do ovc search."""
try:
results = search_master(request)
except Exception as e:
print('error with search - %s' % (str(e)))
return JsonResponse(results, content_type='application/json',
safe=False)
else:
retu... | 39,626 |
def incdata(data, s):
"""
add 's' to each byte.
This is useful for finding the correct shift from an incorrectly shifted chunk.
"""
return b"".join(struct.pack("<B", (_ + s) & 0xFF) for _ in data) | 39,627 |
def fake_k8s_api_server(print_logs=False):
"""
Runs a fake k8s API server instance that supports generic get/list/watch/create/update
operations. It does **not** do any of the controller functionality, such as
creating pods based on a deployment, etc.
"""
with run_service(
"fakek8s", pr... | 39,628 |
def nonsquare_hungarian_matching(
weights: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
"""Hungarian matching with arbitrary shape.
The matchers_ops.hungarian_matching supports only squared weight matrices.
This function generalizes the hungarian matching to nonsquare cases by padding
the weights to a square... | 39,629 |
def search(
locations,
species=None,
inlet=None,
instrument=None,
find_all=True,
start_datetime=None,
end_datetime=None,
):
""" Search for gas data (optionally within a daterange)
TODO - review this function - feel like it can be tidied and simplified
Args:
... | 39,630 |
def strip_non_printable(value):
"""
Removes any non-printable characters and adds an indicator to the string
when binary characters are fonud
:param value: the value that you wish to strip
"""
if value is None:
return None
# Filter all non-printable characters
# (note that we m... | 39,631 |
def delete_one_test(client, module):
"""Deletes a record."""
id = get_test_id(module)
res = client.delete(f"/{module}/{id}")
assert res.json['id'] == id | 39,632 |
def flatten(name):
"""Get a flatten layer.
Parameters
----------
name : string
the name of the flatten layer
Returns
-------
flatten : keras.layers.core.Flatten
"""
if LIB_TYPE == "keras":
return Flatten(name=name) | 39,633 |
def tangent_circle(dist, radius):
"""
return tangent angle to a circle placed at (dist, 0.0) with radius=radius
For non-existing tangent use 100 degrees.
"""
if dist >= radius:
return math.asin(radius/float(dist))
return math.radians(100) | 39,634 |
def test_post_valid_cohort(testapp, institution, project, cohort):
""" Valid cohort post should succeed """
res = testapp.post_json('/cohort', cohort, status=201)
assert 'display_title' in res
assert 'cohort_phenotypic_features' in res | 39,635 |
def test_sync_server_without_pipeline_enabled(sync_server, data, expected_status,
expected_children):
"""
Nearly end-to-end test of how Controller serves .sync as a POST
Tests case where metadata.labels.pipelines.kubeflow.org/enabled does not
exist and thus... | 39,636 |
def find_backup_path(docsents, q, cand, k=40):
"""
If no path is found create a dummy backup path
:param docsents:
:param q:
:param cand:
:param k:
:return:
"""
path_for_cand_dict = {"he_docidx": None,
"he_locs": None,
"e1wh_loc": N... | 39,637 |
def state_transitions():
"""Simplified state transition dictionary"""
return {
"E": {"A": {"(0, 9)": 1}},
"A": {"I": {"(0, 9)": 1}},
"I": {"H": {"(0, 9)": 1}},
"H": {"R": {"(0, 9)": 1}}
} | 39,638 |
def test_list_my_groups_as_support_user(list_my_groups_context):
"""
Test that we can get all the groups as a support user, even without ignore_access
"""
results = list_my_groups_context.support_user_client.list_my_groups(status=200)
assert_that(len(results["groups"]), greater_than(50))
assert... | 39,639 |
def run_test():
"""for test purpose only"""
speclist = read_spec_config("spec_conf.json")
engine = create_engine('sqlite:///orm.db', echo=True)
Base = declarative_base()
orm_classes = [model_factory(i, Base) for i in speclist]
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engi... | 39,640 |
def inference(module: nn.Module) -> Iterator[None]:
"""Enables inference mode for module.
Switches all children to eval mode.
Disables gradient flow.
All the tensors created in this mode are marked as inference,
and they are NOT COMPATIBLE WITH AUTOGRAD AT ALL
(used in JIT, backward, etc.).
... | 39,641 |
def send(socket, action, opts=None, request_response=True, return_type='auto'):
"""Send a request to an RPC server.
Parameters
----------
socket : zmq socket
The ZeroMQ socket that is connected to the server.
action : str
Name of action server should perform. See :func:`RPCClie... | 39,642 |
def brighter(data, data_mean=None):
"""
Brighter set of parameters for density remap.
Parameters
----------
data : numpy.ndarray
data_mean : None|float|int
Returns
-------
numpy.ndarray
"""
return clip_cast(amplitude_to_density(data, dmin=60, mmult=40, data_mean=data_mean)... | 39,643 |
def get_configuration(args_in: List[str]) -> Configuration:
"""
Retrieves configuration from the command line or environment variables.
Parameters
----------
args_in: List[str]
The system arguments received by the main script
Returns
-------
An object of type Configuration
... | 39,644 |
def main() -> int:
"""Entry point for 'compress'."""
try:
argv = parser.parse_args()
buffersize = int(argv.buffersize * 1024**2)
action = compress if argv.decompress is False else decompress
schemes = {getattr(argv, scheme): scheme for scheme in SCHEMES}
if True not in ... | 39,645 |
def get_lensed_host_fluxes(host_truth_db_file, image_dir, bands='ugrizy',
components=('bulge', 'disk'),
host_types=('agn', 'sne'), verbose=False):
"""
Loop over entries in `agn_hosts` and `sne_hosts` tables in
the host_truth_db_file and compute fluxes (w... | 39,646 |
def load_challenges() -> list[Challenge]:
"""
Loads all challenges.
Returns
-------
list[Challenge]
All loaded challenges.
"""
__challenges.clear()
modules = []
for lib in (Path(__file__).parent / "saves/challenges").iterdir():
if not lib.name.endswith(".py") or lib.... | 39,647 |
def tracks2Csv(tracks, csvPath, overwriteCsv=False):
"""
Saves list of 'Track' objects to a CSV file
Input:
tracks: List of Track objects
csvPath: String path to csv file
overwriteCsv: Whether to overwrite existing CSV files
"""
df = tracks2Dataframe(tracks... | 39,648 |
def get_new_user_data(GET_params):
"""Return the data necessary to create a new OLD user or update an existing one.
:param GET_params: the ``request.GET`` dictionary-like object generated by
Pylons which contains the query string parameters of the request.
:returns: A dictionary whose values ar... | 39,649 |
def add_heatmap_summary(feature_query, feature_map, name):
"""Plots dot produce of feature_query on feature_map.
Args:
feature_query: Batch x embedding size tensor of goal embeddings
feature_map: Batch x h x w x embedding size of pregrasp scene embeddings
name: string to name tensorflow summaries
Ret... | 39,650 |
def ParseVecFile(filename):
"""Parse a vector art file and return an Art object for it.
Right now, handled file types are: EPS, Adobe Illustrator, PDF
Args:
filename: string - name of the file to read and parse
Returns:
geom.Art: object containing paths drawn in the file.
Retur... | 39,651 |
def batchnorm_to_float(module):
"""Converts batch norm to FP32"""
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
module.float()
for child in module.children():
batchnorm_to_float(child)
return module | 39,652 |
def test_exception_column_context_transform(simple_dataframe):
"""
If an exception is raised when transforming a column,
the exception includes the name of the column being transformed
"""
class FailingTransformer(object):
def fit(self, X):
pass
def transform(self, X):
... | 39,653 |
def get_mat_2d(sequence, rnn=False):
"""Uses aa_to_map to turn a sequence into a 3D array representation of the
protein.
"""
if rnn:
mat = np.zeros((len(sequence), 36))
for i, aa in enumerate(sequence):
mat[i] = aa_to_map(aa)[:,:6,:].flatten()
else... | 39,654 |
def TimeSec():
"""[Takes current time in and convert into seconds.]
Returns:
[float]: [Time in seconds]
"""
now = datetime.now()
return now.second+(now.minute*60)+(now.hour*60*60) | 39,655 |
def SinePolicyExample():
"""An example of minitaur walking with a sine gait."""
randomizer = (minitaur_env_randomizer.MinitaurEnvRandomizer())
environment = minitaur_gym_env.MinitaurBulletEnv(
render=True,
motor_velocity_limit=np.inf,
pd_control_enabled=True,
hard_reset=False,
env_ra... | 39,656 |
def partition_variable(variable, partition_dict):
"""
As partition_shape() but takes a mapping of dimension-name to number
of partitions as it's second argument. <variable> is a VariableWrapper
instance.
"""
partitions = []
for dim in variable.dimensions:
if dim.name in partition_d... | 39,657 |
def strip(folder, classifier_prefix, correct_prediction, correct_names=None, incorrect_names=None, drop_non_dicoms=False):
"""Strip a folder of non-DICOM files and of image files that are not of the predicted classification."""
if drop_non_dicoms:
drop_non_dicom(folder)
filepaths = get_files(folder,... | 39,658 |
def _get_object_properties(agent,
properties,
obj_type,
obj_property_name,
obj_property_value,
include_mors=False):
"""
Helper method to simplify retrieving of properties
T... | 39,659 |
def get_crypto_currency_pairs(info=None):
"""Gets a list of all the cypto currencies that you can trade
:param info: Will filter the results to have a list of the values that correspond to key that matches info.
:type info: Optional[str]
:returns: If info parameter is left as None then the list will co... | 39,660 |
def sparse_graph_convolution_layers(name, inputs, units, reuse=True):
"""
This one is used by the Joint_SMRGCN model;
A crude prototypical operation
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE if reuse else False):
# adj_tensor: list (size nb_bonds) of [length, length] matrices
... | 39,661 |
def update_contour():
"""
Finds contours in the current color image and uses them to update contour_center
and contour_area
"""
global contour_center
global contour_area
global color_list
image = rc.camera.get_color_image()
if image is None:
contour_center = None
co... | 39,662 |
def main(argv):
"""
The main function to invoke the powerfulseal cli
"""
args = parse_args(args=argv)
if args.mode is None:
return parse_args(['--help'])
##########################################################################
# VALIDATE POLICY MODE
######################... | 39,663 |
def update_or_create_tags(observer, repo, tag=None, type_to_update=None):
"""Create or update tags."""
observer.update_state(
state='PROGRESS',
meta='Retrieving data and media from Github'
)
git = GithubAPI(repo)
if tag:
data, media = git.get_data(tag)
if type_to_up... | 39,664 |
def confirm_api_access_changes(request):
"""Renders the confirmation page to confirm the successful changes made to
the API access settings for the superuser's group.
Parameters:
request - The request object sent with the call to the confirm page if
the requested changes were su... | 39,665 |
def output_sheet(options: Options, config: Config, markdown_outputs: list,
message_outputs: list, sheet):
"""send the sheet to the output functions"""
extra_values = config.get_extra_values()
markdowns = list(
markdown_emails_for_date(sheet=sheet,
send_date=op... | 39,666 |
def mpl_hill_shade(data, terrain=None,
cmap=DEF_CMAP, vmin=None, vmax=None, norm=None, blend_function=rgb_blending,
azimuth=DEF_AZIMUTH, elevation=DEF_ELEVATION):
""" Hill shading that uses the matplotlib intensities. Is only for making comparison between
blending me... | 39,667 |
def helm_install(perm_ctx: NamespacePermCtx):
"""helm install 到某个命名空间""" | 39,668 |
def nonzeros(m, row):
""" returns the non zeroes of a row in csr_matrix """
for index in range(m.indptr[row], m.indptr[row + 1]):
yield m.indices[index], m.data[index] | 39,669 |
def init_h2o():
"""
Start up H2o
"""
h2o.init(nthreads=-1) | 39,670 |
def img_docs(filename='paths.ini', section='PATHS'):
"""
Serve the PATH to the img docs directory
"""
parser = ConfigParser()
parser.read(filename)
docs = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
docs[param[0]] = par... | 39,671 |
def temp_file():
"""
Creates a temp file and deletes it afterwards
:return:
"""
temp = tempfile.NamedTemporaryFile(delete=False)
try:
yield temp
finally:
temp.close()
os.unlink(temp.name) | 39,672 |
def KGPhenio(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "current", **kwargs
) -> Graph:
"""R... | 39,673 |
def _x_mul(a, b, digit=0):
"""
Grade school multiplication, ignoring the signs.
Returns the absolute value of the product, or None if error.
"""
size_a = a.numdigits()
size_b = b.numdigits()
if a is b:
# Efficient squaring per HAC, Algorithm 14.16:
# http://www.cacr.math.uw... | 39,674 |
def server_version(headers):
"""Extract the firmware version from HTTP headers."""
version_re = re.compile(r"ServerTech-AWS/v(?P<version>\d+\.\d+\w+)")
if headers.get("Server"):
match = version_re.match(headers["Server"])
if match:
return match.group("version") | 39,675 |
def init_test_env(setting_path, output_path, file_list,fname_list):
"""
create test environment, the file list would be saved into output_path/reg/test/file_path_list.txt,
a corresponding auto-parsed filename list would also be saved in output/path/reg/test/file_name_list.txt
:param setting_path: the ... | 39,676 |
def slice_constant(data, batch_size=32, name='constant_data', global_step=None):
"""Provide a slice based on the global_step.
This is useful when the entire data array can be stored in memory because it
allows you to feed the data very efficiently.
Args:
data: A numpy array or tensor.
batch_size: The ... | 39,677 |
def es_subcadena(adn1, adn2):
"""
(str, str) -> bool
>>> es_subcadena('gatc', 'tta')
False
>>> es_subcadena('gtattt', 'atcgta')
False
:param:adn1:str:primera cadena a comparar
:param:adn2:str:segunda cadena a comparar
:return:bool:verificacion si una es subcadena de la otra
"""... | 39,678 |
def print_possible_values(column: pd.Series) -> None:
"""Print all distinct values of a given column.
Args:
column: Column to evaluate.
"""
print(f"Possible values in '{column.name}':")
print(np.sort(column.dropna().unique())) | 39,679 |
def get_labels_and_features(nested_embeddings):
""" returns labels and embeddings
"""
x = nested_embeddings[:,:-1]
y = nested_embeddings[:,-1]
return x,y | 39,680 |
def all_(f : a >> bool, t : r(a)) -> bool:
"""
all :: Foldable r => (a -> bool) -> r a -> bool
Determines whether all elements of the structure satisfy the predicate.
"""
return DL.all_(toList(t)) | 39,681 |
def log_binom_sum(lower, upper, obs_vote, n0_curr, n1_curr, b_1_curr, b_2_curr, prev):
"""
Helper function for computing log prob of convolution of binomial
"""
# votes_within_group_count is y_0i in Wakefield's notation, the count of votes from
# given group for given candidate within precinct i (u... | 39,682 |
def parse_locator(src):
""" (src:str) -> [pathfile:str, label:either(str, None)]
"""
pathfile_label = src.split('#')
if len(pathfile_label)==1:
pathfile_label.append(None)
if len(pathfile_label)!=2:
raise ValueError('Malformed src: %s' % (src))
return pathfile_label | 39,683 |
def detect_seperator(path, encoding):
"""
:param path: pathlib.Path objects
:param encoding: file encoding.
:return: 1 character.
"""
# After reviewing the logic in the CSV sniffer, I concluded that all it
# really does is to look for a non-text character. As the separator is
# determine... | 39,684 |
def pr_at_k(df, k):
"""
Returns p/r for a specific result at a specific k
df: pandas df with columns 'space', 'time', 'y_true', and 'y_pred'
k: the number of obs you'd like to label 1 at each time
"""
#static traits of df
universe = df['time'].nunique()
p = df['y_true'].... | 39,685 |
def draw_segm(im, np_segms, np_label, np_score, labels, threshold=0.5, alpha=0.7):
"""
Draw segmentation on image.
"""
mask_color_id = 0
w_ratio = .4
color_list = get_color_map_list(len(labels))
im = np.array(im).astype('float32')
clsid2color = {}
np_segms = np_segms.astype(np.uint8)... | 39,686 |
def test_query_transactions(rotkehlchen_api_server):
"""Test that querying the avalanche transactions endpoint works as expected
This test uses real data.
"""
async_query = random.choice([False, True])
response = requests.get(
api_url_for(
rotkehlchen_api_server,
'av... | 39,687 |
def solve(board):
"""
solve a sudoku board using backtracking
param board: 2d list of integers
return: solution
"""
space_found = find_empty_space(board)
if not space_found:
return True
else:
row, col = space_found
for i in range(1, 10):
if valid_number(board,... | 39,688 |
def verify_interface(cls, interface):
"""Verify that all abstract methods are implemented"""
for attr, method in inspect.getmembers(interface):
if isinstance(method, FunctionWrapper):
if method.abstract:
# Check for method implementation
if not hasattr(cls, at... | 39,689 |
def check(s: str) -> None:
"""
Checks if the given input string of brackets are balanced or not
Args:
s (str): The input string
"""
stack: List[str] = []
def get_opening(char: str) -> Optional[str]:
"""
Gets the corresponding opening braces of the given input chara... | 39,690 |
def format_address(msisdn):
"""
Format a normalized MSISDN as a URI that ParlayX will accept.
"""
if not msisdn.startswith('+'):
raise ValueError('Only international format addresses are supported')
return 'tel:' + msisdn[1:] | 39,691 |
def copytree(src, dst, ignore='.gitkeep'):
""" Recursively copy's directory tree
Taken from: https://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
"""
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(s... | 39,692 |
def get_nag_statistics(nag):
"""Return a report containing all NAG statistics"""
report = """Constants: {0}
Inputs: {1}
NANDs: {2}
Outputs: {3}
Min. I/O distance: {4}
Max. I/O distance: {5}""".format(
nag.constant_number,
nag.input_number,
nag.nand_number,
nag... | 39,693 |
def svm_loss_naive(w, x, y, reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on mini-batches of N examples.
:param w: A numpy array of shape (D, C) containing weights.
:param x: A numpy array of shape (N, D) con... | 39,694 |
def unread(b, n):
"""Given a filelike object and an integer, unread that many characters from
the object."""
b.seek(b.tell() - n) | 39,695 |
def create_backup(storage, remote, parent=None):
""" Create a new backup of provided remote and return its backup object.
.. warning:: Do not forget to add a label on returned backup to avoid its
removal by the garbage collector.
"""
if parent:
parent_ref = storage.resolve(parent)
... | 39,696 |
def get_pairwise_correlation(population_df, method="pearson"):
"""Given a population dataframe, calculate all pairwise correlations.
Parameters
----------
population_df : pandas.core.frame.DataFrame
Includes metadata and observation features.
method : str, default "pearson"
Which co... | 39,697 |
def get_game_raw_pbp_filename(season, game):
"""
Returns the filename of the raw pbp folder
:param season: int, current season
:param game: int, game
:return: str, /scrape/data/raw/pbp/[season]/[game].zlib
"""
return os.path.join(organization.get_season_raw_pbp_folder(season), str(game) + ... | 39,698 |
def plot_route(cities, route, name='diagram.png', ax=None):
"""Plot a graphical representation of the route obtained"""
mpl.rcParams['agg.path.chunksize'] = 10000
if not ax:
fig = plt.figure(figsize=(5, 5), frameon = False)
axis = fig.add_axes([0,0,1,1])
axis.set_aspect('equal', ad... | 39,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.