content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_model(args, vocab_size, num_labels, mode='train'):
"""create lac model"""
# model's input data
words = fluid.data(name='words', shape=[-1, 1], dtype='int64', lod_level=1)
targets = fluid.data(
name='targets', shape=[-1, 1], dtype='int64', lod_level=1)
if mode == "train":
... | 23,100 |
def time_nifti_to_numpy(N_TRIALS):
"""
Times how fast a framework can read a nifti file and convert it to numpy
"""
img_paths = [ants.get_ants_data('mni')]*10
def test_nibabel():
for img_path in img_paths:
array = nib.load(img_path).get_data()
def test_itk():
fo... | 23,101 |
def escape_string(value):
"""escape_string escapes *value* but not surround it with quotes.
"""
value = value.replace('\\', '\\\\')
value = value.replace('\0', '\\0')
value = value.replace('\n', '\\n')
value = value.replace('\r', '\\r')
value = value.replace('\032... | 23,102 |
def current_script_path() -> str:
"""
Return path to where the currently executing script is located
"""
return os.path.abspath(os.path.dirname(sys.argv[0])) | 23,103 |
def _supports_masking(remask_kernel: bool):
"""Returns a decorator that turns layers into layers supporting masking.
Specifically:
1) `init_fn` is left unchanged.
2) `apply_fn` is turned from
a function that accepts a `mask=None` keyword argument (which indicates
`inputs[mask]` must be masked), into
... | 23,104 |
def warnings(request: HttpRequest):
"""Adiciona alguns avisos no content"""
warning = list()
if hasattr(request, 'user'):
user: User = request.user
if not user.is_anonymous:
# Testa email
if user.email is None or user.email == "":
warning.append({
... | 23,105 |
def _get_raw_key(args, key_field_name):
"""Searches for key values in flags, falling back to a file if necessary.
Args:
args: An object containing flag values from the command surface.
key_field_name (str): Corresponds to a flag name or field name in the key
file.
Returns:
The flag value ass... | 23,106 |
def get_images(headers, name, handler_registry=None,
handler_override=None):
"""
This function is deprecated. Use Header.data instead.
Load images from a detector for given Header(s).
Parameters
----------
fs: RegistryRO
headers : Header or list of Headers
name : string
... | 23,107 |
def compare_outputs(images, questions, vqg, vocab, logging,
args, num_show=1):
"""Sanity check generated output as we train.
Args:
images: Tensor containing images.
questions: Tensor containing questions as indices.
vqg: A question generation instance.
vocab:... | 23,108 |
def shape_is_ok(sequence: Union[Sequence[Any], Any], expected_shape: Tuple[int, ...]) -> bool:
"""
Check the number of items the array has and compare it with the shape product
"""
try:
sequence_len = len(flatten(sequence))
except Exception as err:
logger.info(f"Error when trying to ... | 23,109 |
def ChannelSE(reduction=16, **kwargs):
"""
Squeeze and Excitation block, reimplementation inspired by
https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py
Args:
reduction: channels squeeze factor
"""
channels_axis = 3 if backend.image_dat... | 23,110 |
def add_trainingset_flag(cam_parquet,
trainingset_pkl_path,
cam=None):
"""
Add to a single-cam parquet the information flags (adding columns)
indicating if a given cam view was used in a training set for
melting, hydro classif or riming degree
Input... | 23,111 |
def pw_wavy(n_samples=200, n_bkps=3, noise_std=None, seed=None):
"""Return a 1D piecewise wavy signal and the associated changepoints.
Args:
n_samples (int, optional): signal length
n_bkps (int, optional): number of changepoints
noise_std (float, optional): noise std. If None, no noise ... | 23,112 |
def date():
"""
____this is data type for date column____
"""
return Column(Date) | 23,113 |
def sell_holdings(symbol, holdings_data):
""" Place an order to sell all holdings of a stock.
Args:
symbol(str): Symbol of the stock we want to sell
holdings_data(dict): dict obtained from get_modified_holdings() method
"""
shares_owned = 0
result = {}
for item in holdings_data:... | 23,114 |
def get_active_project_path():
"""
Arguments:
None
Return:
str: current project folder path
"""
window = sublime.active_window()
folders = window.folders()
if len(folders) == 1:
return folders[0]
else:
active_view = window.active_view()
active_file_name = active_view.file_name() if active_view else N... | 23,115 |
def get_people_urls(gedcom_data, apid_full_map):
"""
Read in all the person URLs for later reference
"""
people = {}
found = False
logging.info("Extracting person specific URL information")
for line in gedcom_data.split("\n"):
if len(line) > 5:
tag = line.split(" ")[1]
... | 23,116 |
def permute_masks(old_masks):
"""
Function to randomly permute the mask in a global manner.
Arguments
---------
old_masks: List containing all the layer wise mask of the neural network, mandatory. No default.
seed: Integer containing the random seed to use for reproducibility. Default is 0
Returns
-------
new... | 23,117 |
async def file_clang_formatted_correctly(filename, semaphore, verbose=False):
"""
Checks if a file is formatted correctly and returns True if so.
"""
ok = True
# -style=file picks up the closest .clang-format
cmd = "{} -style=file {}".format(CLANG_FORMAT_PATH, filename)
async with semaphore... | 23,118 |
def service_builder(client: Client, is_for_update: bool, endpoint_tag: str,
name: str, service_type: str, protocol: str = None, source_port: int = None,
destination_port: int = None, protocol_name: str = None,
icmp_type: str = None, icmp_code: str = None,
... | 23,119 |
def fkl( angles ):
"""
Convert joint angles and bone lenghts into the 3d points of a person.
Based on expmap2xyz.m, available at
https://github.com/asheshjain399/RNNexp/blob/7fc5a53292dc0f232867beb66c3a9ef845d705cb/structural_rnn/CRFProblems/H3.6m/mhmublv/Motion/exp2xyz.m
Args
angles: 99-long ve... | 23,120 |
def no_matplotlib(monkeypatch):
""" Mock an import error for matplotlib"""
import_orig = builtins.__import__
def mocked_import(name, globals, locals, fromlist, level):
""" """
if name == 'matplotlib.pyplot':
raise ImportError("This is a mocked import error")
return impor... | 23,121 |
def profile(func: Callable[..., Any]) -> Callable[..., Any]:
"""
Create a decorator for wrapping a provided function in a LineProfiler context.
Parameters
----------
func : callable
The function that is to be wrapped inside the LineProfiler context.
Returns
-------
wrapper : ca... | 23,122 |
def phase_comp(psi_comp, uwrap=False, dens=None):
"""Compute the phase (angle) of a single complex wavefunction component.
Parameters
----------
psi_comp : NumPy :obj:`array` or PyTorch :obj:`Tensor`
A single wavefunction component.
Returns
-------
angle : NumPy :obj:`array` or PyT... | 23,123 |
def test_config_changed_different_state_absent(mock_module,
mock_exec):
"""
cl-interface - test config_changed with state == noconfig
"""
instance = mock_module.return_value
instance.params.get_return_value = 'lo'
iface = {'name': 'lo', 'ifacetype':... | 23,124 |
def packets(args):
"""Show packet info."""
with open(args.infile, 'rb') as tsi:
offset = 0
packet_idx = 0
for packet in iter(lambda: tsi.read(args.packet_size), b''):
ts_packet = get_ts_packet(packet, args.packet_size)
offset += args.packet_size - TS_PACKET_SIZE
... | 23,125 |
def EG(d1,d2,P):
"""
Méthode permettant de calculer l'esperance de gain du joueur 1 s'il lance d1 dés et
que le joueur 2 lance d2 dés
----------------------------------------------------
Args:
- d1 : nombre de dés lancés par le joueur 1
- d2 : nombre de dés lancés par le joueur 2
... | 23,126 |
def save_current_editor_as():
"""
Saves the current editor as (the save as dialog will be shown
automatically).
"""
_window().save_current_as() | 23,127 |
def get_tx_data(request):
"""
JSON Needed:
1. txid
E.g.:
{"txid": "hgjsyher6ygfdg"}
"""
txid = request.data['txid']
try:
# req_hex_data = get_tx_data(txid)
req_hex_data = api.gettxoutdata(txid,0) # TODO
except:
return Response(status=status.HTTP_403_... | 23,128 |
def roi_max_counts(images_sets, label_array):
"""
Return the brightest pixel in any ROI in any image in the image set.
Parameters
----------
images_sets : array
iterable of 4D arrays
shapes is: (len(images_sets), )
label_array : array
labeled array; 0 is background.
... | 23,129 |
def normalize_full_width(text):
"""
a function to normalize full width characters
"""
return unicodedata.normalize('NFKC', text) | 23,130 |
def make_definitions(acronym, words_by_letter, limit=1):
"""Find definitions an acronym given groupings of words by letters"""
definitions = []
for _ in range(limit):
definition = []
for letter in acronym.lower():
opts = words_by_letter.get(letter.lower(), [])
defini... | 23,131 |
def plot_effective_area_from_file(file, all_cuts=False, ax=None, **kwargs):
""" """
ax = plt.gca() if ax is None else ax
if all_cuts:
names = ["", "_NO_CUTS", "_ONLY_GH", "_ONLY_THETA"]
else:
names = tuple([""])
label_basename = kwargs["label"] if "label" in kwargs else ""
kw... | 23,132 |
def get_spreading_coefficient(dist):
"""Calculate the spreading coefficient.
Args:
dist: A Distribution from a direct (GC) spreading simulation.
Returns:
The dimensionless spreading coefficient (beta*s*A).
"""
potential = -dist.log_probs
valley = np.amin(potential)
split = ... | 23,133 |
def get_config_path() -> Path:
"""Returns path to the root of the project"""
return Path(__file__).parent / "config" | 23,134 |
def round(x):
"""
Return ``x`` rounded to an ``Integer``.
"""
return create_RealNumber(x).round() | 23,135 |
def test_delete_record_get_request(client, set_up, login):
"""test if record confirm delete template is displayed"""
record_to_delete = CoupeDay.objects.first()
response = client.get(reverse('home:record-delete', kwargs={'pk': record_to_delete.id}), follow=True)
delete_txt = f"Confirm delete"
assert... | 23,136 |
def test_testclass(ctestdir):
"""Using test classes
"""
with get_example("testclass.py").open("rt") as f:
ctestdir.makepyfile(f.read())
result = ctestdir.runpytest("--verbose")
try:
result.assert_outcomes(passed=4, skipped=4, failed=0, xfailed=2)
except TypeError:
result.... | 23,137 |
def author(repo, subset, x):
"""``author(string)``
Alias for ``user(string)``.
"""
# i18n: "author" is a keyword
n = encoding.lower(getstring(x, _("author requires a string")))
return [r for r in subset if n in encoding.lower(repo[r].user())] | 23,138 |
def p_definition (t):
"""definition : type_def
| constant_def"""
t[0] = t[1] | 23,139 |
def create_test_example_solution_files(exercise_name, prob_spec_exercise):
"""
Auto-generates the test file.
Function creates the test file in its own right, but also calls the
create_example_and_solution_files function. This function also creates
the parameters to feed into the create_example_and... | 23,140 |
def pianoroll_plot_setup(figsize=None, side_piano_ratio=0.025,
faint_pr=True, xlim=None):
"""Makes a tiny piano left of the y-axis and a faint piano on the main figure.
This function sets up the figure for pretty plotting a piano roll. It makes a
small imshow plot to the left of the main... | 23,141 |
def exercise(request, exercisename):
"""Show single sport and its totals."""
e = exercisename
cur_user = request.user
exercises = Exercise.objects.filter(owner=cur_user, sport=e).order_by('-date')
context = {'exercises': exercises, 'total': Stats.total(cur_user, sport=e),
'totaltime'... | 23,142 |
def rng() -> int:
"""Return a 30-bit hardware generated random number."""
pass | 23,143 |
def randomBinaryMatrix(scale, type):
"""
Generates a pseudo random BinaryMatrix of a given scale(small,large) and
datatype(int).
"""
if(scale == "small" and type == "int"):
nrow = random.randint(1, 10)
ncol = random.randint(1, 10)
data = []
for i in range(nrow):
... | 23,144 |
def draw_contours(mat, contours, color=(0, 0, 255), thickness=1):
"""
Draws contours on the input image. The input image is modified.
:param mat: input image
:param contours: contours to draw
:param color: color of contours
:param thickness: thickness of contours, filled if -1
:return: None
... | 23,145 |
def load_batch(server_context: ServerContext, assay_id: int, batch_id: int) -> Optional[Batch]:
"""
Loads a batch from the server.
:param server_context: A LabKey server context. See utils.create_server_context.
:param assay_id: The protocol id of the assay from which to load a batch.
:param batch_i... | 23,146 |
def canvas_compose(mode, dst, src):
"""Compose two alpha premultiplied images
https://ciechanow.ski/alpha-compositing/
http://ssp.impulsetrain.com/porterduff.html
"""
src_a = src[..., -1:] if len(src.shape) == 3 else src
dst_a = dst[..., -1:] if len(dst.shape) == 3 else dst
if mode == COMPO... | 23,147 |
async def get_timelog_user_id(
*,
user_id: int,
epic_id: int,
month: int,
year: int,
session: Session = Depends(get_session),
):
"""
Get list of timelogs by user_id, month.
Parameters
----------
user_id : str
ID of user from which to pull timelogs.
year_month : i... | 23,148 |
def _cross(
vec1,
vec2,
):
"""Cross product between vec1 and vec2 in R^3"""
vec3 = np.zeros((3,))
vec3[0] = +(vec1[1] * vec2[2] - vec1[2] * vec2[1])
vec3[1] = -(vec1[0] * vec2[2] - vec1[2] * vec2[0])
vec3[2] = +(vec1[0] * vec2[1] - vec1[1] * vec2[0])
return vec3 | 23,149 |
def _simplex_dot3D(g, x, y, z):
""" 3D dot product """
return g[0] * x + g[1] * y + g[2] * z | 23,150 |
def __get_report_failures(test_data: TestData) -> str:
"""
Gets test report with all failed test soft asserts
:param test_data: test data from yaml file
:return: str test report with all soft asserts
"""
test_id = __get_test_id()
failed_assert_reports = __FAILED_EXPECTATIONS.get(test_id)
... | 23,151 |
def make_complex_heatmap(df_data, heatmap_cmap='coolwarm',
vmax=4,
vmin=-4,
figsize=(16, 9),
row_metadata=None,
col_metadata=None,
col_colorbar_anchor=[0.12, 0.1, 0.7, 0.... | 23,152 |
def initialized_sm(registrations, uninitialized_sm):
""" The equivalent of an app with commit """
uninitialized_sm.initialize()
return uninitialized_sm | 23,153 |
def compute_options(
platform: PlatformName,
package_dir: Path,
output_dir: Path,
config_file: Optional[str],
args_archs: Optional[str],
prerelease_pythons: bool,
) -> BuildOptions:
"""
Compute the options from the environment and configuration file.
"""
manylinux_identifiers = ... | 23,154 |
def coordinateToIndex(coordinate):
"""Return a raw index (e.g [4, 4]) from board coordinate (e.g. e4)"""
return [abs(int(coordinate[1]) - 8), ("a", "b", "c", "d", "e", "f", "g", "h").index(coordinate[0])] | 23,155 |
def parse_page(url):
"""parge the page and get all the links of images, max number is 100 due to limit by google
Args:
url (str): url of the page
Returns:
A set containing the urls of images
"""
page_content = download_page(url)
if page_content:
link_list = re.f... | 23,156 |
def assert_ndim(arg, ndims):
"""Raise exception if `arg` has a different number of dimensions than `ndims`."""
if not is_array(arg):
arg = np.asarray(arg)
if isinstance(ndims, Iterable):
if arg.ndim not in ndims:
raise AssertionError(f"Number of dimensions must be one of {ndims},... | 23,157 |
def full_file_names(file_dir):
"""
List all full file names(with extension) in target directory.
:param file_dir:
target directory.
:return:
a list containing full file names.
"""
for _, _, files in os.walk(file_dir):
return files | 23,158 |
def json_page_resp(name, page, paginator):
"""
Returns a standardized page response
"""
page_rows = paginator.get_page(page)
return JsonResponse({'page':page, 'pages':paginator.num_pages, name:[x['json'] for x in page_rows], 'size':len(page_rows)}, safe=False) | 23,159 |
def input_house_detail(driver):
"""进入房源预订页面"""
pass | 23,160 |
def get_script_runner():
"""
Gets the script runner plugin instance if any otherwise returns None.
:rtype: hackedit.api.interpreters.ScriptRunnerPlugin
"""
from .interpreters import ScriptRunnerPlugin
return _window().get_plugin_instance(ScriptRunnerPlugin) | 23,161 |
def detect_peak(a, thresh=0.3):
"""
Detect the extent of the peak in the array by looking for where the slope
changes to flat. The highest peak is detected and data and followed until
the slope flattens to a threshold.
"""
iPk = np.argmax(a)
d = np.diff(a)
g1 = np.gradient(a)
g2... | 23,162 |
def latest_version():
"""
Returns the latest version, as specified by the Git tags.
"""
versions = []
for t in tags():
assert t == t.strip()
parts = t.split(".")
assert len(parts) == 3, t
parts[0] = parts[0].lstrip("v")
v = tuple(map(int, parts))
ver... | 23,163 |
def get_age_group(df,n: int=10):
"""Assigns a category to the age DR
Parameters
----------
df : Dataframe
n : number of categories
Returns
-------
Dataset with Age_group column
"""
df["Age_group"] = pd.cut(df["Age"], n, labels = list(string.ascii_uppercase)[:n])
re... | 23,164 |
def test_thermal_info(duthosts, enum_rand_one_per_hwsku_hostname, snmp_physical_entity_and_sensor_info):
"""
Verify thermal information in physical entity mib with redis database
:param duthost: DUT host object
:param snmp_physical_entity_info: Physical entity information from snmp fact
:return:
... | 23,165 |
def transformer_encoder_layer(query_input,
key_input,
attn_bias,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,... | 23,166 |
def generate(ode, lenght=int(2e4)):
"""
Time series generation from a ODE
:param ode: ODE object;
:param lenght: serie lenght;
:return: time serie.
"""
state = ode.initial_state
data = np.zeros([int(state.shape[0]), lenght])
for i in range(5000):
state = runge_kutta(ode... | 23,167 |
def complexFormatToRealImag(complexVec):
"""
A reformatting function which converts a complex vector into real valued array.
Let the values in the input array be [r1+j*i1,r 2+j*i2,..., rN+j*iN]
then the output array will be [r1, i1, r2, i2,..., rN, iN]
:param complexVec: complex numpy ndarray
:r... | 23,168 |
def send_invoice(order_id):
"""
當交易成功時,發送 email 的任務
P.S. 為「PDF 收據」,非 通知訂單成立的文字 email 訊息
"""
order = Order.objects.get(id=order_id)
subject = "【Cloth2U】 Your invoice"
message = "Please kindly find the attached file," +\
" the invoice for your recent purchase."
email_message ... | 23,169 |
def displayaction(uid):
""" Display the command from the xml file
"""
tree = ET.parse(OPENSTRIATOFILE)
root = tree.getroot()
textaction = root.findall("./action[@uid='"+uid+"']")
if len(textaction) == 0:
return "This UID does not exist!"
else:
return "UID %s action: %s" % (ui... | 23,170 |
def get_parent(inst, rel_type='cloudify.relationships.contained_in'):
"""
Gets the parent of an instance
:param `cloudify.context.NodeInstanceContext` inst: Cloudify instance
:param string rel_type: Relationship type
:returns: Parent context
:rtype: :class:`cloudify.context.RelationshipSubj... | 23,171 |
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf... | 23,172 |
def _create_or_get_dragonnet(embedding, is_training, treatment, outcome, split, getter=None):
"""
Make predictions for the outcome, using the treatment and embedding,
and predictions for the treatment, using the embedding
Both outcome and treatment are assumed to be binary
Note that we return the l... | 23,173 |
def fit_ols(Y, X):
"""Fit OLS model to both Y and X"""
model = sm.OLS(Y, X)
model = model.fit()
return model | 23,174 |
def compute_modularity_per_code(mutual_information):
"""Computes the modularity from mutual information."""
# Mutual information has shape [num_codes, num_factors].
squared_mi = np.square(mutual_information)
max_squared_mi = np.max(squared_mi, axis=1)
numerator = np.sum(squared_mi, axis=1) - max_squ... | 23,175 |
def _CheckSemanticColorsReferences(input_api, output_api):
"""
Checks colors defined in semantic_colors_non_adaptive.xml only referencing
resources in color_palette.xml.
"""
errors = []
color_palette = None
for f in IncludedFiles(input_api):
if not f.LocalPath().endswith('/semantic_colors_non_adaptiv... | 23,176 |
def post_new_attending():
"""Posts attending physician information to the server
This method generates the new attending physician’s
dictionary with all of his/her information, then validates
that all of the information is the correct type. If the
validation stage is satisfied, then the attending’s... | 23,177 |
def submitFeatureWeightedGridStatistics(geoType, dataSetURI, varID, startTime, endTime, attribute, value,
gmlIDs, verbose, coverage, delim, stat, grpby, timeStep, summAttr,
weighted, wfs_url, outputfname, sleepSecs, async=False):
"""
... | 23,178 |
def fetch_words(url):
"""
Fetch a list of words from a URL
Args:
url: the url of any text document (no decoding to utf-8 added)
Returns:
A list of strings containing the words in the document
"""
with urlopen(url) as story:
story_words = []
for line in s... | 23,179 |
def generate_fgsm_examples(sess, model, x, y, X, Y, attack_params, verbose, attack_log_fpath):
"""
Untargeted attack. Y is not needed.
"""
fgsm = FastGradientMethod(model, back='tf', sess=sess)
fgsm_params = {'eps': 0.1, 'ord': np.inf, 'y': None, 'clip_min': 0, 'clip_max': 1}
fgsm_params = overr... | 23,180 |
def add_class(attrs_dict, classes_str):
"""Adds the classes_str to the 'class' key in attrs_dict, or creates it"""
try:
attrs_dict["class"] += " " + classes_str
except KeyError:
attrs_dict["class"] = classes_str | 23,181 |
def s3_bucket_for(bucket_prefix, path):
"""returns s3 bucket for path"""
suffix = s3_bucket_suffix_for(path)
return "{}-{}".format(bucket_prefix, suffix) | 23,182 |
def regrid_create_operator(regrid, name, parameters):
"""Create a new `RegridOperator` instance.
:Parameters:
regrid: `ESMF.Regrid`
The `ESMF` regridding operator between two fields.
name: `str`
A descriptive name for the operator.
parameters: `dict`
... | 23,183 |
def _decode_hmc_values(hmc_ref):
"""Decrypts any sensitive HMC values that were encrypted in the DB"""
if hmc_ref is not None:
hmc_ref = jsonutils.to_primitive(hmc_ref)
#Make sure to DeCrypt the Password after retrieving from the database
## del two lines by lixx
#if hmc_ref.get(... | 23,184 |
def config_source_local(src_folder, conanfile, output, conanfile_path, hook_manager):
""" Entry point for the "conan source" command.
"""
conanfile_folder = os.path.dirname(conanfile_path)
_run_source(conanfile, conanfile_path, src_folder, hook_manager, output, reference=None,
client_cac... | 23,185 |
def init_data(my_data, rp):
""" initialize the quadrant problem """
msg.bold("initializing the quadrant problem...")
# make sure that we are passed a valid patch object
if not isinstance(my_data, patch.CellCenterData2d):
print("ERROR: patch invalid in quad.py")
print(my_data.__class__)... | 23,186 |
def dtensor_shutdown_tpu_system():
"""Shutdown TPU system."""
@def_function.function
def _shutdown_tpu_system():
return gen_dtensor_ops.shutdown_tpu_system()
success = _shutdown_tpu_system() if context.is_tfrt_enabled() else True
if success:
logging.info("TPU system shut down.")
else:
logging.... | 23,187 |
def edit_comment(request):
"""
Edit an existing comment
"""
response = {"status": "success",
"data": {}}
if "char_id" in request.POST:
char_id = request.POST["char_id"]
else:
response["status"] = "fail"
response["data"]["message"] = "Paste ID was not ... | 23,188 |
def aws_get_size(size):
""" Get Node Size - Ex: (cmd:<size>)"""
conn = util_get_connection()
sizes = [i for i in conn.list_sizes()]
if size:
for i in sizes:
if str(i.ram) == size or i.id == size:
print >> sys.stderr, ' - '.join([i.id, str(i.ram), str(i.price)])
... | 23,189 |
def make_positions(tensor, padding_idx, onnx_trace=False):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
"""
# The series of casts and type-conversions here are carefully
# balanced to both work with ONNX export and... | 23,190 |
def taubin_curv(coords, resolution):
"""Curvature calculation based on algebraic circle fit by Taubin.
Adapted from: "https://github.com/PmagPy/PmagPy/blob/2efd4a92ddc19c26b953faaa5c08e3d8ebd305c9/SPD/lib
/lib_curvature.py"
G. Taubin, "Estimation Of Planar Curves, Surfaces And Nonplanar
... | 23,191 |
def periodic_general(box: Box,
fractional_coordinates: bool=True,
wrapped: bool=True) -> Space:
"""Periodic boundary conditions on a parallelepiped.
This function defines a simulation on a parallelepiped, $X$, formed by
applying an affine transformation, $T$, to the unit... | 23,192 |
def filter(
needle: Callable[[T], object],
haystack: Iterable[T],
parse: None = None,
*,
allow_mismatch: Literal[False] = False,
allow_many: bool = False,
allow_duplicates: bool = False,
) -> T:
"""
`haystack` is a sequence of T elements, and `needle` must accept `T` values. If `pars... | 23,193 |
def test_additive_hash_returns_correct_values(key, value):
"""Test that additive hash returns the correct values."""
from hash import additive_hash
assert additive_hash(key) == value | 23,194 |
def calculate_mac(mac_type, credentials, options, url_encode=False):
"""Calculates a message authentication code (MAC)."""
normalized = normalize_string(mac_type, options)
digestmod = module_for_algorithm(credentials['algorithm'])
result = hmac.new(credentials['key'], normalized, digestmod)
if url_e... | 23,195 |
def run():
"""
Test Case - Fbx mesh group Import scaling in Atom:
1. Creates a new level called MeshScalingTemporaryLevel
2. Has a list of 12 meshes, which it will do the following for each one:
- Create an entity and attach the mesh to it.
- Sets it with an initial offset of x:-15, y:0,... | 23,196 |
def get_prime(num_dict):
"""获取字典里所有的素数"""
prime_dict = {}
for key, value in num_dict.items():
if value:
prime_dict.update({key: key})
return prime_dict | 23,197 |
def get_shared_keys(param_list):
"""
For the given list of parameter dictionaries, return a list of the dictionary
keys that appear in every parameter dictionary
>>> get_shared_keys([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}])
['a', 'b']
>>> get_shared_keys([{'a':0, 'd':3}, {'a':0... | 23,198 |
def labeledTest(*labels):
"""This decorator mark a class as an integrationTest
this is used in the test call for filtering integrationTest
and unittest.
We mark the difference by the usage of service dependency:
* An unittest can run without additional services.
* An integration test need additi... | 23,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.