content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def contact_ocsp_server(certs):
"""Sends an OCSP request to the responding server for a certificate chain"""
chain = convert_to_oscrypto(certs)
req = create_ocsp_request(chain[0], chain[1])
URI = extract_ocsp_uri(certs[0])
data = requests.post(URI, data=req, stream=True, headers={'Content-Type': 'ap... | 48,100 |
def reset_index_inplace(df: pd.DataFrame, *args, **kwargs) -> pd.DataFrame:
"""
Return the dataframe with an inplace resetting of the index.
This method mutates the original DataFrame.
Compared to non-inplace resetting, this avoids data copying, thus
providing a potential speedup.
In Pandas, ... | 48,101 |
def load_mapping():
"""Load the mapping from the disk.
If the configuration directory files do not exist (probably because it is
the user's first time executing a dtags command), create them.
:return: the mapping object loaded from the disk
"""
try:
# Parse and load the mapping from th... | 48,102 |
def get_current_user():
"""Get the current logged in user, or None."""
if environment.is_local_development():
return User('user@localhost')
current_request = request_cache.get_current_request()
if local_config.AuthConfig().get('enable_loas'):
loas_user = current_request.headers.get('X-AppEngine-LOAS-Pe... | 48,103 |
def shadowed_exec(source: str, *args, **kwargs):
"""
Wrapper for builtin `exec` that accepts source code as input and executes it while preserving
a copy of it in the file system. That's particularly useful when inspecting the state created
by source execution later on.
:param source: source code t... | 48,104 |
def main(args=None):
"""Main entry point of the application."""
parser = argparse.ArgumentParser(description=globals()["__doc__"])
parser.add_argument("entry", help="name of the entry to retrieve")
parser.add_argument("-d", "--database-filepath",
help="optional filepath of databa... | 48,105 |
def genericGetCreationDate(page):
"""
Go to each date position and attempt to get date
"""
randSleep()
allDates = []
signaturePositions = findSignatures(page)
for p in signaturePositions:
timestamp = getTimestampFromSERP(p, page)
# print('timestamp/locationOfSignature:', ti... | 48,106 |
def depth(data):
"""
For each event, it finds the deepest layer in which the shower has
deposited some E.
"""
maxdepth = 2 * (data[2].sum(axis=(1, 2)) != 0)
maxdepth[maxdepth == 0] = 1 * (
data[1][maxdepth == 0].sum(axis=(1, 2)) != 0
)
return maxdepth | 48,107 |
def python_obj_size(obj, humanize=True):
""" 获取一个python对象的大小,默认返回人可读的形式 """
if humanize:
return humanize_bytes(sys.getsizeof(obj))
else:
return sys.getsizeof(obj) | 48,108 |
def transform_user_extensions(user_extension_json):
"""
Transforms the raw extensions JSON from the API into a list of extensions mapped to users
:param user_extension_json: The JSON text blob returned from the CRXcavator API
:return: Tuple containing unique users list, unique extension list, and exten... | 48,109 |
def shower_array_rot(shower_array, alt, az):
"""
Given a series of point on the Z axis, perform a rotation of alt around Y and az around Z
Parameters
----------
shower_array: numpy array of shape (N,3) giving N points coordinates
alt: altitude shower direction - float
az: azimuth shower dir... | 48,110 |
async def on_message(message):
"""
Most importnat feature,
gets called whenever a
message is sent then builds
the log structure.
:param message:
:return:
"""
msg = message.clean_content if not message.attachments else message.attachments[0].url
save_data = {
message.id: {... | 48,111 |
def get_dscp_configuration(dscp_configuration_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDscpConfigurationResult:
"""
Use this data source to access information about an ... | 48,112 |
def aggregate_returns(df_daily_rets, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
df_daily_rets : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet (returns).
convert_to : str
... | 48,113 |
def parse_args(args):
"""Parse the command line arguments."""
parser = argparse.ArgumentParser(
description='STOMP client for Network Rail\'s public data.'
)
subparsers = parser.add_subparsers()
# Creation of new configuration files
create_parser = subparsers.add_parser(
'create'... | 48,114 |
def impute(x,nu):
"""
Impute to missing values: for each row of x this function find the nearest row in eucledian distance
in a sample of nu rows of x and replace the missing value of the former row
with the corrisponding values of the latter row
... | 48,115 |
def test_resolve_add_new_mates_fail_bulk() -> None:
"""Raises error when failed to bulk insert new mates."""
with pytest.raises(Exception, match="New mates not created"):
resolve_add_new_mates(None, None, []) | 48,116 |
def get_data_splits(comment_type_str=None, ignore_ast=False):
"""Retrieves train/validation/test sets for the given comment_type_str.
comment_type_str -- Return, Param, Summary, or None (if None, uses all comment types)
ignore_ast -- Skip loading ASTs (they take a long time)"""
dataset, high_level... | 48,117 |
def copy_support_files(file_path):
"""Copy the support files to a named destination
file_path: path where you want the support files to be copied to
Will raise EmperorSupportFilesError if a problem is found whilst trying to
copy the files.
"""
file_path = join(file_path, 'emperor_required_res... | 48,118 |
def get_slide_roi_masks(slide_path, halo_roi_path, annotation_name, slide_id:str=None,
output_dir:str=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""get roi masks from slides
Given a slide, halo annotation xml file, generate labels from xml polygons,
then crop both the image and mask to ... | 48,119 |
def generate_stop_enex_nb(entries: tp.Array2d,
ts: tp.Array,
stop: tp.MaybeArray[float],
trailing: tp.MaybeArray[bool],
entry_wait: int,
exit_wait: int,
pick_first:... | 48,120 |
def mangle_type(typ):
"""
Mangle Numba type
"""
if typ in N2C:
typename = N2C[typ]
else:
typename = str(typ)
return mangle_type_c(typename) | 48,121 |
def lorentz(sample_len=1000, sigma=10, rho=28, beta=8 / 3, step=0.01):
"""This function generates a Lorentz time series of length sample_len,
with standard parameters sigma, rho and beta.
"""
x = np.zeros([sample_len])
y = np.zeros([sample_len])
z = np.zeros([sample_len])
# Initial conditi... | 48,122 |
def draw_lane_lines_on_all_images(images, cols=2, rows=3, figsize=(15, 13)):
"""
This method calls draw_windows_and_fitted_lines Fn for each image and then show the grid of output images.
"""
no_of_images = len(images)
fig, axes = plt.subplots(rows, cols, figsize=figsize)
indexes = range(cols * r... | 48,123 |
def test_synced_dataset():
"""
test_synced_dataset tests test_sync_dataset with an input
which is already synced. Should return a dataset the same as the input one.
"""
# Note we are testing only the first channel
# What is a good way to test all the entries of the dictionary at the same... | 48,124 |
def get_field_order(address, latin=False):
"""
Returns expected order of address form fields as a list of lists.
Example for PL:
>>> get_field_order({'country_code': 'PL'})
[[u'name'], [u'company_name'], [u'street_address'], [u'postal_code', u'city']]
"""
rules = get_validation_rules(address... | 48,125 |
def env_start():
""" returns numpy array """
global maze, current_position
current_position = 500
return current_position | 48,126 |
def bootstrap_acceleration(d):
""" Bootstrap (BCA) acceleration term.
Args:
d : Jackknife differences
Returns:
a : Acceleration
"""
return np.sum(d**3) / np.sum(d**2)**(3.0/2.0) / 6.0 | 48,127 |
def normalize_map(x):
"""
normalize map input
:param x: map input (H, W, ch)
:return np.ndarray: normalized map (H, W, ch)
"""
# rescale to [0, 2], later zero padding will produce equivalent obstacle
return x * (2.0/255.0) | 48,128 |
def parse_bam():
"""
Reads bam file and saves reads and their segments in objects of the Read en Segment classes.
:param bamfile used to open bam file:
"""
global sample_name, header, bam
sys.stderr.write(time.strftime("%c") + " Busy with parsing bam file...\n")
bam = pysam.AlignmentFile(Na... | 48,129 |
def today():
"""Get the today of int date
:return: int date of today
"""
the_day = date.today()
return to_int_date(the_day) | 48,130 |
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
{
'title':'联系我们',
'message':'你可以通过以下方式和我们取得联系',
'year':datetime.now().year,
}
) | 48,131 |
def plagdet_score(rec, prec, gran):
"""Combines recall, precision, and granularity to a allow for ranking."""
if (rec == 0 and prec == 0) or prec < 0 or rec < 0 or gran < 1:
return 0
return ((2 * rec * prec) / (rec + prec)) / math.log(1 + gran, 2) | 48,132 |
def do_eject_replica_source(cs, args):
"""Ejects a replica source from its set."""
instance = _find_instance(cs, args.instance)
cs.instances.eject_replica_source(instance) | 48,133 |
def continuum(spec,bin=50,perc=60,norder=4):
""" Derive the continuum of a spectrum."""
nx = len(spec)
x = np.arange(nx)
# Loop over bins and find the maximum
nbins = nx//bin
xbin1 = np.zeros(nbins,float)
ybin1 = np.zeros(nbins,float)
for i in range(nbins):
xbin1[i] = np.mean(x[i... | 48,134 |
def train(GAN, G, D, X_train, Y_train, epochs=(args.epochs or 20), n_samples=570, batch_size=(args.batch_size or 8)):
"""
Entrenamiento adversario
"""
d_loss = []
g_loss = []
epochs_range = range(epochs)
for epoch in epochs_range:
batches = range(int(n_samples/batch_size))
fo... | 48,135 |
async def _async_setup_entities(hass, config_entry, async_add_entities,
discovery_infos):
"""Set up the ZHA locks."""
entities = []
for discovery_info in discovery_infos:
entities.append(ZhaDoorLock(**discovery_info))
async_add_entities(entities, update_before_ad... | 48,136 |
def mean_IoU(Y_true, Y_pred):
"""
Calculate the mean IoU score between two lists of labeled masks.
:param Y_true: a list of labeled masks (numpy arrays) - the ground truth
:param Y_pred: a list labeled predicted masks (numpy arrays) for images with the original dimensions
:return: mean IoU score for... | 48,137 |
def get_matrix_header(filename):
"""
Returns the entries, rows, and cols of a matrix market file.
"""
with open(filename) as f:
entries = 0
rows = 0
cols = 0
for line in f.readlines():
if line.startswith('%'):
continue
line = line.s... | 48,138 |
def test_set_context_bad_input():
"""
check the set_context function with a wrong input type
"""
r=sheep_client.set_context(33)
assert(r["status_code"]==550) | 48,139 |
def get_slot_names(slotted_instance):
"""Get all slot names in a class with slots."""
# thanks: https://stackoverflow.com/a/6720815/782170
return slotted_instance.__slots__ | 48,140 |
def make_standard_fisher_regularizer(make_logits, scope, should_regularize,
perturbation, differentiate_probability):
"""Creates per-example logits and the per-example standard Fisher-Rao norm.
This function assumes the model of a categorical distribution generated by a
softm... | 48,141 |
def objective(y_objective, sim_param, curve_param):
"""
Calculates the objective function (RMS-VIF) given the control point y-values of a given particle
:param y_objective: control point y-values of the particle
:param sim_param: Instance of sim_param
:param curve_param: Instance of curve_param
... | 48,142 |
def form_poisson_equation_impl(height, width, alpha, normals, depth_weight, depth):
"""
Creates a Poisson equation given the normals and depth at every pixel in image.
The solution to Poisson equation is the estimated depth.
When the mode, is 'depth' in 'combine.py', the equation should return the a... | 48,143 |
def shortest_first_name(names):
"""Returns the shortest first name (str)"""
names = dedup_and_title_case_names(names)
name_dict = []
for i in names:
i = i.split()
name_dict.append({'name':i[0], 'surname': i[1]})
short_name_sort = sorted(name_dict, key=lambda k: len(k['name']))
re... | 48,144 |
def timezone_validator(self, response):
"""Match timezone code in libraries/timezone.
Arguments
---------
response: "String containing current answer"
Raises
------
ValidationError: "Display a short description with available formats"
Returns
-------
boolean: True
... | 48,145 |
def reset_clb_srv(req):
"""
Service when reset of state planner
:param req:
:return:
"""
global reset_pose, pose_msgs , goal_sub, global_offset
rospy.loginfo_once("reset pose")
resp = TriggerResponse()
resp.success = True
resp.message = "Reset pose: True"
reset_pose = pose... | 48,146 |
def Calcola():
"""Calcolate point of task!"""
esci=False
while esci is False:
try:
check=False
while check is False:
DeadLine=input("inserisci la deadline in giorni ")
try:
DeadLine = int(DeadLine)
... | 48,147 |
def disabled(name):
"""
Ensure an Apache module is disabled.
.. versionadded:: 2016.3.0
name
Name of the Apache module
"""
ret = {"name": name, "result": True, "comment": "", "changes": {}}
is_enabled = __salt__["apache.check_mod_enabled"](name)
if is_enabled:
if __opt... | 48,148 |
def parse_settings(track_data, track_settings, line):
"""Loop through and parse the settings used in the rip."""
for setting, reg in track_settings.items():
result = reg.match(line)
if result:
track_data[setting] = result.group(1) | 48,149 |
def get_stops_in_polygon(feed, polygon, geo_stops=None):
"""
Return the slice of ``feed.stops`` that contains all stops that lie
within the given Shapely Polygon object that is specified in
WGS84 coordinates.
Parameters
----------
feed : Feed
polygon : Shapely Polygon
Specified ... | 48,150 |
def highlight_loops(view):
"""Takes a view, calculates its dominator tree, and highlights its loops."""
if len(view.graph.nodes) == 0:
MessageBox.showError(None, "Can not create dominator tree of empty views")
return
nodeListArray = GraphAlgorithm... | 48,151 |
def define_stkvar(*args):
"""
define_stkvar(pfn, name, off, flags, ti, nbytes) -> bool
Define/redefine a stack variable.
@param pfn: pointer to function (C++: func_t *)
@param name: variable name, NULL means autogenerate a name (C++: const
char *)
@param off: offset of the stack variabl... | 48,152 |
def spherical_polar_area(r, lon, lat):
"""Calculates the area bounding an array of latitude and longitude points.
Parameters
----------
r : float
Radius of sphere.
lon : 1d array
Longitude points. [Degrees]
lat : 1d array
Longitude points. [Degrees]
Returns
----... | 48,153 |
def greetings():
"""
This is greeting function
"""
print("hello world") | 48,154 |
def row_plays(hand, row):
"""Return the set of legal plays in the specified row.
A row play is a (start, 'WORD') pair,
"""
results = set()
# for each anchor and for each legal prefix, add all legal suffixes and save any valid words in results
for (i, square) in enumerate(row[1: -1], start=1):
... | 48,155 |
def test_apply_group(client):
"""test group applying works correctly
target_url: /lotteries/<id> [POST]
"""
idx = 1
user = test_user
members = [test_user1['secret_id'],
test_user2['secret_id'],
test_user3['secret_id']
]
with client.application... | 48,156 |
def nearest_pillar(grid, xy, ref_k0 = 0, kp = 0):
"""Returns the (j0, i0) indices of the primary pillar with point closest in x,y plane to point xy."""
# note: currently works with unmasked data and using primary pillars only
pe_i = grid.extent_kji[2] + 1
sum_dxy2 = grid.pillar_distances_sqr(xy, ref_k0... | 48,157 |
def read_state(file, statename):
""" read and select state from file
Args:
file (str): path to state shapefile
statename (str): name of state (i.e. California)
"""
all = gpd.read_file("../data/states.shp")
state = all[all['STATE_NAME'] == statename]
return state | 48,158 |
def get_random_state(seed):
"""
Get a random number from the whole range of large integer values.
"""
np.random.seed(seed)
return np.random.randint(MAX_INT) | 48,159 |
def test_add_poll_errors(game_id, game_round, moderator):
"""Test validation of new poll requests."""
new_poll_wrong_round = moderator.post('/game/%s/round/nosuchround/new_poll' % game_id)
assert new_poll_wrong_round.status_code == 404 | 48,160 |
def get_start_and_end_time(file_or_file_object):
"""
Returns the start and end time of a MiniSEED file or file-like object.
:type file_or_file_object: str or file
:param file_or_file_object: MiniSEED file name or open file-like object
containing a MiniSEED record.
:return: tuple (start time... | 48,161 |
def test_run_success() -> None:
"""Successful run produces expected results."""
today = datetime.date.today().strftime("%F\n")
expected = (0, "success", today, "")
assert run("date +%F") == expected | 48,162 |
def rmat2imat(nrows, ncols, nnz, rmat):
"""Converts rmat to imat iterator"""
for i, row in enumerate(rmat):
for j, v in row.iteritems():
yield i, j, v | 48,163 |
def edit_module(module_path):
""" Handle interactive edition of the CMake module. """
question = "Edit generated CMake module (highly recommended)?"
answer = qisys.interact.ask_yes_no(question, default=True)
if not answer:
return
qibuild_cfg = qibuild.config.QiBuildConfig()
qibuild_cfg.r... | 48,164 |
async def send_message(msg: str) -> Optional[str]:
"""
Send a message to the websocket and return the response
Args:
msg: The message to be sent
Returns:
The response message or None if it was not defined
"""
if not (WS and WS.open):
print('Reconnecting websocket')
... | 48,165 |
def _getname(storefile):
"""returns the filename"""
if storefile is None:
raise ValueError("This method cannot magically produce a filename when given None as input.")
if not isinstance(storefile, basestring):
if not hasattr(storefile, "name"):
storefilename = _getdummyname(store... | 48,166 |
def flow_lines(sol, nlines, time_length, scale=0.5):
"""
compute the flow lines of the solution
Parameters
----------
sol : :py:class:`Simulation<pylbm.simulation.Simulation>`
the solution given by pylbm
nlines : int (number of flow lines)
time_length : double (time during which we ... | 48,167 |
def minOperations(n):
""" finds min. operations to reach and string """
if type(n) != int or n <= 1:
return 0
res = 0
i = 2
while(i <= n + 1):
if (n % i == 0):
res += i
n /= i
else:
i += 1
return res | 48,168 |
def matrix2dictionary(matrix):
"""
convert matrix to dictionary of comparisons
"""
pw = {}
for line in matrix:
line = line.strip().split('\t')
if line[0].startswith('#'):
names = line[1:]
continue
a = line[0]
for i, pident in enumerate(line[1:]... | 48,169 |
def combine_fastq_output_files(files_to_combine, out_prefix, remove_temp_output):
""" Combines fastq output created by BMTagger/bowtie2 on multiple databases and
returns a list of output files. Also updates the log file with read counts for the
input and output files.
"""
# print out the read... | 48,170 |
def one_external_user_directory(self, node="clickhouse1"):
"""Check that we can restart ClickHouse server when one
LDAP external user directory is configured.
"""
self.context.node = self.context.cluster.node(node)
servers = {
"openldap1": {
"host": "openldap1",
"por... | 48,171 |
def deliver_dap():
"""
Endpoint for submissions only intended for DAP. POST request requires the submission JSON to be uploaded
as "submission" and the filename passed in the query parameters.
"""
logger.info('Processing DAP submission')
filename = request.args.get("filename")
meta = MetaWra... | 48,172 |
def api_run_delete(run_id):
"""Delete the given run and corresponding entities."""
data = current_app.config["data"] # type: DataStorage
RunFacade(data).delete_run(run_id)
return "DELETED run %s" % run_id | 48,173 |
def main(args):
"""Main entry point
"""
# loading genome accession file
acc_tbl = parse_acc_table(args['<accession_table>'])
# creating put directory (if needed)
if not os.path.isdir(args['-d']):
os.makedirs(args['-d'])
# query via efetch & download
logging.info('Do... | 48,174 |
def gfalternate_createdataandstatsdict(ldt_tower,data_tower,attr_tower,alternate_info):
"""
Purpose:
Creates the data_dict and stat_dict to hold data and statistics during gap filling from
alternate data sources.
Usage:
Side effects:
Called by:
Calls:
Author: PRI
Date: May 2015... | 48,175 |
def doGeneMapping(model):
"""
Function that maps enzymes and genes to reactions
This function works only if the GPR associations are defined
as follows: (g1 and g2 and g6) or ((g3 or g10) and g12)
- *model* Pysces model
- *GPRdict* dictionary with (iso)enzymes... | 48,176 |
def delay_to_midnight():
"""Calculates the delay between the current time and midnight"""
current_time = get_current_time()
delay = time_conversions.hhmm_to_seconds("24:00") - time_conversions.hhmm_to_seconds(current_time)
return delay | 48,177 |
def predict(model, imgs):
"""
Predict the labels of a set of images using the VGG16 model.
Args:
imgs (ndarray) : An array of N images (size: N x width x height x channels).
Returns:
preds (np.array) : Highest confidence value of the predictio... | 48,178 |
def main():
"""
主函数
"""
try_times = 5
module_path = path.dirname(__file__)#获取当前文件的绝对路径:包括包
filepath = module_path + '/password.txt'#拼接文件 获取最内层
# filepath = 'L2/password_3.0.txt'#获取到L2文件下的目录
file_tool = FileTool(filepath)
while try_times > 0:
password = input('请输入密码:')
... | 48,179 |
def get_last_query_records_count(connection: psycopg2_connection):
"""
Returns the number of rows that were loaded by the last COPY command run in the current session.
"""
# TODO: handle array extraction of rows num , handle NONE
result_set = redshift_query(connection, COPY_ROWS_COUNT_QUERY)
if ... | 48,180 |
def trading():
"""Распечатка всей аналитики, необходимой для управления портфелем"""
port = Portfolio(date=DATE,
cash=CASH,
positions=POSITIONS)
optimizer = Optimizer(port)
print(optimizer.portfolio)
print(optimizer.dividends_metrics)
print(optimizer.ret... | 48,181 |
def _endmsg(rd) -> str:
"""
Returns an end message with elapsed time
"""
msg = ""
s = ""
if rd.hours > 0:
if rd.hours > 1:
s = "s"
msg += colors.bold(str(rd.hours)) + " hour" + s + " "
s = ""
if rd.minutes > 0:
if rd.minutes > 1:
s = "s"
... | 48,182 |
def decompress(fcn):
"""Decorator that decompresses returned data.
libmagic is used to identify the MIME type of the data and the function
will keep decompressing until no supported compression format is identified.
"""
def wrapper(cls, raw=False, *args, **kw):
data = fcn(cls)
if r... | 48,183 |
def get_satellite_params(platform=None):
"""
Helper function to generate Landsat or Sentinel query information
for quick use during NRT cube creation or sync only.
Parameters
----------
platform: str
Name of a satellite platform, Landsat or Sentinel only.
params
"""
... | 48,184 |
def generate_random_token(length = 64):
""" Generates a random token of specified length.
"""
lrange = 16 ** length
hexval = "%0{}x".format(length)
return hexval % (random.randrange(lrange)) | 48,185 |
async def process_file(path, request_headers):
"""Serves a file when doing a GET request with a valid path."""
sever_root="/opt/vosk-server/websocket/web"
MIME_TYPES = {
"html": "text/html",
"js": "text/javascript",
"css": "text/css"
}
if "Upgrade" in request_headers:
... | 48,186 |
def permute_sse_metric(
name: str,
ref: np.ndarray,
est: np.ndarray,
compute_permutation: bool = False,
fs: Optional[int] = None) -> Union[float, Tuple[float, list]]:
"""
Computation of SiSNR/PESQ/STOI in permutation/non-permutation mode
Args:
name: metric nam... | 48,187 |
def get_tids_from_directory(audio_dir):
"""Get track IDs from the mp3s in a directory.
Parameters
----------
audio_dir : str
Path to the directory where the audio files are stored.
Returns
-------
A list of track IDs.
"""
tids = []
for _, dirnames, files in os.walk(... | 48,188 |
def coverage_qc_report(institute_id, case_name):
"""Display coverage and qc report."""
_, case_obj = institute_and_case(store, institute_id, case_name)
data = controllers.multiqc(store, institute_id, case_name)
if data["case"].get("coverage_qc_report") is None:
return abort(404)
coverage_qc... | 48,189 |
def get(name, decode=True):
"""
Get a resource from the trimesh/resources folder.
Parameters
-------------
name : str
File path relative to `trimesh/resources`
decode : bool
Whether or not to decode result as UTF-8
Returns
-------------
resource : str or bytes
Fil... | 48,190 |
def test_if() -> None:
"""if-elif-else."""
PositiveOrNegative = Literal[-1, 0, 1]
def positive_negative(number: int) -> PositiveOrNegative:
"""Return -1 for negative numbers, 1 for positive numbers, and 0 for 0."""
result: PositiveOrNegative
if number < 0:
result = -1
... | 48,191 |
def ba2str(ba):
"""Convert Bluetooth address to string"""
string = []
for b in ba.b:
string.append('{:02X}'.format(b))
string.reverse()
return ':'.join(string).upper() | 48,192 |
def calc_variance(img, omit=[]):
"""
calculate variance of pixel values in image
:param img: 2D array of pixel values
:param omit: pixel values to omit from calculation
:return: variance
"""
import numpy as np
from accessory import get_iterable
if np.ndim(img) > 2:
msg = 'E... | 48,193 |
def delete_user(client: Client, user_id: str) -> bool:
"""Deletes disabled user account via the `/users/{user_id}` endpoint.
:param client: Client object
:param user_id: The ID of the user account
:return: `True` if succeeded, `False` otherwise
"""
params = {'version': get_user_info(client, use... | 48,194 |
def get_token(corp_id: str, corp_secret: str):
"""获取access_token
https://open.work.weixin.qq.com/api/doc/90000/90135/91039
"""
req = requests.get(
f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'
)
return req.json().get('access_token') | 48,195 |
def GrantCharacterToUser(request, callback, customData = None, extraHeaders = None):
"""
Grants the specified character type to the user. CharacterIds are not globally unique; characterId must be evaluated
with the parent PlayFabId to guarantee uniqueness.
https://docs.microsoft.com/rest/api/playfab/ser... | 48,196 |
def _update_run_op(beta1, beta2, eps, global_step, lr, weight_decay, param, m, v, gradient, decay_flag, optim_filter):
"""
Update parameters.
Args:
beta1 (Tensor): The exponential decay rate for the 1st moment estimations. Should be in range (0.0, 1.0).
beta2 (Tensor): The exponential decay... | 48,197 |
def make_initial_ledger(toodir=None):
"""Set up the initial ToO ledger with one ersatz observation.
Parameters
----------
toodir : :class:`str`, optional, defaults to ``None``
The directory to treat as the Targets of Opportunity I/O directory.
If ``None`` then look up from the $TOO_DIR ... | 48,198 |
def encrypt_caesar(plaintext):
"""Encrypt plaintext using a Caesar cipher.
Add more implementation details here.
"""
raise NotImplementedError | 48,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.