content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import optparse
def ParseArgs():
"""Parses command line options.
Returns:
An options object as from optparse.OptionsParser.parse_args()
"""
parser = optparse.OptionParser()
parser.add_option('--android-sdk', help='path to the Android SDK folder')
parser.add_option('--android-sdk-tools',
... | 492894d0cb4faf004f386ee0f4285180d0a6c37d | 13,270 |
def get_interface_from_model(obj: Base) -> str:
"""
Transform the passed model object into an dispatcher interface name.
For example, a :class:``Label`` model will result in a string with the value `labels` being
returned.
:param obj: the model object
:return: the interface string
"""
... | 2ee8d1ac86b0d8d6433ace8d58483dbf91af997b | 13,271 |
import codecs
def get_text(string, start, end, bom=True):
"""This method correctly accesses slices of strings using character
start/end offsets referring to UTF-16 encoded bytes. This allows
for using character offsets generated by Rosette (and other softwares)
that use UTF-16 native string represent... | ffe3c74a248215a82b0e0a5b105f5e4c94c8c2a8 | 13,272 |
import math
def init_distance(graph: dict, s: str) -> dict:
"""
初始化其他节点的距离为正无穷
防止后面字典越界
"""
distance = {s: 0}
for vertex in graph:
if vertex != s:
distance[vertex] = math.inf
return distance | dd8ceda3ca7435b5f02b7b47a363f017f796bc36 | 13,273 |
def read_cry_data(path):
"""
Read a cry file and extract the molecule's geometry.
The format should be as follows::
U_xx U_xy U_xz
U_yx U_yy U_yz
U_zx U_zy U_zz
energy (or comment, this is ignored for now)
ele0 x0 y0 z0
ele1 x1 y1 z1
...
elen... | 3a7a88e9d70c5f7499ad219602062ad2d852139b | 13,274 |
import torch
def get_camera_wireframe(scale: float = 0.3):
"""
Returns a wireframe of a 3D line-plot of a camera symbol.
"""
a = 0.5 * torch.tensor([-2, 1.5, 4])
b = 0.5 * torch.tensor([2, 1.5, 4])
c = 0.5 * torch.tensor([-2, -1.5, 4])
d = 0.5 * torch.tensor([2, -1.5, 4])
C = torch.zer... | 65bb8fa078f2f6f3edb38ac86da0603073fd413f | 13,275 |
def read_input(file):
"""
Args:
file (idx): binary input file.
Returns:
numpy: arrays for our dataset.
"""
with open(file, 'rb') as file:
z, d_type, d = st.unpack('>HBB', file.read(4))
shape = tuple(st.unpack('>I', file.read(4))[0] for d in range(d))
retur... | 91b10314a326380680898efdb8a7d15aa7a84f24 | 13,276 |
from typing import List
def maximum_segment_sum(input_list: List):
"""
Return the maximum sum of the segments of a list
Examples::
>>> from pyske.core import PList, SList
>>> maximum_segment_sum(SList([-5 , 2 , 6 , -4 , 5 , -6 , -4 , 3]))
9
>>> maximum_segment_sum(PList.f... | a42b41f3a3b020e0bcba80b557c628b2a0805caf | 13,277 |
def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load.
(default=None)
sat_id : (string or NoneType)
Specifies th... | a302202b7a12534186cfabe66a788df5c29b3266 | 13,278 |
def has_bookmark(uri):
"""
Returns true if the asset with given URI has been bookmarked by the
currently logged in user. Returns false if there is no currently logged
in user.
"""
if is_logged_in():
mongo.db.bookmarks.ensure_index('username')
mongo.db.bookmarks.ensure_in... | 8571c8b50c28a0e8829a143b1d33fd549cfad213 | 13,279 |
import six
import tqdm
def evaluate(f, K, dataiter, num_steps):
"""Evaluates online few-shot episodes.
Args:
model: Model instance.
dataiter: Dataset iterator.
num_steps: Number of episodes.
"""
if num_steps == -1:
it = six.moves.xrange(len(dataiter))
else:
it = six.moves.xrange(num_ste... | a6feebd96907f01789dd74bfb22e5a5306010bf9 | 13,280 |
def find_period_of_function(eq,slopelist,nroots):
"""This function finds the Period of the function.
It then makes a list of x values that are that period apart.
Example Input: find_period_of_function(eq1,[0.947969,1.278602])
"""
global tan
s1 = slopelist[0]
s2 = slopelist[1]
if tan == 1... | 491d853aa99a31348a3acce1c29cc508e7ab3b69 | 13,281 |
def merge_date_tags(path, k):
"""called when encountering only tags in an element ( no text, nor mixed tag and text)
Arguments:
path {list} -- path of the element containing the tags
k {string} -- name of the element containing the tags
Returns:
whatever type you want -- th... | 2ae3bd0dada288b138ee450103c0b4412a841336 | 13,282 |
def ocp_play():
"""Decorator for adding a method as an common play search handler."""
def real_decorator(func):
# Store the flag inside the function
# This will be used later to identify the method
if not hasattr(func, 'is_ocp_playback_handler'):
func.is_ocp_playback_handler ... | 9e96fe81b331820bf7485501e458cbb4efba4328 | 13,283 |
def _scatter(x_arr, y_arr, attributes, xlabel=None, xlim=None, xlog=False,
ylabel=None, ylim=None, ylog=False,
show=True, save=None):
"""Private plotting utility function."""
# initialise figure and axis settings
fig = plt.figure()
... | 8494f9398ea0e5d197a58ea341c626e03d47b028 | 13,284 |
def first_item(iterable, default=None):
"""
Returns the first item of given iterable.
Parameters
----------
iterable : iterable
Iterable
default : object
Default value if the iterable is empty.
Returns
-------
object
First iterable item.
"""
if not ... | f5ebbaea7cf4152382fb4b2854f68a3320d21fdc | 13,285 |
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encod... | 086d2e50b083a869fff2c06b4da7c04975b19fa3 | 13,287 |
def FileDialog(prompt='ChooseFile', indir=''):
"""
opens a wx dialog that allows you to select a single
file, and returns the full path/name of that file """
dlg = wx.FileDialog(None,
message = prompt,
defaultDir = indir)
if dl... | cef7816a40297a5920359b2dba3d7e3e6f6d11ec | 13,288 |
def my_account():
"""
Allows a user to manage their account
"""
user = get_user(login_session['email'])
if request.method == 'GET':
return render_template('myAccount.html', user=user)
else:
new_password1 = request.form.get('userPassword1')
new_password2 = request.form.get... | f3e762931201ed82fa07c7b08c8bc9913c3729dd | 13,289 |
from typing import List
def __pad_assertwith_0_array4D(grad: 'np.ndarray', pad_nums) -> 'np.ndarray':
"""
Padding arrary with 0 septally.
:param grad:
:param pad_nums:
:return:
"""
gN, gC, gH, gW = grad.shape
init1 = np.zeros((gN, gC, gH + (gH - 1) * pad_nums, gW), dtype = grad.dtype)... | 3562e42800c25a059f82a0d163e239badefdcfd3 | 13,290 |
def islist(data):
"""Check if input data is a list."""
return isinstance(data, list) | 98769191b0215f8f863047ccc0c37e4d0af0a444 | 13,291 |
def spatial_mean(xr_da, lon_name="longitude", lat_name="latitude"):
"""
Perform averaging on an `xarray.DataArray` with latitude weighting.
Parameters
----------
xr_da: xarray.DataArray
Data to average
lon_name: str, optional
Name of x-coordinate
lat_name: str, optional
... | 5afb6cb9e9a6b88cc3368da4f3544ea9b7c217be | 13,292 |
def rank(value_to_be_ranked, value_providing_rank):
"""
Returns the rank of ``value_to_be_ranked`` in set of values, ``values``.
Works even if ``values`` is a non-orderable collection (e.g., a set).
A binary search would be an optimized way of doing this if we can constrain
``values`` to be an order... | 18c2009eb59b62a2a3c63c69d55f84a6f51e5953 | 13,293 |
def Characteristics(aVector):
"""
Purpose:
Compute certain characteristic of data in a vector
Inputs:
aVector an array of data
Initialize:
iMean mean
iMed median
iMin minimum
iMax maximum
iKurt kurtosis
iS... | 228ba375a7fca9a4e13920e6eadd0dab83b0847c | 13,294 |
def loglik(alpha,gamma_list,M,k):
"""
Calculate $L_{[\alpha]}$ defined in A.4.2
"""
psi_sum_gamma=np.array(list(map(lambda x: psi(np.sum(x)),gamma_list))).reshape((M,1)) # M*1
psi_gamma=psi(np.array(gamma_list)) # M*k matrix
L=M*gammaln(np.sum(alpha)-np.sum(gammaln(alpha)))+np.sum((psi_gamma-ps... | 233307f7ef4e350bec162199a5d0cd8c773b4151 | 13,295 |
from gum.indexer import indexer, NotRegistered
def handle_delete(sender_content_type_pk, instance_pk):
"""Async task to delete a model from the index.
:param instance_pk:
:param sender_content_type_pk:
"""
try:
sender_content_type = ContentType.objects.get(pk=sender_content_type_pk)
... | 049af2041e3ea33bdfddf81c72aeb95b04e5f60c | 13,296 |
def fixedcase_word(w, truelist=None):
"""Returns True if w should be fixed-case, None if unsure."""
if truelist is not None and w in truelist:
return True
if any(c.isupper() for c in w[1:]):
# tokenized word with noninitial uppercase
return True
if len(w) == 1 and w.isupper() and... | 9047866f7117e8b1e4090c8e217c3063cfd37c38 | 13,298 |
import torch
import types
def linspace(
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
split=None,
device=None,
comm=None,
):
"""
Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can
optionally b... | 0597835fae9658f65553496b1272d786678919c2 | 13,299 |
def _h1_cmp_chi2_ ( h1 ,
h2 ,
density = False ) :
"""Compare histograms by chi2
>>> h1 = ... ## the first histo
>>> h2 = ... ## the second histo (or function or anything else)
>>> chi2ndf , probability = h1.cmp_chi2 ( h2 )
"""
... | ff2e5c191491c18adc29edf08a5bb837fabf045f | 13,300 |
def _questionnaire_metric(name, col):
"""Returns a metrics SQL aggregation tuple for the given key/column."""
return _SqlAggregation(
name,
"""
SELECT {col}, COUNT(*)
FROM participant_summary
WHERE {summary_filter_sql}
GROUP BY 1;
""".format(
col=col, su... | abd477798670733788461ed35fc0b4814ee7081d | 13,301 |
import re
def xyzToAtomsPositions(xyzFileOrStr):
"""
Returns atom positions (order) given a molecule in an xyz format.
Inchi-based algorithm.
Use this function to set the atoms positions in a reference
molecule. The idea is to assign the positions once and to never
change them again.
Arg... | 8db5c81d0e8aca2eef686d955ed810b4b166d0db | 13,302 |
async def modify_video_favorite_list(
media_id: int,
title: str,
introduction: str = '',
private: bool = False,
credential: Credential = None):
"""
修改视频收藏夹信息。
Args:
media_id (int) : 收藏夹 ID.
title (str) : 收藏夹名。
introducti... | e3618fc59785b63cf7f6810a0f2683bcd18d5277 | 13,303 |
def get_salesforce_log_files():
"""Helper function to get a list available log files"""
return {
"totalSize": 2,
"done": True,
"records": [
{
"attributes": {
"type": "EventLogFile",
"url": "/services/data/v32.0/sobjects/... | 1c182898517d73c360e9f2ab36b902afea8c58d7 | 13,304 |
def remove_true_false_edges(dict_snapshots, dict_weights, index):
"""
Remove chosen true edges from the graph so the embedding could be calculated without them.
:param dict_snapshots: Dict where keys are times and values are a list of edges for each time stamp.
:param dict_weights: Dict where keys are t... | 3f833fda22710c20703aa7590eae0fd649b69634 | 13,305 |
def addFavoriteDir(name:str, directory:str, type:str=None, icon:str=None, tooltip:str=None, key:str=None):
"""
addFavoriteDir(name, directory, type, icon, tooltip, key) -> None.
Add a path to the file choosers favorite directory list. The path name can contain environment variables which will be expanded w... | 28cbabd79d35151877112dd76ffe2a513a2bfcec | 13,306 |
def save(data):
"""Save cleanup annotations."""
data_and_frames = data.split("_")
data = data_and_frames[0]
frames = data_and_frames[1]
if len(data) == 1:
removed = []
else:
removed = [int(f) for f in data[1:].split(':')]
frames = [int(f) for f in frames[:].split(':')]
... | be62bd3933374ebac8e735be0f66ca79a6273b35 | 13,307 |
import re
def list_runs_in_swestore(path, pattern=RUN_RE, no_ext=False):
"""
Will list runs that exist in swestore
:param str path: swestore path to list runs
:param str pattern: regex pattern for runs
"""
try:
status = check_call(['icd', path])
proc = Popen(['ils'... | 616089f049129b284ae6575609741620f2ac48f6 | 13,308 |
def linear_regression(
XL: ArrayLike, YP: ArrayLike, Q: ArrayLike
) -> LinearRegressionResult:
"""Efficient linear regression estimation for multiple covariate sets
Parameters
----------
XL
[array-like, shape: (M, N)]
"Loop" covariates for which N separate regressions will be run
... | 3059987940eefce0a4a401c096d8b7be0d3ce1d7 | 13,309 |
import math
def orthogonal_decomposition(C, tr_error, l_exp):
"""
Orthogonal decomposition of the covariance matrix to determine the meaningful directions
:param C: covariance matrix
:param tr_error: allowed truncation error
:param l_exp: expansion order
:return: transformation matrix Wy, nu... | d6920b31a0503ad15b98631de352da690b6761b8 | 13,310 |
import http
import json
def get_data():
"""Reads the current state of the world"""
server = http.client.HTTPConnection(URL)
server.request('GET','/data')
response = server.getresponse()
if (response.status == 200):
data = response.read()
response.close()
return json.loads(d... | 3c0563f2776c60ea103db154c63e2053b1d7d045 | 13,311 |
def chi_angles(filepath, model_id=0):
"""Calculate chi angles for a given file in the PDB format.
:param filepath: Path to the PDB file.
:param model_id: Model to be used for chi calculation.
:return: A list composed by a list of chi1, a list of chi2, etc.
"""
torsions_list = _sidechain_torsio... | 85c192fe6c272cad5cdd7dbb4f570f1f78284057 | 13,312 |
def surface_sphere(radius):
"""
"""
phi, theta = np.mgrid[0.0:np.pi:100j, 0.0:2.0*np.pi:100j]
x_blank_sphere = radius*np.sin(phi)*np.cos(theta)
y_blank_sphere = radius*np.sin(phi)*np.sin(theta)
z_blank_sphere = radius*np.cos(phi)
sphere_surface = np.array(([x_blank_sphere,
... | 25750b7c4a57dd3a2f3ebb5a2a041fa1f5e56c89 | 13,313 |
import re
def format_bucket_objects_listing(bucket_objects):
"""Returns a formated list of buckets.
Args:
buckets (list): A list of buckets objects.
Returns:
The formated list as string
"""
out = ""
i = 1
for o in bucket_objects:
# Shorten to 24 chars max, remove... | f5268d148687338ed606b1593065a0c1842cac00 | 13,314 |
def charts(chart_type, cmid, start_date, end_date=None):
"""
Get the given type of charts for the artist.
https://api.chartmetric.com/api/artist/:id/:type/charts
**Parameters**
- `chart_type`: string type of charts to pull, choose from
'spotify_viral_daily', 'spotify_viral_weekly',
... | 2dfafd09f53bf2add20afcba8c85a6f081e551af | 13,315 |
def search_candidates(api_key, active_status="true"):
"""
https://api.open.fec.gov/developers#/candidate/get_candidates_
"""
query = """https://api.open.fec.gov/v1/candidates/?sort=name&sort_hide_null=false&is_active_candidate={active_status}&sort_null_only=false&sort_nulls_last=false&page=1&per_page=20... | 9ec1c39541cda87f1d1618d4e5497b8215a5f4b4 | 13,317 |
def load_dat(file_name):
"""
carga el fichero dat (Matlab) especificado y lo
devuelve en un array de numpy
"""
data = loadmat(file_name)
y = data['y']
X = data['X']
ytest = data['ytest']
Xtest = data['Xtest']
yval = data['yval']
Xval = data['Xval']
return X,y,Xtest,ytest,... | 5c3de04f60ea803e1c70dbc2103425b10ee58567 | 13,318 |
def get_specific_pos_value(img, pos):
"""
Parameters
----------
img : ndarray
image data.
pos : list
pos[0] is horizontal coordinate, pos[1] is verical coordinate.
"""
return img[pos[1], pos[0]] | 3929b29fa307a7e8b5282783c16639cacb2ab805 | 13,319 |
from typing import List
from typing import Tuple
from typing import Dict
from typing import Any
from typing import Set
def transpose_tokens(
cards: List[MTGJSONCard]
) -> Tuple[List[MTGJSONCard], List[Dict[str, Any]]]:
"""
Sometimes, tokens slip through and need to be transplanted
back into their appr... | 339e8d18a4c80e168411c874f8afac97b14db77b | 13,320 |
from datetime import datetime
def from_local(local_dt, timezone=None):
"""Converts the given local datetime to a universal datetime."""
if not isinstance(local_dt, datetime.datetime):
raise TypeError('Expected a datetime object')
if timezone is None:
a = arrow.get(local_dt)
else:
... | 6b4eb44aa66c04a23aa8dac2bbe882e5619cd45f | 13,321 |
import re
def mrefresh_to_relurl(content):
"""Get a relative url from the contents of a metarefresh tag"""
urlstart = re.compile('.*URL=')
_, url = content.split(';')
url = urlstart.sub('', url)
return url | 90cc3dbace5d4b001698612f9263309fa95aac8b | 13,322 |
import torch
def simclr_loss_func(
z1: torch.Tensor,
z2: torch.Tensor,
temperature: float = 0.1,
extra_pos_mask=None,
) -> torch.Tensor:
"""Computes SimCLR's loss given batch of projected features z1 from view 1 and
projected features z2 from view 2.
Args:
z1 (torch.Tensor): NxD Te... | b9d7880ec1c8a66321623a0061d201f9bbaaa426 | 13,323 |
def find_node_types(G, edge_type):
"""
:param G: NetworkX graph.
:param edge_type: Edge type.
:return: Node types that correspond to the edge type.
"""
for e in G.edges:
if G[e[0]][e[1]][e[2]]['type'] == edge_type:
u, v = e[0], e[1]
break
utype = G.nodes[u]['... | 970bbbabe172460a974dbf961500def2280b9fe1 | 13,324 |
import scipy
def distance_point_point(p1, p2):
"""Calculates the euclidian distance between two points or sets of points
>>> distance_point_point(np.array([1, 0]), np.array([0, 1]))
1.4142135623730951
>>> distance_point_point(np.array([[1, 1], [0, 0]]), np.array([0, 1]))
array([1., 1.])
>>> di... | 481733330a99576540d2a80676d51d315b6406f7 | 13,325 |
def switch(
confs=None, remain=False, all_checked=False, _default=None, **kwargs
):
"""
Execute first statement among conf where task result is True.
If remain, process all statements conf starting from the first checked
conf.
:param confs: task confs to check. Each one may contain a task a... | aba656d4a6d06f721551aa49ec1521d0fa9444d3 | 13,326 |
def makeProcesses(nChildren):
"""
Create and start all the worker processes
"""
global taskQueue,resultsQueue,workers
if nChildren < 0:
print 'makeProcesses: ',nChildren, ' is too small'
return False
if nChildren > 3:
print 'makeProcesses: ',nChildren, ' is too large... | 748372d9c83917841eeba5e400f37a5ecf5961dd | 13,327 |
def create_moleculenet_model(model_name):
"""Create a model.
Parameters
----------
model_name : str
Name for the model.
Returns
-------
Created model
"""
for func in [create_bace_model, create_bbbp_model, create_clintox_model, create_esol_model,
create_free... | 19f15eb4fd1a5c1befaef306cb7d146d7933919e | 13,328 |
from typing import Collection
from typing import Optional
def detect_daml_lf_dir(paths: "Collection[str]") -> "Optional[str]":
"""
Find the biggest Daml-LF v1 version in the set of file names from a Protobuf archive, and return
the path that contains the associated files (with a trailing slash).
If t... | acd2b99236a3534ec64c375893b40511995e6dfc | 13,329 |
def random_mini_batches(X, Y, mini_batch_size):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (m, n_H, n_W, c)
Y -- true "label" vector of shape (m, num_classes)
mini_batch_size -- size of mini-batches, integer
Returns:
mini_ba... | fbad986073bfb867f5e35bf1a0ee639b644f00bb | 13,330 |
import types
def classifyContent(text):
"""
Uses the NLP provider's SDK to perform a content classification operation.
Arguments:
text {String} -- Text to be analyzed.
"""
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT,
language='... | eebb4ebef4811748d5fb9e130e582dae289f9ce7 | 13,331 |
def print_instance_summary(instance, use_color='auto'):
""" Print summary info line for the supplied instance """
colorize_ = partial(colorize, use_color=use_color)
name = colorize_(instance.name, "yellow")
instance_type = instance.extra['gonzo_size']
if instance.state == NodeState.RUNNING:
... | e250645e040fba4bbd9df0e86bc3711d3f8ac51e | 13,332 |
from datetime import datetime
def generate_blob_sas_token(blob, container, blob_service, permission=BlobPermissions.READ):
"""Generate a blob URL with SAS token."""
sas_token = blob_service.generate_blob_shared_access_signature(
container, blob.name,
permission=permission,
start=dateti... | e3993c3dd075516bce07221cf9351ab74a431a27 | 13,333 |
from typing import Sequence
def rewrite_complex_signature(function, signature: Sequence[tf.TensorSpec]):
"""Compatibility layer for testing complex numbers."""
if not all([spec.dtype.is_complex for spec in signature]):
raise NotImplementedError("Signatures with mixed complex and non-complex "
... | e541ef96c6b4f2492847443e8ca45f18fc9383ff | 13,334 |
def get_args(argv: list):
"""gets the args and dictionarize them"""
if len(argv) not in [5,7]:
Errors.args_error()
data = {}
# getting the type of the title
if "-" in argv[1]:
data["type"] = "series" if argv[1] == "-s" else "movie" if argv[1] == "-m" else None
else:
... | 6f29e63bc19b57cdf9f49cf2dd7b099c62a604a0 | 13,335 |
def fund_with_erc20(
to_fund_address, erc20_token_contract, ether_amount=0.1, account=None
):
"""Send a specified amount of an ERC20 token to an address.
Args:
to_fund_address (address): Address to send to the tokens to.
erc20_token_contract (Contract): Contract of the ERC20 token.
... | 6eaf46519645b8b6bbf36b39ea106c05924ab51f | 13,336 |
from carbonplan_trace.v1.glas_preprocess import select_valid_area # avoid circular import
def energy_adj_ground_to_sig_end(ds):
"""
Waveform energy from the ground peak. We calculated senergy_whrc as the energy of the waveform (in digital counts) from the ground peak
to the signal end multiplied by two.... | b1f2f9acacb2186694aec3249632fea1fd4f7a58 | 13,337 |
import logging
def get_previous_version(versions: dict, app: str) -> str:
"""Looks in the app's .version_history to retrieve the prior version"""
try:
with open(f"{app}/.version_history", "r") as fh:
lines = [line.strip() for line in fh]
except FileNotFoundError:
logging.warnin... | d3a4aec5c3bc842181aa3901971774761866c3e5 | 13,338 |
def healthcheck() -> bool:
"""FastAPI server healthcheck."""
return True | 1767229ccda121e88264093c479d2bccf994a7e9 | 13,339 |
def ToHexStr(num):
"""
将返回的错误码转换为十六进制显示
:param num: 错误码 字符串
:return: 十六进制字符串
"""
chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
hexStr = ""
if num < 0:
num = num + 2**32
while num >= 16:
digit = num % 16
hexStr = chaDic.get(digit, str(digit)) ... | b6cf482defdc9f4fcf9ce64903e7a718e096bacb | 13,340 |
import requests
def getSBMLFromBiomodelsURN(urn):
""" Get SBML string from given BioModels URN.
Searches for a BioModels identifier in the given urn and retrieves the SBML from biomodels.
For example:
urn:miriam:biomodels.db:BIOMD0000000003.xml
Handles redirects of the download page.
:p... | 9a28f4a0619ebed6f9e272d84331482442ae9fb8 | 13,341 |
def draw(k, n):
"""
Select k things from a pool of n without replacement.
"""
# At k == n/4, an extra 0.15*k draws are needed to get k unique draws
if k > n/4:
result = rng.permutation(n)[:k]
else:
s = set()
result = np.empty(k, 'i')
for i in range(k):
... | d7135d659fc4e702942ea2da0f794fcb9d77bfd2 | 13,342 |
def print_version(args):
"""Print the version (short or long)"""
# Long version
if len(args) > 0 and args[0] == '--full':
apk_version = dtfglobals.get_generic_global(
dtfglobals.CONFIG_SECTION_CLIENT, 'apk_version')
bundle_version = dtfglobals.get_generic_global(
dt... | b7bec22239e765d3e9c2131302144b0e44360f2a | 13,343 |
from datetime import datetime
def naturalTimeDifference(value):
"""
Finds the difference between the datetime value given and now()
and returns appropriate humanize form
"""
if isinstance(value, datetime):
delta = datetime.now() - value
if delta.days > 6:
return val... | ce285358b1b99a4b2df460e6193d2a0970aa4eff | 13,344 |
def raises_Invalid(function):
"""A decorator that asserts that the decorated function raises
dictization_functions.Invalid.
Usage:
@raises_Invalid
def call_validator(*args, **kwargs):
return validators.user_name_validator(*args, **kwargs)
call_validator(key, data, error... | b1dcaea71cfe95e25029be360645c68a0906346d | 13,345 |
from pathlib import Path
def load_dataset(dataset_path: Path) -> [Instruction]:
"""Returns the program as a list of alu instructions."""
with open_utf8(dataset_path) as file:
program = []
for line in file:
if len(line.strip()) > 0:
instruction = line.strip().split("... | 6d9fd90401c750a4aa5d83491c9610984b95ebd1 | 13,346 |
import json
def process_info(args):
"""
Process a single json file
"""
fname, opts = args
with open(fname, 'r') as f:
ann = json.load(f)
f.close()
examples = []
skipped_instances = 0
for instance in ann:
components = instance['components']
if len(... | 8ade5b21db3cca57d9de91311fc57754161673de | 13,347 |
def logout():
"""
退出登录
:return:
"""
# pop是移除session中的数据(dict),pop会有一个返回值,如果移除的key不存在返回None
session.pop('user_id', None)
session.pop('mobile', None)
session.pop('nick_name', None)
# 要清除is_admin的session值,不然登录管理员后退出再登录普通用户又能访问管理员后台
session.pop('is_admin', None)
return jsonify(er... | a60e91457ddb32bceeda01a66027209adaf8eecb | 13,348 |
def lift_to_dimension(A,dim):
"""
Creates a view of A of dimension dim (by adding dummy dimensions if necessary).
Assumes a numpy array as input
:param A: numpy array
:param dim: desired dimension of view
:return: returns view of A of appropriate dimension
"""
current_dim = len(A.shape... | bc21d0af45e8073f2e8da6ed57c441739a7385f5 | 13,349 |
def search(keyword=None):
"""
Display search results in JSON format
Parameters
----------
keyword : str
Search keyword. Default None
"""
return get_json(False, keyword) | 558a34fedb4e05e7a31b655effa47287cbc46202 | 13,350 |
from typing import List
def min_offerings(heights: List[int]) -> int:
"""
Get the max increasing sequence on the left and the right side of current index,
leading upto the current index.
current index's value would be the max of both + 1.
"""
length = len(heights)
if length < 2:
r... | 952ea82815ecb4db6d4d0347f16b0cf5b299f7d3 | 13,351 |
def pretty(value, width=80, nl_width=80, sep='\n', **kw):
# type: (str, int, int, str, **Any) -> str
"""Format value for printing to console."""
if isinstance(value, dict):
return '{{{0} {1}'.format(sep, pformat(value, 4, nl_width)[1:])
elif isinstance(value, tuple):
return '{}{}{}'.form... | d2af8d83c2e116ebb1a6e65cd369c3a33adf4585 | 13,352 |
def niceNumber(v, maxdigit=6):
"""Nicely format a number, with a maximum of 6 digits."""
assert(maxdigit >= 0)
if maxdigit == 0:
return "%.0f" % v
fmt = '%%.%df' % maxdigit
s = fmt % v
if len(s) > maxdigit:
return s.rstrip("0").rstrip(".")
elif len(s) == 0:
return ... | d57f83272a819d5abf12d71fdac84fe8e92eeb05 | 13,355 |
def query_incident(conditions: list, method=None, plan_status="A", mulitple_fields=False):
"""
Queries incidents in Resilient/CP4S
:param condition_list: list of conditions as [field_name, field_value, method] or a list of list conditions if multiple_fields==True
:param method: set all field conditions... | 9c037b5d864248bd280db644f4c3868557b59721 | 13,356 |
def get_banner():
"""Return a banner message for the interactive console."""
global _CONN
result = ''
# Note how we are connected
result += 'Connected to %s' % _CONN.url
if _CONN.creds is not None:
result += ' as %s' % _CONN.creds[0]
# Give hint about exiting. Most people exit wi... | 5c5e1f2d32548d112f75c933ce4c4e842cdfc993 | 13,357 |
def generate_fish(
n,
channel,
interaction,
lim_neighbors,
neighbor_weights=None,
fish_max_speeds=None,
clock_freqs=None,
verbose=False,
names=None
):
"""Generate some fish
Arguments:
n {int} -- Number of fish to generate
channel {Channel} -- Channel instance... | 58d8fb4626d18caa5b093b30588603f335074e4b | 13,358 |
import functools
def log_exception(function):
"""Exception logging wrapper."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except:
err = "There was an exception in "
err += function.__name__
... | f2c86b168550c12d73d87f1b2001a3caab46ceda | 13,359 |
def calculate_triad_connectivity(tt1, tt2, tt3, ipi1, ipi2, tau_z_pre, tau_z_post,
base_time, base_ipi, resting_time, n_patterns):
"""
This function gives you the connectivity among a triad, assuming that all the other temporal structure outside of
the trial is homogeneus
... | 6497a68bfdbf9db12a6cbef0784c0aacc3f5e055 | 13,360 |
from datetime import datetime
import random
def random_date_from(date,
min_td=datetime.timedelta(seconds=0),
max_td=datetime.timedelta(seconds=0)):
"""
Produces a datetime at a random offset from date.
Parameters:
date: datetime
The reference ... | 2392e6684de81f5e693a7e6fbe4934940df5eada | 13,361 |
def generate_log_normal_dist_value(frequency, mu, sigma, draws, seed_value):
"""
Generates random values using a lognormal distribution,
given a specific mean (mu) and standard deviation (sigma).
https://stackoverflow.com/questions/51609299/python-np-lognormal-gives-infinite-
results-for-big-average... | f0613688a5af83a867825b3e91c8f1f8a99c05ba | 13,362 |
from re import VERBOSE
def compute_mean_field(
grain_index_field,
field_data,
field_name,
vx_size=(1.0, 1.0, 1.0),
weighted=False,
compute_std_dev=False,
):
"""
Compute mean shear system by grains.
Args:
grain_index_field : VTK field containing index
field_dat... | 8baa187a853c1d44597cae0417b455c74db2072d | 13,363 |
def evaluate_argument_value(xpath_or_tagname, datafile):
"""This function takes checks if the given xpath_or_tagname exists in the
datafile and returns its value. Else returns None."""
tree = ET.parse(datafile)
root = tree.getroot()
if xpath_or_tagname.startswith(root.tag + "/"):
xpath_or_ta... | be4597e039717a535a86edfa4b04761417d0eaf4 | 13,364 |
def normalise_genome_position(x):
"""
Normalise position (circular genome)
"""
x['PositionNorm0'] = np.where(x['Position'] > (x['GenomeLength'] / 2),
(x['GenomeLength'] - x['Position']),
x['Position'])
x['PositionNorm'] = x['Positio... | 251808a0c7ea2b4f83e8c82ec06fc2d1d9e9b887 | 13,365 |
from faker import Faker
def random_address(invalid_data):
"""
Generate Random Address
return: string containing imitation postal address.
"""
fake = Faker(['en_CA']) # localized to Canada
return fake.address().replace('\n',', '), global_valid_data | 3375f2eefd05e1575ec8caf2944ee7960a17ca46 | 13,366 |
import math
def rot_poly(angle, polygon, n):
"""rotate polygon into 2D plane in order to determine if a point exists
within it. The Shapely library uses 2D geometry, so this is done in order
to use it effectively for intersection calculations.
Parameters
----------
angle : float
... | 3048d6fac8a5e2dffb3d621c8bec2a25aa6b31d0 | 13,367 |
def bytes_isspace(x: bytes) -> bool:
"""Checks if given bytes object contains only whitespace elements.
Compiling bytes.isspace compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
Returns:
Result of che... | 6c28b904cb6e0ef515ce7a16725fb99a535c3192 | 13,368 |
import re
def snake_case(name: str):
"""
https://stackoverflow.com/a/1176023/1371716
"""
name = re.sub('(\\.)', r'_', name)
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
name = re.sub('__([A-Z])', r'_\1', name)
name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
return name.lower() | 4696ca3c1a50590aa6617ee3917b8364c11f3910 | 13,369 |
import glob
def get_loss_data():
"""
This function returns a list of paths to all .npy loss
files.
Returns
-------
path_list : list of strings
The list of paths to output files
"""
path = "./data/*_loss.npy"
path_list = glob.glob(path, recursive=True)
return path_lis... | bc98b0bdf60ac3f7125da82fd68956957e89a777 | 13,370 |
def ranked_avg_knn_scores(batch_states, memory, k=10, knn=batch_count_scaled_knn):
"""
Computes ranked average KNN score for each element in batch of states
\sum_{i = 1}^{K} (1/i) * d(x, x_i)
Parameters
----------
k: k neighbors
batch_states: numpy array of size [batch_size x state_size]
... | 56d60d97e7c10b06deb417e0d6b52a5a76f9150e | 13,371 |
def login_exempt(view_func):
"""登录豁免,被此装饰器修饰的action可以不校验登录."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.login_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) | d0853317260d68e9ea3d3a70a02c2f1ca67681a2 | 13,372 |
def to_uint8_image(message : ImageMessage) -> ImageMessage:
"""Convert image type to uint8.
Args:
message (ImageMessage): Image to be converted
Returns:
ImageMessage: Resulting iamge
"""
message.image = np.uint8(message.image*255)
if message.mask is not None:
message.ma... | fd9626800b5c0fec284ab185c1ff29e9cfefb3e7 | 13,373 |
import string
def list_zero_alphabet() -> list:
"""Build a list: 0, a, b, c etc."""
score_dirs = ['0']
for char in string.ascii_lowercase:
score_dirs.append(char)
return score_dirs | 6cd9fc9e93257dcc7729235ac3cffa01dbd80c95 | 13,374 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.