content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def last_check():
"""Return the date of the last check"""
cache = cache_file()
if cache:
return os.path.getmtime(cache_file())
# Fallback
return time.time() | 41,500 |
def is_constant_type(expression_type):
"""Returns True if expression_type is inhabited by a single value."""
return (expression_type.integer.modulus == "infinity" or
expression_type.boolean.HasField("value") or
expression_type.enumeration.HasField("value")) | 41,501 |
def compute_tuning_improvement_sds_5_4():
"""Compute average improvement during tuning, in sds"""
data = _get_tuning_results_df()
delta = data['delta'].dropna()
result = delta.mean()
fn = OUTPUT_DIR.joinpath('5_4_tuning_improvement_sds.txt')
with fn.open('w') as f:
f.write(
... | 41,502 |
def make_grid(batch_imgs, n_rows):
"""Makes grid of images."""
batch_imgs = np.array(batch_imgs)
assert len(batch_imgs.shape) == 4, f'Invalid shape {batch_imgs.shape}'
batchsize, height, width, channels = batch_imgs.shape
n_cols = (batchsize + n_rows - 1) // n_rows
grid = np.zeros((n_rows * height, n_cols... | 41,503 |
def getTypes(parasites):
"""Take parasites and assign a type to them -- like in pokemon! Then
return the list of parasites."""
bugsOut = []
for i in range(len(parasites)):
bugsOut.append([i+1, parasites[i],
random.choice(["fire", "water", "grass"])])
return bugsOut | 41,504 |
def test_cache_function_new(FunctionType):
"""Test that new u[x, y] instances don't cache"""
grid = Grid(shape=(3, 4))
u0 = FunctionType(name='u', grid=grid)
u0.data[:] = 6.
u1 = FunctionType(name='u', grid=grid)
u1.data[:] = 2.
assert np.allclose(u0.data, 6.)
assert np.allclose(u1.data,... | 41,505 |
def split_copy(src: str, dest: str) -> None:
"""
Splits src into N number of files and sends one to each remote destination
using the input src name
Args:
src: Path to source file
dest: Full path to destination
"""
ext = os.path.splitext(src)[1]
basename = os.path.basename(s... | 41,506 |
def jsonUsers(request):
"""Export user list to JSON"""
user_list = list(CustomUser.objects.values())
return JsonResponse(user_list, safe=False) | 41,507 |
def farthest_point_sample(points, num_points=1024):
"""
Input:
points: a point set, in the format of NxM, where N is the number of points, and M is the point dimension
num_points: required number of sampled points
"""
def compute_dist(centroid, points):
return np.sum((centroid - ... | 41,508 |
def resolve_shx_font_name(font_name: str) -> str:
""" Map SHX font names to TTF file names. e.g. 'TXT' -> 'txt_____.ttf' """
# Map SHX fonts to True Type Fonts:
font_upper = font_name.upper()
if font_upper in SHX_FONTS:
font_name = SHX_FONTS[font_upper]
return font_name | 41,509 |
def select_event_by_name(session, event_name):
"""
Get an event by name
Parameters
----------
session :
database connexion session
event_name : str
name of the RAMP event
Returns
-------
`Event` instance
"""
event = session.query(Event).filter(Event.name ==... | 41,510 |
def repoExitError(message):
"""
Exits the repo manager with error status.
"""
wrapper = textwrap.TextWrapper(
break_on_hyphens=False, break_long_words=False)
formatted = wrapper.fill("{}: error: {}".format(sys.argv[0], message))
sys.exit(formatted) | 41,511 |
def attention_mask_creator(input_ids):
"""Provide the attention mask list of lists: 0 only for [PAD] tokens (index 0)
Returns torch tensor"""
attention_masks = []
for sent in input_ids:
segments_ids = [int(t > 0) for t in sent]
attention_masks.append(segments_ids)
return torch.tensor... | 41,512 |
def extension_from_parameters():
"""Construct string for saving model with annotation of parameters"""
ext = ''
ext += '.A={}'.format(ACTIVATION)
ext += '.B={}'.format(BATCH_SIZE)
ext += '.D={}'.format(DROP)
ext += '.E={}'.format(NB_EPOCH)
if FEATURE_SUBSAMPLE:
ext += '.F={}'.format(... | 41,513 |
def gen_image_coeff(filter_or_bp, pupil=None, mask=None, module='A',
coeff=None, coeff_hdr=None, sp_norm=None, nwaves=None,
fov_pix=11, oversample=4, return_oversample=False, use_sp_waveset=False,
**kwargs):
"""Generate PSF
Create an image (direct, coronagraphic, grism, or DHS) based on a set of
... | 41,514 |
def rotateBoard90(b):
"""b is a 64-bit score4 board consists of 4 layers
Return: a 90 degree rotated board as follow (looking from above)
C D E F 0 4 8 C
8 9 A B ==> 1 5 9 D
4 5 6 7 2 6 A E
0 1 2 3 3 7 B F
"""
return rotateLayer90(b & 0xFFFF) \
| rota... | 41,515 |
def register_preset_path(path):
"""Add filepath to registered presets
:param path: the directory of the preset file(s)
:type path: str
:return:
"""
if path in _registered_paths:
return log.warning("Path already registered: %s", path)
_registered_paths.append(path)
return path | 41,516 |
def aggregate(
predict_csv: builtins.str,
n_models: builtins.int,
*,
threshold: builtins.float = 0.5,
fill_holes: builtins.bool = False,
min_lesion_size: builtins.int = 3,
aggregation_type: builtins.str = "mean",
num_workers: typing.Optional[builtins.int] = None,
) -> None:
"""aggreg... | 41,517 |
def das(var, level=0):
"""Single dispatcher that generates the DAS response."""
raise StopIteration | 41,518 |
def test(c, module=None, runner=None, opts=None, pty=True):
"""
Run a Spec or Nose-powered internal test suite.
"""
runner = runner or 'spec'
# Allow selecting specific submodule
specific_module = " --tests=tests/%s.py" % module
args = (specific_module if module else "")
if opts:
... | 41,519 |
def set_pause_orchestration(
self,
ne_pk_list: list[str],
) -> bool:
"""Set appliances to pause orchestration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - pauseOrchestration
- POST
- /pauseOrchestration
... | 41,520 |
def unwrap(value: str, wrap_char: str) -> str:
"""Unwraps a given string from a character or string.
:param value: the string to be unwrapped
:param wrap_char: the character or string used to unwrap
:return: unwrapped string or the original string if it is not
quoted properly with the w... | 41,521 |
def round_to_memory_units(memory_bytes, round_up):
"""Round bytes to the nearest memory unit."""
return from_memory_units(to_memory_units(memory_bytes, round_up)) | 41,522 |
def get_modification_time(input_dir_or_zip):
"""Get time of most recent content modification as seconds since the epoch."""
path = 'routes.txt'
if os.path.isdir(input_dir_or_zip):
return int(os.stat(os.path.join(input_dir_or_zip, path)).st_mtime)
else:
with zipfile.ZipFile(input_dir_or_z... | 41,523 |
def clone(translation):
""" Clones the given translation, creating an independent copy. """
clone = gettext.GNUTranslations()
clone._catalog = translation._catalog.copy()
if hasattr(translation, 'plural'):
clone.plural = types.FunctionType(
translation.plural.__code__,
tr... | 41,524 |
def get_general_channel():
"""Returns just the general channel of the workspace"""
channels = get_all_channels()
for channel in channels:
if (channel['is_general']):
return channel | 41,525 |
def nonrigid_rotations(spc_mod_dct_i):
""" Determine if the rotational partition function for a certain
species should be calculated according to some non-rigid model.
This determination solely relies on whether has specified the
use of a non-rigid model for the species.
:param spc... | 41,526 |
def general_standing():
"""
It gives the general standing based on the current matchday. Note that it depends on the parameters that are
imported at the beginning of the notebook, specifically Results, hence in order to refresh it needs to be run
after Results is created from the utilities script.
T... | 41,527 |
def pixwt(xc, yc, r, x, y):
"""
; ---------------------------------------------------------------------------
; FUNCTION Pixwt( xc, yc, r, x, y )
;
; Compute the fraction of a unit pixel that is interior to a circle.
; The circle has a radius r and is centered at (xc, yc). The center of
; t... | 41,528 |
def test_2d_gradient_3d_data_no_axes(deriv_4d_data):
"""Test for failure of 2D gradient with 3D data and no axes parameter."""
test = deriv_4d_data[0]
with pytest.raises(ValueError) as exc:
gradient(test, deltas=(1, 1))
assert 'must match the number of dimensions' in str(exc.value) | 41,529 |
def predict(net, inputs, use_GPU=False, in_type='numpy'):
"""Make predictions using a well-trained network.
Parameters
----------
inputs : numpy array or torch tensor
The inputs of the network.
use_GPU : bool
If True, calculate using GPU, otherwise, calculate using CPU.
... | 41,530 |
def tag_from_ci_env_vars(ci_name, pull_request_var, branch_var, commit_var):
"""
Checks if the CI environmental variables to check for a pull request,
commit id and band commit branch are present.
:return: String with the CI build information, or None if the CI
environmental variables could... | 41,531 |
def test_say_hello() -> None:
"""Test that standard works."""
world = HelloWorld()
world.say_hello() | 41,532 |
def load_model() -> modellib.MaskRCNN:
"""
This function loads the segmentation model and returns it. The weights
are downloaded if necessary.
Returns:
modellib.MaskRCNN: MRCNN model with trained weights
"""
# Define directory with trained model weights
root_dir = os.path.split(__fi... | 41,533 |
def svn_mergeinfo_catalog_merge(*args):
"""
svn_mergeinfo_catalog_merge(svn_mergeinfo_catalog_t mergeinfo_catalog, svn_mergeinfo_catalog_t changes_catalog,
apr_pool_t result_pool,
apr_pool_t scratch_pool) -> svn_error_t
"""
return _core.svn_mergeinfo_catalog_merge(*args) | 41,534 |
def test_list_double_enumeration_nistxml_sv_iv_list_double_enumeration_1_5(mode, save_output, output_format):
"""
Type list/double is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/double/Schema+Instance/NISTSchema-SV-IV-list-double-enumeration-1.xsd",
instan... | 41,535 |
def results_to_log(date, net, epochs, lr, acc_train, mcc_train, auc_train, loss_train, acc_test, mcc_test, auc_test, loss_test, early_stopping, filename):
"""Append the network results to a log file"""
with open(filename, 'a') as f:
f.write("#"*100)
f.write("\nNetwork ran date: {} and trained on... | 41,536 |
def save_decoder(decoder: TFGraphRecordDecoder, path: Text) -> None:
"""Saves a TFGraphRecordDecoder to a SavedModel."""
tf.saved_model.save(decoder, path) | 41,537 |
def _delete_token_in_travis(user, project, token_name):
"""update the binstar token in travis."""
from conda_smithy.ci_register import (
travis_endpoint,
travis_headers,
travis_get_repo_info,
)
headers = travis_headers()
repo_info = travis_get_repo_info(user, project)
r... | 41,538 |
def normalize_const(v):
"""
Normalize a numpy array of floats or doubles.
"""
return v / numpy.linalg.norm(v) | 41,539 |
def _decode_block_str(block_str):
""" Decode block definition string
Gets a list of block arg (dicts) through a string notation of arguments.
E.g. ir_r2_k3_s2_e1_i32_o16_se0.25_noskip
All args can exist in any order with the exception of the leading string which
is assumed to indicate the block ty... | 41,540 |
def make_lc_resolver(type_: type[_T], /) -> collections.Callable[..., collections.Awaitable[_T]]:
"""Make an injected callback which resolves a LazyConstant.
Notes
-----
* This is internally used by `inject_lc`.
* For this to work, a `LazyConstant` must've been set as a type
dependency for th... | 41,541 |
def get_md5(string):
"""
Get md5 according to the string
"""
byte_string = string.encode("utf-8")
md5 = hashlib.md5()
md5.update(byte_string)
result = md5.hexdigest()
return result | 41,542 |
def clean_docs_and_uniquify(docs):
"""
normalize docs and uniquify the doc
:param docs:
:return:
"""
docs = [normalize(t) for t in docs if isinstance(t, str)]
docs = dedupe(docs)
return docs | 41,543 |
def shard_init_helper_(init_method, tensor: Tensor, **kwargs: Any) -> None:
"""
Helper function to initialize shard parameters.
"""
if hasattr(tensor, _PARALLEL_DIM):
local_rank = get_rank()
group = get_group()
world_size = get_world_size()
parallel_dim = getattr(tensor,... | 41,544 |
def segment_zentf_tiling(image2d, model,
tilesize=1024,
classlabel=1,
overlap_factor=1):
"""Segment a singe [X, Y] 2D image using a pretrained segmentation
model from the ZEN. The out will be a binary mask from the prediction
of ZEN ... | 41,545 |
def setup_train_and_sub_df(path):
"""
Sets up the training and sample submission DataFrame.
Args:
path (str): Base diretory where train.csv and sample_submission.csv are located
Returns:
tuple of:
train (pd.DataFrame): The prepared training dataframe with the extra columns:
... | 41,546 |
def import_tests(logger, path, pattern, use_abs=True):
"""Find and import all tests from a given path."""
logger.info('Loading tests from "%s" with pattern: "%s"', path, pattern)
tests = glob.glob(os.path.join(path, "{}.py".format(pattern)))
for test in tests:
relpath = os.path.relpath(test)[:-3... | 41,547 |
def test_es_preference_param(app):
"""Test the preference param is correctly added in a request."""
RecordsSearch.__bases__ = (SpySearch,)
with app.test_request_context('/', headers={'User-Agent': 'Chrome'},
environ_base={'REMOTE_ADDR': '212.54.1.8'}):
rs = Records... | 41,548 |
def key2cas(key):
"""
Find the CAS Registry Number of a chemical substance using an IUPAC InChIKey
:param key - a valid InChIKey
"""
if _validkey(key):
hits = query('InChIKey=' + key, True)
if hits:
if len(hits) == 1:
return hits[0]['rn']
else:... | 41,549 |
def connect_server(server, username, startpage, sleep_func=time.sleep, tracktype='recenttracks'):
""" Connect to server and get a XML page."""
if server == "libre.fm":
baseurl = 'http://alpha.libre.fm/2.0/?'
urlvars = dict(method='user.get%s' % tracktype,
api_key=('lastexport... | 41,550 |
def test_sadf():
"""Just make sure that the modules can be imported and that the
SadfCommand can be instantiated.
"""
sadf.SadfCommand(start_time='11:00:00', end_time='13:00:00')
assert 1 is 1 | 41,551 |
def eigenvalue_nonunitary_diamondnorm(A, B, mxBasis):
""" Eigenvalue nonunitary diamond distance between A and B """
d2 = A.shape[0]
evA = _np.linalg.eigvals(A)
evB = _np.linalg.eigvals(B)
return (d2 - 1.0) / d2 * _np.max(_tools.minweight_match(evA, evB, lambda x, y: abs(abs(x) - abs(y)),
... | 41,552 |
def main(**kwags):
""" Authenticate to AMP for Endpoints Console using a Cisco Security account
Download connector for chosen OS, group, and settings and save to disk
"""
user = kwags.get("user")
password = kwags.get("password")
region = kwags.get("region")
group = kwags.get("group")
... | 41,553 |
def str_to_int(value):
"""Convert str to int if possible
Args:
value(str): string to convert
Returns:
int: converted value. str otherwise
"""
try:
return int(value)
except ValueError:
return value | 41,554 |
def json_response(data):
"""this function is used for ajax
def route(request):
return json_response(t.json())
"""
header = 'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n'
body = json.dumps(data, ensure_ascii=False, indent=8)
r = header + '\r\n' + body
return r.encod... | 41,555 |
def linePointXY(l,p,inside=True,distance=False,params=False):
"""
For a point ``p`` and a line ``l`` that lie in the same XY plane,
compute the point on ``l`` that is closest to ``p``, and return
that point. If ``inside`` is true, then return the closest distance
point between the point and the lin... | 41,556 |
def config_port_type(dut, interface, stp_type="rpvst", port_type="edge", no_form=False, cli_type="klish"):
"""
API to config/unconfig the port type in RPVST
:param dut:
:param port_type:
:param no_form:
:return:
"""
commands = list()
command = "spanning-tree port type {}".format(port... | 41,557 |
def compute_output_pattern(mask_path, crop_output):
"""
Computes the output pattern of the region cropped (without the source file prefix)
Args:
mask_path: path to the masks
crop_output: If True the output is cropped, and the descriptor CropRoi must exist
Returns:
the output patt... | 41,558 |
def check_strand(strand):
""" Check the strand format. Return error message if the format is not as expected. """
if (strand != '-' and strand != '+'):
return "Strand is not in the expected format (+ or -)" | 41,559 |
def to_halfpi(rin, za): # match with a shunt input l net, rin > za.real
"""
"""
ra, xa = za.real, za.imag
xd = np.sqrt(ra * (rin - ra))
if np.iscomplex(xd): raise ValueError
x2 = np.array([-xa - xd, -xa + xd])
x1 = -(ra**2 + (x2 + xa)**2) / (x2 + xa)
return np.transpose([x1 * 1j, x2... | 41,560 |
def load_config_or_exit(workdir="."):
"""Loads the challenge configuration file from the current directory, or prints a message and exits the script if it doesn't exist.
Returns:
dict: The config
"""
path = Path(workdir)
if (path / "challenge.yml").exists():
path = path / "challenge... | 41,561 |
def checkOnes(x, y):
"""
Checks if any of the factors in y = 1
"""
_ = BranchingValues()
_.x = 1
for i in _range(len(y)):
if _if(y[i][0] == 1):
_.x = 0
_endif()
if _if(y[i][1] == 1):
_.x = 0
_endif()
_endfor()
return _.x | 41,562 |
def get_type_specs_from_feature_specs(
feature_specs: Dict[str, common_types.FeatureSpecType]
) -> Dict[str, tf.TypeSpec]:
"""Returns `tf.TensorSpec`/`tf.SparseTensorSpec`s for the given feature spec.
Returns a dictionary of type_spec with the same type and shape as defined by
`feature_specs`.
Args:
f... | 41,563 |
def read_fortran_namelist(fileobj):
"""Takes a fortran-namelist formatted file and returns appropriate
dictionaries, followed by lines of text that do not fit this
pattern.
"""
data = {}
extralines = []
indict = False
fileobj.seek(0)
for line in fileobj.readlines():
if indic... | 41,564 |
def check_token(surface: str) -> Tuple[str, str]:
"""Adopted and modified from coltekin/childes-tr/misc/parse-chat.py
For a given surface form of the token, return (surface, clean), where
clean is the token form without CHAT codes.
"""
if surface is None:
return None, None
clean=''
if re.match(TO_OMIT, surfa... | 41,565 |
def _drawendinglines(lines, extra, edgemap, seen, state):
"""Draw ending lines for missing parent edges
None indicates an edge that ends at between this node and the next
Replace with a short line ending in ~ and add / lines to any edges to
the right.
"""
if None not in edgemap.values():
... | 41,566 |
def euler210_():
"""Solution for problem 210."""
pass | 41,567 |
def test_unigrams_without_feature_selection():
"""
Test without any feature selection and unigram features only, matrices and vocabulary are as in
test_main.test_baseline_use_all_features_signifier_only.
"""
# training corpus is "cats like dogs" (x2), "kids play games"
# eval corpus is "birds l... | 41,568 |
def merge_parallel_rank_vote(
combined_out: np.ndarray,
combined_n: np.ndarray,
output: np.ndarray,
n: np.ndarray,
start_y: int,
) -> None:
"""Merge the output from a worker into the total output for rank vote.
Args:
combined_out (np.ndarray): The total output array
combined... | 41,569 |
def remove_media_url(media_path):
"""
Strip leading MEDIA_URL from a media file url.
:param media_path:
:return:
"""
if media_path.startswith(MEDIA_URL):
return media_path[len(MEDIA_URL):]
else:
return media_path | 41,570 |
def _map_route_on_graph(ordered_cluster: sp.Cluster, graph: sp.Graph) -> list[sp.Segment]:
"""Построить маршрут в графе
Args:
ordered_cluster: Кластер с заданным порядком обхода точек
graph: Граф для прокладывания маршрута
Returns:
Построенный маршрут
"""
route = [] # Пут... | 41,571 |
def list_violation_data(client: Client, args) -> Tuple[str, Dict, Dict]:
"""List violation data.
Args:
client: Client object with request.
args: Usually demisto.args()
Returns:
Outputs.
"""
from_ = args.get('from')
to_ = args.get('to')
query = args.get('query')
... | 41,572 |
def train_add_test(func=lambda a, b: a+b, results_dir=None, reg_weight=5e-2, learning_rate=1e-2, n_epochs=10001):
"""Addition of two MNIST digits with a symbolic regression network.
Withold sums > 15 for test data"""
tf.reset_default_graph()
# Symbolic regression network to combine the conv net outputs... | 41,573 |
def update_scenario_multiple_columns(io, c, scenario_name, column_values_dict):
"""
:param io:
:param c:
:param scenario_name:
:param column_values_dict:
:return:
"""
for column_name in column_values_dict:
update_scenario_single_column(
io=io,
c=c,
... | 41,574 |
def walk_graph(csr_matrix, labels, walk_length=40, num_walks=1, n_jobs=1):
"""Perform random walks on adjacency matrix.
Args:
csr_matrix: adjacency matrix.
labels: list of node labels where index align with CSR matrix
walk_length: maximum length of random walk (default=40)
num_w... | 41,575 |
def mutate_split(population, config):
"""
Splitting a non-zero dose (> 0.25Gy) into 2 doses.
population - next population, array [population_size, element_size].
"""
interval_in_indices = int(2 * config['time_interval_hours'])
mutation_config = config['mutations']['mutate_split']
min_dose =... | 41,576 |
def _copy_df(df):
""" Copy a DataFrame """
return df.copy() if df is not None else None | 41,577 |
def test_rightvalue():
"""Ensures that the numerical differential equation solver approaches the analytic
value for the differential equation."""
apt = np.fabs(num_for_Eu(9, 1)[1][-1] - 1 - np.exp(-10)) < 1e-3 | 41,578 |
def test_get_gifs_non_admin(client: FlaskClient) -> None:
"""Assert when GET /gifs is requested, that non-admin users
are not allowed to make the request.
Args:
client (:obj:`~flask.testing.FlaskClient`): The Client fixture.
"""
username = create_random_username()
auth_token = create_au... | 41,579 |
def main(**kwargs):
""" A CLI that does nothing. """
print(kwargs) | 41,580 |
def copy_ownership_and_apply_mode(src, dst, mode, copy_user, copy_group):
# type: (str, str, int, bool, bool) -> None
"""
Copy ownership (user and optionally group on Linux) from the source to the
destination, then apply given mode in compatible way for Linux and Windows.
This replaces the os.chown ... | 41,581 |
def findPossi(bo):
""" Find all possibilities for all fields and add them to a list."""
possis = []
for row,rowVal in enumerate(bo):
for col,colVal in enumerate(rowVal):
localpossi=newPossiFinder(bo, col, row)
if bo[row][col]==0:
# Here ujson.loads(ujson.dump... | 41,582 |
def modernforms_exception_handler(func):
"""Decorate Modern Forms calls to handle Modern Forms exceptions.
A decorator that wraps the passed in function, catches Modern Forms errors,
and handles the availability of the device in the data coordinator.
"""
async def handler(self, *args, **kwargs):
... | 41,583 |
def reads_per_insertion(tnpergene_list,readpergene_list,lines):
"""It computes the reads per insertion following the formula:
reads/(insertions-1) if the number of insertions is higher than 5,
if not then the reads per insertion will be 0.
Parameters
----------
tnpergene_list : list
A... | 41,584 |
def test_add_exclude() -> None:
"""
Test argument for columns to exclude.
@return: None
"""
exclude = str(uuid.uuid4())
arguments = parse_harness([FLAG_EXCLUDE, exclude], add_exclude_value_flag)
assert arguments.exclude == exclude
assert parse_harness([], add_exclude_value_flag).exclude... | 41,585 |
def SizerItem_AssignWindow(item, window):
"""
Wrapper for wxSizerItem.SetWindow() resp. wxSizerItem.AssignWindow()
wxSizerItem.SetWindow() is deprecated since wxPython 2.9 use
wxSizerItem.AssignWindow() instead.
Depending on the wxPython version L{SizerItem_SetWindow28()} or
L{SizerItem_Assign... | 41,586 |
def getCurrDegreeSize(currDegree, spatialDim):
"""
Computes the number of polynomials of the current spatial dimension
"""
return np.math.factorial(currDegree + spatialDim - 1) / (
np.math.factorial(currDegree) * np.math.factorial(spatialDim - 1)) | 41,587 |
def loadConfig(): #remi--todo-----------------------------------------------
"""Load settings/config/materials from INI-file.
TODO: Read material-assignements from config-file.
"""
#20070724 buggy Window.FileSelector(loadConfigFile, 'Load config data from INI-file', inifilename)
global iniFileName, GUI_A, GUI_B
... | 41,588 |
def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n]
"""
x_shape = shape_list(x)
m = x_... | 41,589 |
def get_base_dir_for_individual_image(dataset,
show_both_knees_in_each_image,
downsample_factor_on_reload,
normalization_method,
seed_to_further_shuffle_train_test_val_sets,
crop_to_just_the_knee):
"""
Get the path for an image.
"""
assert seed_to_further_shuffle_train_test_val... | 41,590 |
def get_column_dtype(column, pd_or_sqla, index=False):
"""
Take a column (sqlalchemy table.Column or df.Series), return its dtype in Pandas or SQLA
If it doesn't match anything else, return String
Args:
column: pd.Series or SQLA.table.column
pd_or_sqla: either 'pd' or 'sqla': which kin... | 41,591 |
def _stdlibs(tut):
"""Given a target, return the list of its standard rust libraries."""
libs = [
lib.static_library
for li in tut[CcInfo].linking_context.linker_inputs.to_list()
for lib in li.libraries
]
stdlibs = [lib for lib in libs if (tut.label.name not in lib.basename)]
... | 41,592 |
def _chebyshev(wcs_dict):
"""Returns a chebyshev model of the wavelength solution.
Constructs a Chebyshev1D mathematical model
Parameters
----------
wcs_dict : dict
Dictionary containing all the wcs information decoded from the header and
necessary for constructing the Chebyshev1D... | 41,593 |
def printListOfMods(tree):
"""Print a list of modules (tree), mostly useful for debugging.
INPUT: list of modules
"""
for mod in tree:
print(mod.symbol, mod.param) | 41,594 |
def autosolve(equation):
"""
Automatically solve an easy maths problem.
:type equation: string
:param equation: The equation to calculate.
>>> autosolve("300 + 600")
900
"""
try:
# Try to set a variable to an integer
num1 = int(equation.split(" ")[0])
except Value... | 41,595 |
def request_champion(champion_name: str) -> BeautifulSoup:
"""
Get http request to website with all statistics about a
champion with html format.
"""
request = http.request(
'GET',
f'https://www.leaguespy.gg/league-of-legends/champion/{champion_name}/stats',
None,
H... | 41,596 |
def calculate_coarse_change_maps(p):
"""1) in net, the remaining 0.4 mha /yr should go to pasture. 2) as we discussed, there should also be a far amount of crop expansion into pasture and a fair amount of pasture expansion into savannah and forest. typically something like 65% of all deforestation goes to pasture."... | 41,597 |
def _act_drop(grid_world, agent, env_obj, drop_loc):
""" Private MATRX method.
Drops the carried object.
Parameters
----------
grid_world : GridWorld
The :class:`matrx.grid_world.GridWorld` instance in which the
object is dropped.
agent : AgentBody
... | 41,598 |
def get_emoticon_radar_chart(scores_list, colors, names):
""" AAA
"""
data_radars = []
emotions = ['anger', 'anticipation', 'disgust', 'fear', 'joy', 'sadness', 'surprise', 'trust']
for score, color, name in zip(scores_list, colors, names):
data = go.Scatterpolar(r=score, theta=emotions, fil... | 41,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.