content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_torch():
"""Make sure we know how to cast dypes and devices of models"""
model = SimpleNN()
device = "cuda"
model = model.to(device)
x = torch.arange(10.0).to(device)
output = model.forward(x)
assert x.device.type == device
assert model.mm.device.type == device
assert out... | 5,344,300 |
def sRGB_to_sd_Mallett2019(RGB):
"""
Recovers the spectral distribution of given *sRGB* colourspace array using
*Mallett and Yuksel (2019)* method.
Parameters:
-----------
RGB : array_like, (3,)
*sRGB* colourspace array. Do not apply a transfer function to the
*RGB* values.
... | 5,344,301 |
def test_model_with_circular_imports():
"""
Basic test for FQNImportURI + circular imports
"""
#################################
# META MODEL DEF
#################################
my_meta_model = metamodel_from_file(
join(abspath(dirname(__file__)),
'interface_model1', ... | 5,344,302 |
def stationary_traffic_matrix(topology, mean, stddev, gamma, log_psi, n,
max_u=0.9,
origin_nodes=None, destination_nodes=None):
"""
Return a stationary sequence of traffic matrices.
The sequence is generated by first generating a single matrix ass... | 5,344,303 |
def gen_coverage_badge(
input_file=None,
output_file=None,
webshields=None,
verbose=None,
silent=None
):
"""
This command generates a badge for the coverage results, from an XML file in
the 'coverage' format. Such a file can be for example generated using the
pyth... | 5,344,304 |
def test_MuonRingFitter(method):
"""test MuonRingFitter"""
# flashCam example
center_xs = 0.3 * u.m
center_ys = 0.6 * u.m
radius = 0.3 * u.m
width = 0.05 * u.m
muon_model = toymodel.RingGaussian(
x=center_xs, y=center_ys, radius=radius, sigma=width,
)
# testing with flashca... | 5,344,305 |
def _extract_dims(
m: ArrayLike,
target: int,
depth: int = 0
) -> Iterator[ArrayLike]:
"""
Extract the requested dimension.
Mainly used only to extract the last two dimensions of a matrix.
As not really generalized for "any" dimension, not really good to expose publicly.
"""
if dep... | 5,344,306 |
def lsst_exposure_time(bands=''):
"""
Sample from the LSST exposure time distribution
"""
dist = {'u': 15.0, 'g': 15.0, 'r': 15.0, 'i': 15.0, 'z': 15.0, 'Y': 15.0}
return [dist[b] for b in bands.split(',')] | 5,344,307 |
def bin2hexstring(bin_str):
"""
二进制串转十六进制串,按照 4:1 比例转换
:param bin_str: 二进制串
:return: 十六进制串
"""
bin_len = len(bin_str)
left = 0
right = 4
re_str = hex(int(bin_str[left:right], 2))[2:]
for i in range(right, bin_len, 4):
left = right
right += 4
re_str += hex(... | 5,344,308 |
def check_dict_word(word, target):
"""
Check dict word. If one character not in searching word, then not add the word to python_dict.
:param word: str, word in dictionary.txt.
:param target: str, the searching word
:return: True, all character within are in searching word.
"""
# Level one: c... | 5,344,309 |
def print_content():
"""
Print all content.
"""
content = TARIELI.get_full_content()
print(content)
app_continue() | 5,344,310 |
def get_memory_in_GB(memory_str):
"""Returns the memory value in GB from a given string in kB"""
try:
return '{0} GB'.format(int(memory_str[:-2]) / 1000000)
except (ValueError, TypeError):
return '' | 5,344,311 |
def test_explain_instance_classification(caplog):
"""
Tests :mod:`fatf.transparency.lime.Lime.explain_instance` method.
These tests are for a classification task.
"""
runtime_error_no_predictor = 'A predictive function is not available.'
runtime_error_non_prob = ('The predictive model is not pr... | 5,344,312 |
def get_slot_dict(token_present=False):
"""Compiles a dictionary of the available slots
:returns: A python dictionary of the available slots
"""
ret, slot_list = c_get_slot_list(token_present)
if (ret != 0):
return ret
slot_dict = {}
ret = CKR_OK
for slot in slot_list:
... | 5,344,313 |
def submit_bwa_map(insert_size, ref_genome, read_1, read_2, output):
"""The `bwa mem` function."""
map_cmd = "bwa mem -t 24 -I {} {} {} {}".format(insert_size, ref_genome, read_1, read_2)
map_cmd += " | samtools sort -m 5G -@24 -O bam -T {} -o {}.bam".format(output, output)
"""Create a .sh files with th... | 5,344,314 |
def main():
"""Command line conversion of a PPK file to an OpenSSH file
python -m puttykeys myprivatekey.ppk [password] > id_rsa"""
if len(sys.argv) > 1:
f=open(sys.argv[1],'r')
ppkraw = f.read()
f.close()
if len(sys.argv) > 2:
sys.stdout.write(ppkraw_to_openssh(ppkraw, sys.argv[2]))
els... | 5,344,315 |
def load_segment_by_patient(patient):
"""
Load the pixels for a patient and segment all of them
"""
pixels = load_pixels_by_patient(patient)
segments = []
for pixel in pixels:
segments.append(segment(pixel))
return np.array(segments) | 5,344,316 |
def filehash(thisfile, filesha):
"""
First parameter, filename
Returns SHA1 sum as a string of hex digits
"""
try:
filehandle = open(thisfile, "rb")
except:
return ""
data = filehandle.read()
while data != b"":
filesha.update(data)
data = filehandle.read(... | 5,344,317 |
def object_size(o):
"""
Calls `getsizeof <https://docs.python.org/3/library/sys.html#sys.getsizeof>`_.
@param o object
@return size of the object, that excludes references objects.
"""
return getsizeof(o) | 5,344,318 |
def show_date(
enode,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Display system date information
This function runs the following vtysh command:
::
# show date
:param dict kw... | 5,344,319 |
def show_score(connection, amt):
"""
show_score
:param connection: :class:`sqlite3`
:param amt: int
:return: int
"""
sand = read_sum(connection, "sand", amt)
putt = read_sum(connection, "putt", amt)
return sand + putt | 5,344,320 |
def current_time():
""" current_time() -> str
>>> current_time()
14:28:04
Returns the current local time in 24 clock system.
"""
return time.strftime('%X', (time.localtime())) | 5,344,321 |
def kernel_s_xz2(y, x, z, zc, yp, xp, zp):
"""
Kernel for xz-component of stress in the semi-infinite space domain
(2nd system)
"""
# Y = y - yp
# X = x - xp
# Z = z - zp - 2 * zc
Y = yp - y
X = xp - x
Z = zp - z + 2 * zc
rho = np.sqrt(Y ** 2 + X ** 2 + Z ** 2)
kernel = (... | 5,344,322 |
def prepare_hex_string(number, base=10):
"""
Gets an int number, and returns the hex representation with even length padded to the left with zeroes
"""
int_number = int(number, base)
hex_number = format(int_number, 'X')
# Takes the string and pads to the left to make sure the number of characte... | 5,344,323 |
def parse_function(image_size, raw_image_key_name):
"""Generate parse function for parsing the TFRecord training dataset.
Read the image example and resize it to desired size.
Args:
image_size: int, target size to resize the image to
raw_image_key_name: str, name of the JPEG image in each TFRecord entry... | 5,344,324 |
def clean_coverage(x):
"""
Cleans the coverage polygons by remove small multipolygon shapes.
Parameters
---------
x : polygon
Feature to simplify.
Returns
-------
MultiPolygon : MultiPolygon
Shapely MultiPolygon geometry without tiny shapes.
"""
# if its a sing... | 5,344,325 |
def send():
"""For testing: Example of activating a background task."""
log.info("executing a background task")
bgtasks.send_email.spool(email="tomi@tomicloud.com",
subject="Hello world!", template="welcome.html")
return jsonify({"reply":"background task will start"}), 200 | 5,344,326 |
def get_today_month_and_day() -> str:
"""Returns today's month and day in the format: %m-%d"""
return datetime.date.today().strftime("%m-%d") | 5,344,327 |
def climate_zone_to_tmy3_stations(climate_zone):
"""Return TMY3 weather stations falling within in the given climate zone.
Parameters
----------
climate_zone : str
String representing a climate zone.
Returns
-------
stations : list of str
Strings representing TMY3 station i... | 5,344,328 |
def artist_html_file_path(artist) -> Path: # Used
"""Return absolute artists HTML file path.
Parameters
----------
artist
Artist name.
Returns
-------
:cod:`Path`
Absolute artists HTML file path.
"""
artist_file_name = re.sub(r"[\s/]", "_", artist)
return artis... | 5,344,329 |
def _deepfoolx_batch(model, epochs, eta, clip_min, clip_max):
"""DeepFool for multi-class classifiers in batch mode.
"""
original_model_X = model.X
y0 = tf.stop_gradient(model.prob)
B, ydim = tf.shape(y0)[0], y0.get_shape().as_list()[1]
k0 = tf.argmax(y0, axis=1, output_type=tf.int32)
k0 =... | 5,344,330 |
def tokenize(text):
"""
The function to tokenize and lemmatize the text.
Inputs:
text: the text which needs to be tokenized
Outputs:
tokens: tokens which can be used in machine learning
"""
stop_words = stopwords.words("english")
... | 5,344,331 |
def remove_task(name: str):
"""
Delete a task based on information "name":
- **name**: each tasks must have a name
"""
name_idx = _db_has_name(name)
if name_idx == None:
raise HTTPException(status_code = 400, detail = {"message" : "name doesn't exists"})
else:
del db["tasks... | 5,344,332 |
def set_dj_definition(cls, type_map: dict = None) -> None:
"""Set the definition property of a class by inspecting its attributes.
Params:
cls: The class whose definition attribute should be set
type_map: Optional additional type mappings
"""
# A mapping between python types and DataJoi... | 5,344,333 |
def test_location_string():
"""Tests that Locations __str__ method returns correctly."""
test_obj = Location("Hovel", "a drab and dingy room", (0, 0, 0))
assert test_obj.__str__() == "Hovel - a drab and dingy room" | 5,344,334 |
def mmap_zeros(shape, dtype):
"""
Create an empty shared memory array.
"""
new = anonymousmemmap(shape, dtype)
new[:] = 0.0
return new | 5,344,335 |
def edge_disjoint_paths(g: Graph, source: Node, sink: Node) -> Iterable:
""" Given directed graph G, and two nodes s and t, find k paths from
s to t such that no two paths share an edge.
Menger’s Theorem: Given a directed graph G with nodes s,t the maximum number of
edge-disjoint s-... | 5,344,336 |
def listToMLlibVectorUDF(col):
""" Map struct column from list to MLlib vector """
return Column(default().listToMLlibVectorUDF(col._jc)) | 5,344,337 |
def change_file_paths_to_showcase(df, showcase_dir="/showcase_data/raw_data"):
"""Changes file paths to use showcase directory"""
output = df.copy()
if "file_path" in df.columns:
output.loc[:, "file_path"] = df.file_path.apply(
lambda x: add_path(x, showcase_dir)
)
if "file_p... | 5,344,338 |
def clear_message(self, trace_number):
"""
UI function
"""
if(trace_number == 0):
self.Message1.configure(background="green", font=("Helvetica",24))
elif(trace_number == 1):
self.Message1.configure(background="#d9d9d9", font=("Helvetica",10))
self.Message2.configure(backgrou... | 5,344,339 |
def match_conftest_error(line):
"""
Extract `ConftestImportFailure` error message from a string.
:param line: A string to pattern match against.
:returns: A dictionary where the key `file_path` holds the file path and the
key `error` the error description. If not matched, the dictionary is
... | 5,344,340 |
def modifyModlist(
old_entry,new_entry,ignore_attr_types=None,ignore_oldexistent=0
):
"""
Build differential modify list for calling LDAPObject.modify()/modify_s()
old_entry
Dictionary holding the old entry
new_entry
Dictionary holding what the new entry should be
ignore_attr_types
List o... | 5,344,341 |
def temporary_worker():
"""A pytest fixture that creates a temporary directory and a config file to match. Deletes directory after test"""
def run_worker():
with rq.Connection():
qs = 'labmanager_unittests'
w = rq.Worker(qs)
w.work()
# This task is used to kill t... | 5,344,342 |
def regnety_3200m(**kwargs):
"""
Constructs a RegNet-Y model under 3200M FLOPs.
"""
model = RegNet(regnetY_3200M_config, **kwargs)
return model | 5,344,343 |
def first_and_last_index(arr, number):
"""
Given a sorted array that may have duplicate values, use binary
search to find the first and last indexes of a given value.
Args:
arr(list): Sorted array (or Python list) that may have duplicate values
number(int): Value to search for in the a... | 5,344,344 |
def _get_exposure(fname, stop=None):
"""
:param fname:
path of the XML file containing the exposure
:param stop:
node at which to stop parsing (or None)
:returns:
a pair (Exposure instance, list of asset nodes)
"""
[exposure] = nrml.read(fname, stop=stop)
if not expos... | 5,344,345 |
def salmon(**kwargs):
"""Convert output of Salmon into a feature counts file"""
from sequana import salmon
salmon_input = kwargs["input"]
output = kwargs["output"]
if os.path.exists(salmon_input) is False:
logger.critical("Input file does not exists ({})".format(salmon_input))
gff = kwa... | 5,344,346 |
async def test_internal_discovery_callback_fill_out_default_manufacturer(hass):
"""Test internal discovery automatically filling out information."""
discover_cast, _, _ = await async_setup_cast_internal_discovery(hass)
info = get_fake_chromecast_info(host="host1")
zconf = get_fake_zconf(host="host1", po... | 5,344,347 |
def dcos_api_session(dcos_api_session_factory):
""" Overrides the dcos_api_session fixture to use
exhibitor settings currently used in the cluster
"""
args = dcos_api_session_factory.get_args_from_env()
exhibitor_admin_password = None
expanded_config = get_expanded_config()
if expanded_conf... | 5,344,348 |
def BarycentricInterpolation(bins, pnts):
"""
barycentricinterpolation for given points,
return the barycentric coordinates for points within the grids
INPUT
bins - grids for discretization,
m-length array where bins[i] indicates the mesh along dimension i
pnts - an a... | 5,344,349 |
def submit_rgi_job(sample_instance: AnalysisSample) -> RGIResult:
"""
Given an input AnalysisSample instance, runs RGI and stores result in the database
:param sample_instance: Instance of AnalysisSample object
:return: Populated RGIResult object generated by the method
"""
logger.info(f"Receive... | 5,344,350 |
def test_case_citation_redirect(client, citation):
"""Should allow various forms of citation, should redirect to normalized_cite"""
url = api_reverse("casemetadata-detail", args=[citation.normalized_cite])
# should have received a redirect
response = client.get(url)
check_response(response, status_... | 5,344,351 |
def forwardslash2shift(args=None):
"""
Make forward slash shift when pressed with another key
"""
run_mapper(premade.ForwardSlash2Shift)
return 0 | 5,344,352 |
def user_details_force_sync(auth_entry, strategy, details, user=None, *args, **kwargs): # lint-amnesty, pylint: disable=keyword-arg-before-vararg
"""
Update normally protected user details using data from provider.
This step in the pipeline is akin to `social_core.pipeline.user.user_details`, which update... | 5,344,353 |
def test_get_datasource_by_id(mocker, dm, datasource_details_result):
"""Test getting datasource by uuid"""
dm.client.get = mocker.Mock(return_value=datasource_details_result)
datasource = dm.get_datasource_by_id("abc")
# Make sure we hit the right endpoint
assert dm.client.get.call_count == 1
... | 5,344,354 |
def plotly_figure(figure, id: str):
"""
:param figure: plotly graph object or px figure
:param id: unique id string of format 'id_xxx' with x representin a number
:return: html style string containing a plotly figure
"""
json_figure = figure.to_json()
html = """
<div id="""+id+"""></... | 5,344,355 |
def _add_resources_to_vault_obj(obj, data, columns):
"""Add associated resources to column and data tuples
"""
i = 0
for s in obj.resources:
if obj.resources[i].id:
name = 'resource_id_' + str(i + 1)
data += (obj.resources[i].id,)
columns = columns + (name,)
... | 5,344,356 |
def classify_helmet_belt_worn(x):
"""
This function returns a strinig representation of the int value of the field which specifies whether the
person was wearing a setabelt or a helmet. This specification is from the Road Crash Statistics Victoria , 2013 Edition
document.
:param x: int value represe... | 5,344,357 |
def history_kernels ( estimated_stimulus_kernel, estimated_response_kernel, ci_kernels, ax=None, presentation="left/right", ground_truth=None ):
"""plot history kernels
:Parameters:
*estimated_stimulus_kernel*
stimulus kernel estimated from the data
*estimated_response_kernel*
... | 5,344,358 |
def init_application():
"""Main entry point for initializing the Deckhand API service.
Create routes for the v1.0 API and sets up logging.
"""
config_files = _get_config_files()
paste_file = config_files[-1]
CONF([], project='deckhand', default_config_files=config_files)
setup_logging(CONF... | 5,344,359 |
def specs_url(self):
"""
The Swagger specifications absolute url (ie. `swagger.json`)
:rtype: str
"""
return url_for(self.endpoint('specs'), _external=False) | 5,344,360 |
def construct_db(db: str) -> sqlite3:
"""Build empty database 'db'."""
conn = sqlite3.connect(db)
c = conn.cursor()
c.executescript('''
CREATE TABLE files (
ID INTEGER PRIMARY KEY,
Name TEXT,
Path TEXT,
FullPath TEXT,
isDir INTEGER,
Size I... | 5,344,361 |
def class_javadoc(ns, stmt):
""" Generate javadoc for class (string without '/**' and '*/' but with * on new line) """
description = ''
desc_stmt = search_one(stmt, 'description')
if desc_stmt is not None:
description += ''.join([str(desc_stmt.arg).replace('\n', '\n * ')])
description += ''.... | 5,344,362 |
def r_precision(r):
"""Score is precision after all relevant documents have been retrieved
Relevance is binary (nonzero is relevant).
Args:
r: Relevance scores (list or numpy) in rank order
(first element is the first item)
Returns:
R Precision
"""
r = np.asarray(r) ... | 5,344,363 |
def evaluate_response_selections(
response_selection_results: List[ResponseSelectionEvaluationResult],
output_directory: Optional[Text],
successes: bool,
errors: bool,
disable_plotting: bool,
) -> Dict: # pragma: no cover
"""Creates summary statistics for response selection.
Only considers... | 5,344,364 |
def _async_climate_updater(
lookin_protocol: LookInHttpProtocol,
uuid: str,
) -> Callable[[], Coroutine[None, Any, Remote]]:
"""Create a function to capture the cell variable."""
async def _async_update() -> Climate:
return await lookin_protocol.get_conditioner(uuid)
return _async_update | 5,344,365 |
def load_natural_movies(cpd=1.00):
"""load natural movies dataset
Parameters
----------
- cpd: float of cycles per degree, should be 1.00 or 1.33
"""
if cpd not in {1.00, 1.33}:
raise Exception('cpd must be in {1.00, 1.33}')
if cpd == 1.00:
cpd = '1.00'
elif cpd == 1.33:... | 5,344,366 |
def sort_dataset_by_len(dataset):
"""
returns a dict mapping length -> list of items of that length
an OrderedDict is used to that the mapping is sorted from smallest to largest
"""
sorted_dataset = collections.OrderedDict()
lengths = sorted(list(set(len(x[1]) for x in dataset)))
for l in le... | 5,344,367 |
def add_note(note_dict):
"""
Add note entries in the db
"""
# Cleanup: Remove print() and set logger here.
pprint.pprint(note_dict)
# Cleanup: Remove print() and set logger here.
print("Adding your note to the database!") | 5,344,368 |
def rule_VisibleTo_if_in_same_visible_container(x, actor, world) :
"""Anything in the same visible container to the actor is visible
if the visible container is lit. We treat doors specially: if x
is in the get_room_doors of the visible container, then the door
is visible, too."""
actor_vis_cont = ... | 5,344,369 |
def select_random_user_goals(user_goals_no_req_slots, user_goals_with_req_slots, cardinality_no_req, cardinality_req):
"""
Helper method to randomly select user goals
"""
random_user_goals = {}
random_user_goals['all'] = []
# select randomly user goals without request slots
random_user_goa... | 5,344,370 |
def dict_items_recursive_apply(config_dict, apply_method, **apply_method_parameters):
"""Recursive apply method to dict elements
>>> dict_items_recursive_apply(
... {"foo": {"bar":"baz"}, "qux": ["a","b"]},
... lambda k,v,x: v.upper()+x, **{"x":"!"}
... ) == {'foo': {'bar': 'BAZ!'}, 'qux': ... | 5,344,371 |
def d_B_nu_d_T_d_nu_dimensionless(x):
"""
Calculates d^2(B_nu) / d (T) / d (nu),
as a function of dimensionless units, x = (h nu / k_B T)
Parameters
----------
x : float
Returns
-------
d_B_nu_d_T_d_nu_dimensionless : float
Not normalized to anything meaningful
"""
return - np.exp(x)*x**3 * (np.exp(x)*... | 5,344,372 |
def test_sbas():
"""./ReadRinex.py -q tests/demo3.10n -o r3sbas.nc
"""
pytest.importorskip('netCDF4')
truth = xarray.open_dataset(R/'r3sbas.nc', group='NAV', autoclose=True)
nav = gr.load(R/'demo3.10n')
assert nav.equals(truth) | 5,344,373 |
def node_to_get_batch_value(shape_node: Node):
"""
The function returns a node that produces the batch value which is usually the element of the shape with index 0
:param shape_node: the node of 1D output shape to get batch from
:return: the node producing batch value
"""
return node_to_get_shap... | 5,344,374 |
def compare_table_defs(psql, db, table, cur_tbl_def, tmp_tbl_def):
"""
Compare table definitions before allowing supported modifications.
Currently, only adding new columns is allowed.
Args:
psql -- handle to talk to redshift
db -- redshift database containing table
table -- table name for ... | 5,344,375 |
def re2_full_match(input, pattern): # pylint: disable=redefined-builtin
"""Extract regex groups
Args:
input: A `tf.string` tensor
pattern: A pattern string.
"""
return core_ops.io_re2_full_match(input, pattern) | 5,344,376 |
def user_agent():
"""
Return a User-Agent that identifies this client.
Example:
python-requests/2.9.1 edx-rest-api-client/1.7.2 ecommerce
The last item in the list will be the application name, taken from the
OS environment variable EDX_REST_API_CLIENT_NAME. If that environment
variabl... | 5,344,377 |
def optional_tools_or_packages_arg(multiple=False):
""" Decorate click method as optionally taking in the path to a tool
or directory of tools or a Conda package. If no such argument is given
the current working directory will be treated as a directory of tools.
"""
name = "paths" if multiple else "... | 5,344,378 |
def revoke_api_access(application):
"""
Revoke the API access of this application
"""
try:
file = open(PATH + '/../DB/access.json', 'r')
accessData = json.load(file)
if (application in accessData):
accessData.pop(application, None)
with open(PATH + '/../DB/ac... | 5,344,379 |
def linear_interpolate_cdf(base_cdf):
"""Linear interpolate regions of straight lines in the CDF.
Parameters:
base_cdf (list): n elements of non-decreasing order.
Returns:
list of length base_cdf where consecutive elements of straight lines
are linearly interpolated between the lef... | 5,344,380 |
def test_mean_los_velocity_vs_rp_correctness1():
""" This function tests that the
`~halotools.mock_observables.mean_los_velocity_vs_rp` function returns correct
results for a controlled distribution of points whose mean radial velocity
is analytically calculable.
For this test, the configuration is... | 5,344,381 |
def hash_str(string: str) -> int:
"""
Create the hash for a string (poorly).
"""
hashed = 0
results = map(ord, string)
for result in results:
hashed += result
return hashed | 5,344,382 |
def graph(g: nx.Graph, s: Optional[list] = None, plot_size: Tuple = (500, 500)): # pragma: no cover
"""Creates a plot of the input graph.
This function can plot the input graph only, or the graph with a specified subgraph highlighted.
Graphs are plotted using the Kamada-Kawai layout with an aspect ratio o... | 5,344,383 |
def intersect(p1x, p1y, p2x, p2y, x0, y0):
"""Intersect segment defined by p1 and p2 with ray coming out of x0,y0 ray
can be horizontal y=y0 x=x0+dx , want dx>0.
Args:
p1x (float): x coordinate of point 1 of segment
p1y (float): y coordinate of point 1 of segment
p2x (float): x coo... | 5,344,384 |
def impulse_matrix(params, dt, reduced=False):
"""Calculate the matrix exponential for integration of MAT model"""
from scipy import linalg
a1, a2, b, w, R, tm, t1, t2, tv, tref = params
if not reduced:
A = - np.matrix([[1 / tm, -1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
... | 5,344,385 |
def get_vimg(request):
"""
获取验证码
:param request:
:return:
"""
text, image = vcode.gen_captcha_text_and_image()
v_key = request.GET.get('vk')
ex_key = request.GET.get('ex')
if ex_key:
try:
redis_conn.delete(ex_key)
except Exception as e:
logger.error(e)
redis_conn.set(v_key, text, 60*3)
return... | 5,344,386 |
def generate_fcm_token():
"""Generate an FCM token
nLAUJTr5RIJ:MNmSQ8O52FoJSvfWEPF4KvWopcNScNFRPHHbXdepwzuXJJMfadpEfb2JlHoqEhWanFz7-N0sfPg-pW4gNubNdxyikiI0lrvGeWGTp86fn9-NA3sZ-Eizv9QE7YKHCOIa70fR38N1ZYsb
"""
return '{}:{}-{}-{}-{}-{}'.format(random_all(11),
random_a... | 5,344,387 |
def build_latex():
"""Builds the LaTeX from source
"""
proc = subprocess.Popen(
['pdflatex {}'.format(LATEX_TEMPORARY_TXT)],
cwd=LATEX_TEMPORARY_DIR,
shell=True,
stdout=subprocess.PIPE)
(_, _) = proc.communicate() | 5,344,388 |
def test_read_text_by_index():
"""
This function tests the read_text_columns_by_index function to
ensure it properly reads in a space delimited text file with
a header in the top row
"""
if plat in lin_plat:
file_name = '../data/test/textcol3.txt'
else:
file_name = r'..\data... | 5,344,389 |
def _create_group(username: str, gid: Optional[int] = None, system: bool = False) -> Result[Group]:
"""
Create a new group.
"""
try:
get_group(username)
except KeyError:
pass
else:
raise ValueError("Username {!r} is already in use".format(username))
args = ["/usr/sbin... | 5,344,390 |
def evaluate(data_loader):
"""Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output
"""
translation_out = []
all_inst_ids ... | 5,344,391 |
def adding_equation(thetas, eta0, eta1, eta2, eta3, kappa3 = 0.0, polarized=False, tau1=0.0, tau2=0.0):
""" Return the reflectance of a 4 layers material (3 interfaces)
with all inter-reflections, using adding equation """
zeros = [np.zeros_like(thetas),np.zeros_like(thetas)] if polarized else np.zeros_... | 5,344,392 |
def text_expand(context):
"""
Give context, pick out the bible indexes, turn them into normalized scripture, and put the scripture back into the context
"""
output = []
end = 0
for m in candidate_filter(context):
output.append(m.group('out'))
try:
bucket = get_bucket(... | 5,344,393 |
def json_custom_parser(obj):
"""
A custom json parser to handle json.dumps calls properly for Decimal and
Datetime data types.
"""
if not isinstance(obj, string_types) and isinstance(obj, Iterable):
return list(obj)
elif isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date... | 5,344,394 |
def like():
""" Function to automatically like a picture
:return: 0 or 1 where 1 = one picture liked
:rtype: int
"""
like_icons = driver.find_elements_by_xpath("//*[contains(@aria-label, 'Like')]")
unlike_icons = driver.find_elements_by_xpath("//*[contains(@aria-label, 'Unlike')]")
for icon... | 5,344,395 |
def entity_tsv(args):
""" Get list of entities in TSV format. Download files for which the
encoding is undetected (e.g. ZIP archives). """
r = fapi.get_entities_tsv(args.project, args.workspace,
args.entity_type, args.attrs, args.model)
fapi._check_response_code(r, 200)
... | 5,344,396 |
def compare_files(file_name1, file_name2):
"""
Compare two files, line by line, for equality.
Arguments:
file_name1 (str or unicode): file name.
file_name2 (str or unicode): file name.
Returns:
bool: True if files are equal, False otherwise.
"""
with open(file_name1) as f... | 5,344,397 |
def print_cv_folds_dates(dates: Dict[Any, Any], freq: str) -> None:
"""Displays a message in streamlit dashboard with cross-validation folds' dates.
Parameters
----------
dates : Dict
Dictionary containing cross-validation dates information.
freq : str
Dataset frequency.
"""
... | 5,344,398 |
def like(request, pk):
"""Add a user to those who liked the post.
Only authenticated users are able to like a post.
"""
if request.method == 'POST':
# query the post in question
try:
post = Post.objects.get(pk=pk)
except Post.DoesNotExist:
return Respons... | 5,344,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.