content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def judge_1d100_with_6_ver(target: int, dice: int):
"""
Judge 1d100 dice result, and return text and color for message.
Result is critical, success, failure or fumble.
Arguments:
target {int} -- target value (ex. skill value)
dice {int} -- dice value
Returns:
message {string}... | 14,000 |
def get_normals(self, indices=None, loc="center"):
"""Return the array of the normals coordinates.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
loc : str
localization of the normals ("center" or "point")
... | 14,001 |
def string_to_weld_literal(s):
"""
Converts a string to a UTF-8 encoded Weld literal byte-vector.
Examples
--------
>>> string_to_weld_literal('hello')
'[104c,101c,108c,108c,111c]'
"""
return "[" + ",".join([str(b) + 'c' for b in list(s.encode('utf-8'))]) + "]" | 14,002 |
def verify_model_licensed(class_name : str, model_path:str):
"""
Load a licensed model from HDD
"""
try :
m = eval(class_name).load(model_path)
return m
except:
print(f"Could not load Annotator class={class_name} located in {model_path}. Try updaing spark-nlp-jsl") | 14,003 |
def examine_api(api):
"""Find all style issues in the given parsed API."""
global failures
failures = {}
for key in sorted(api.keys()):
examine_clazz(api[key])
return failures | 14,004 |
def enable_logging_app_factory(log_file: Path, level) -> logging.Logger:
"""
Enable logging for the system.
:param level: Logging Level
:param log_file: Log File path
:return:
"""
from logging.handlers import RotatingFileHandler
import sys
logger = logging.getLogger(LOGGER)
... | 14,005 |
def launch():
""" Initialize the module. """
return BinCounterWorker(BinCounter, PT_STATS_RESPONSE, STATS_RESPONSE) | 14,006 |
def make_map(source):
"""Creates a Bokeh figure displaying the source data on a map
Args:
source: A GeoJSONDataSource object containing bike data
Returns: A Bokeh figure with a map displaying the data
"""
tile_provider = get_provider(Vendors.STAMEN_TERRAIN_RETINA)
TOOLTIPS = [
... | 14,007 |
def main(count):
"""メイン処理
"""
fd_7seg, speaker = init()
print('app_a1 start')
speaker.play(MELODY_LIST[0])
count_down(fd_7seg, count)
speaker.play(MELODY_LIST[1])
print('app_a1 stop') | 14,008 |
def noise_graph_update(graph: ig.Graph, noise_csv_dir: str, log: Logger) -> None:
"""Updates attributes noises and noise_source to graph.
"""
noise_csvs = os.listdir(noise_csv_dir)
for csv_file in noise_csvs:
edge_noises = pd.read_csv(noise_csv_dir + csv_file)
edge_noises[E.noise_sourc... | 14,009 |
def remove(packages):
"""Removes package(s) using apt.
:param packages:
"""
sudo('apt-get -y remove %s' % packages) | 14,010 |
def save_all_pages(pages, root='.'):
"""Save picture references in pages on the form:
pages = {
urn1 : [page1, page2, ..., pageN],
urn2: [page1, ..., pageM]},
...
urnK: [page1, ..., pageL]
}
Each page reference is a URL.
"""
# In case urn is an actual URN, ... | 14,011 |
def rotate_images(images, rot90_scalars=(0, 1, 2, 3)):
"""Return the input image and its 90, 180, and 270 degree rotations."""
images_rotated = [
images, # 0 degree
tf.image.flip_up_down(tf.image.transpose_image(images)), # 90 degrees
tf.image.flip_left_right(tf.image.flip_up_down(images)), # 1... | 14,012 |
def import_archive(
ctx, archives, webpages, extras_mode_existing, extras_mode_new, comment_mode, include_authinfos, migration,
batch_size, import_group, group, test_run
):
"""Import data from an AiiDA archive file.
The archive can be specified by its relative or absolute file path, or its HTTP URL.
... | 14,013 |
def csv(args:[str])->str:
"""create a string of comma-separated values"""
return ','.join(args) | 14,014 |
def _update_class(oldclass, newclass):
"""Update a class object."""
# XXX What about __slots__?
olddict = oldclass.__dict__
newdict = newclass.__dict__
# PDF changed to remove use of set as not in Jython 2.2
for name in olddict.keys():
if name not in newdict:
delattr(oldclass... | 14,015 |
def update_signature():
"""Create and update signature in gmail.
Returns:Draft object, including updated signature.
Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity
for guides on implementing OAuth2 for the application.
"""
... | 14,016 |
def generate_block(constraints, p, rng=None):
"""Generated a balanced set of trials, might be only part of a run."""
if rng is None:
rng = np.random.RandomState()
n_trials = constraints.trials_per_run
# --- Assign trial components
# Assign the target to a side
gen_dist = np.repeat([0... | 14,017 |
def mean_by_weekday(day, val):
"""
Returns a list that contain weekday, mean of beginning and end of presence.
"""
return [day_abbr[day], mean(val['start']), mean(val['end'])] | 14,018 |
def parse_metrics(match, key):
"""Gets the metrics out of the parsed logger stream"""
elements = match.split(' ')[1:]
elements = filter(lambda x: len(x) > 2, elements)
elements = [float(e) for e in elements]
metrics = dict(zip(['key', 'precision', 'recall', 'f1'], [key] + elements))
return m... | 14,019 |
def minecraftify(clip: vs.VideoNode, div: float = 64.0, mod: int | None = None) -> vs.VideoNode:
"""
Function that transforms your clip into a Minecraft.
Idea from Meme-Maji's Kobayashi memery (love you varde).
:param clip: Input clip
:param div: How much to divide the clip's resolution with... | 14,020 |
def keyframeRegionTrackCtx(q=1,e=1,ex=1,ch=1,i1="string",i2="string",i3="string",n="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/keyframeRegionTrackCtx.html
-----------------------------------------
keyframeRegionTrackCtx is undoable, queryable, and editable.
This com... | 14,021 |
def processGOTerm(goTerm):
"""
In an object representing a GO term, replace single-element lists with
their only member.
Returns the modified object as a dictionary.
"""
ret = dict(goTerm) #Input is a defaultdict, might express unexpected behaviour
for key, value in ret.items():
if l... | 14,022 |
def searchxapian_show(request):
""" zeigt den Inhalt eines Dokumentes """
SORT_BY = { -1: _(u'Relevanz'),
0: _(u'URL'),
1: _(u'Überschrift/Titel'),
2: _(u'Datum der letzten Änderung') }
if request.path.find('index.html') < 0:
my_path = request.path.replace('sear... | 14,023 |
def html2plaintext(html, body_id=None, encoding='utf-8'):
""" From an HTML text, convert the HTML to plain text.
If @param body_id is provided then this is the tag where the
body (not necessarily <body>) starts.
"""
## (c) Fry-IT, www.fry-it.com, 2007
## <peter@fry-it.com>
## download here: ... | 14,024 |
def _create_regularization_of_grad(param, grad, regularization=None):
""" Create and add backward regularization Operators
Function helper of append_regularization_ops.
"""
# If no gradient or no regularization is specified, then we don't need to do anything
if grad is None or (param.regularizer i... | 14,025 |
def MooreSpace(q):
"""
Triangulation of the mod `q` Moore space.
INPUT:
- ``q`` -0 integer, at least 2
This is a simplicial complex with simplices of dimension 0, 1,
and 2, such that its reduced homology is isomorphic to
`\\ZZ/q\\ZZ` in dimension 1, zero otherwise.
If `q=2`, this is... | 14,026 |
def show(tournament_name, params=[], filter_response=True):
"""Retrieve a single tournament record by `tournament name`"""
utils._validate_query_params(params=params, valid_params=VALID_PARAMS, route_type='tournament')
uri = TOURNAMENT_PREFIX + tournament_name
response = api.get(uri, params)
if fi... | 14,027 |
def auto_run_api_pk(**kwargs):
"""run api by pk and config
"""
id = kwargs['id']
env = kwargs['config']
config_name = 'rig_prod' if env == 1 else 'rig_test'
api = models.API.objects.get(id=id)
config = eval(models.Config.objects.get(name=config_name, project=api.project).body)
te... | 14,028 |
def stairway():
"""This function plays Stairway To Heaven.
Msg:
Playing Stairway...
"""
raise Exception("DENIED") | 14,029 |
def create(arxiv_id: ArXivID,
arxiv_ver: int,
resource_type: str,
resource_id: str,
description: str,
creator: Optional[str]) -> Relation:
"""
Create a new relation for an e-print.
Parameters
----------
arxiv_id: ArXivID
The arXiv ID of... | 14,030 |
def cli(ctx):
"""list modify create delete addtovolumeaccessgroup removefromvolumeaccessgroup """ | 14,031 |
def p_contain_resist(D, t, f_y, f_u=None):
"""Pressure containment resistance in accordance with DNVGL-ST-F101.
(press_contain_resis)
Reference:
DNVGL-ST-F101 (2017-12)
sec:5.4.2.2 eq:5.8 p:94 $p_{b}(t)$
"""
if f_u is None:
f_cb = f_y
else:
f_cb = np.minimum(f_y, ... | 14,032 |
def test_pvector_field_default_non_optional():
"""
By default ``pvector_field`` is non-optional, i.e. does not allow
``None``.
"""
class Record(PRecord):
value = pvector_field(int)
with pytest.raises(TypeError):
Record(value=None) | 14,033 |
def revalue(request):
"""其它设备参数修改"""
value = request.GET.get('value')
name = request.GET.get('name')
others = Machines().filter_machines(OtherMachineInfo, pk=request.GET.get('dID'))[0]
if name == 'remark':
others.remark = value
elif name == 'machine_name':
others.machine_name = v... | 14,034 |
def indieauth_endpoint():
""" IndieAuth token endpoint """
import authl.handlers.indieauth
if 'me' in flask.request.args:
# A ticket request is being made
me_url = flask.request.args['me']
try:
endpoint, _ = authl.handlers.indieauth.find_endpoint(me_url,
... | 14,035 |
def policy_simulation_c(model,var,ages):
""" policy simulation for couples"""
if var == 'd':
return {'hs': lifecycle_c(model,var=var,MA=[0],ST_w=[1,3],ages=ages,calc='sum')['y'][0] +
lifecycle_c(model,var=var,MA=[1],ST_h=[1,3],ages=ages,calc='sum')['y'][0],
... | 14,036 |
def emit_obj_db_entry(target, source, env):
"""Emitter for object files. We add each object file
built into a global variable for later use"""
for t in target:
if str(t) is None:
continue
OBJ_DB.append(t)
return target, source | 14,037 |
def listtimes(list, c):
"""multiplies the elements in the list by the given scalar value c"""
ret = []
for i in range(0, len(list)):
ret.extend([list[i]]*c);
return ret; | 14,038 |
def main(): # pragma: no cover
"""
Creates an arm using the NLinkArm class and uses its inverse kinematics
to move it to the desired position.
"""
q_now = np.array([0, 0, 0, 0, 0, 0]) # to np.array([0, 0, 0, np.pi*2/3, np.pi*2/3, np.pi*2/3])
goal_pos = [0.015457, 0.057684, 0.269762] # from... | 14,039 |
def get(request):
"""Given a Request, return a Resource object (with caching).
We need the request because it carries media_type_default.
"""
# XXX This is not thread-safe. It used to be, but then I simplified it
# when I switched to diesel. Now that we have multiple engines, some of
# which ... | 14,040 |
def split_audio_ixs(n_samples, rate=STEP_SIZE_EM, min_coverage=0.75):
"""
Create audio,mel slice indices for the audio clip
Args:
Returns:
"""
assert 0 < min_coverage <= 1
# Compute how many frames separate two partial utterances
samples_per_frame = int((SAMPLING_RATE * WINDOW_STEP_... | 14,041 |
def new(w: int, h: int, fmt: str, bg: int) -> 'Image':
"""
Creates new image by given size and format
and fills it with bg color
"""
if fmt not in ('RGB', 'RGBA', 'L', 'LA'):
raise ValueError('invalid format')
c = len(fmt)
image = Image()
image.im = _new_image(w, h, c)
lib.im... | 14,042 |
def df_to_s3(df : pd.DataFrame, aws_access_key_id : str, region_name : str, aws_secret_access_key : str, bucket_name : str, upload_name : str) -> None:
"""Storing on the cloud made easy. All that is required is an s3 bucket that is open to the local IP address. For more information about setting up an AWS s3 bucket... | 14,043 |
def eval_f(f, xs):
"""Takes a function f = f(x) and a list xs of values that should be used as arguments for f.
The function eval_f should apply the function f subsequently to every value x in xs, and
return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2,..., xn] the
functi... | 14,044 |
def cie94_loss(x1: Tensor, x2: Tensor, squared: bool = False, **kwargs) -> Tensor:
"""
Computes the L2-norm over all pixels of the CIEDE2000 Color-Difference for two RGB inputs.
Parameters
----------
x1 : Tensor:
First input.
x2 : Tensor:
Second input (of size matching x1).
... | 14,045 |
def get_current_user_id() -> str:
"""
This functions gets the id of the current user that is signed in to the Azure CLI.
In order to get this information, it looks like there are two different services,
"Microsoft Graph" (developer.microsoft.com/graph) and "Azure AD Graph"
(graph.windows.net), the ... | 14,046 |
def scale_labels(subject_labels):
"""Saves two lines of code by wrapping up the fitting and transform methods of the LabelEncoder
Parameters
:param subject_labels: ndarray
Label array to be scaled
:return: ndarray
Scaled label array
"""
encoder = preprocessing.LabelEncoder()
... | 14,047 |
def _get_basemap(grid_metadata_dict):
"""Creates basemap.
M = number of rows in grid
M = number of columns in grid
:param grid_metadata_dict: Dictionary created by
`grids.create_equidistant_grid`.
:return: basemap_object: Basemap handle (instance of
`mpl_toolkits.basemap.Basemap`).... | 14,048 |
def load_holes(observatory: str):
"""Loads a list holes to ``targetdb.hole``."""
targetdb.database.become_admin()
observatory_pk = targetdb.Observatory.get(label=observatory).pk
row_start = 13
row_end = -13
min_cols = 14
holes = []
for row in range(row_start, row_end - 1, -1):
... | 14,049 |
def test_true_phase_preservation(chunk):
"""Test if dft is (phase-) preserved when signal is at same place but coords range is changed"""
x = np.arange(-15, 15)
y = np.random.rand(len(x))
N1 = np.random.randint(30) + 5
N2 = np.random.randint(30) + 5
l = np.arange(-N1, 0) + np.min(x)
r = np.... | 14,050 |
def unary_math_intr(fn, intrcode):
"""
Implement the math function *fn* using the LLVM intrinsic *intrcode*.
"""
@lower(fn, types.Float)
def float_impl(context, builder, sig, args):
res = call_fp_intrinsic(builder, intrcode, args)
return impl_ret_untracked(context, builder, sig.retur... | 14,051 |
def is_is_int(a):
"""Return `True` if `a` is an expression of the form IsInt(b).
>>> x = Real('x')
>>> is_is_int(IsInt(x))
True
>>> is_is_int(x)
False
"""
return is_app_of(a, Kind.IS_INTEGER) | 14,052 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 14,053 |
def normalize_channel_wise(tensor: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
"""Normalizes given tensor channel-wise
Parameters
----------
tensor: torch.Tensor
Tensor to be normalized
mean: torch.tensor
Mean to be subtracted
std: torch.Tensor
... | 14,054 |
def load_images(shot_paths):
"""
images = {
shot1: {
frame_id1: PIL image1,
...
},
...
}
"""
images = list(tqdm(map(load_image, shot_paths), total=len(shot_paths), desc='loading images'))
images = {k: v for k, v in images}
return images | 14,055 |
def rmSingles(fluxcomponent, targetstring='target'):
"""
Filter out targets in fluxcomponent that have only one ALMA source.
"""
nindiv = len(fluxcomponent)
flagger = numpy.zeros(nindiv)
for icomp in range(nindiv):
target = fluxcomponent[targetstring][icomp]
match = fluxcom... | 14,056 |
def discover_guids(file_path, keys):
"""
"""
# Now we revise the files
if isinstance(file_path, list):
discovered_files = file_path
else:
discovered_files = [os.path.join(file_path, f) for f in os.listdir(file_path)]
known_guids = set()
for f in discovered_files:
dir... | 14,057 |
def gray():
"""Convert image to gray scale."""
form = ImageForm(meta={'csrf': False})
current_app.logger.debug(f"request: {request.form}")
if form.validate():
service_info = cv_services["gray"]
json_format = request.args.get("json", False)
# Image Processing
image = servi... | 14,058 |
def all_examples(
ctx: typer.Context,
path_out: str = typer.Argument("./tmp", help="Path to example output directory."),
):
"""Generate all examples."""
output_path_string = validate_output_path(path_out)
output_path = Path(output_path_string) / Path("examples")
typer.echo(f"Examples will be sav... | 14,059 |
def compute_accuracy(outputs, targets, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = targets.size(0)
_, preds = outputs.topk(maxk, 1, True, True)
preds = preds.t()
corre... | 14,060 |
def init_logger():
"""Initialize and configure a logger for the application.
"""
# create logger
with open("./function/logging.json", "r", encoding="utf-8") as fd:
logging.config.dictConfig(json.load(fd))
# reduce log level for modules
logging.captureWarnings(True)
requests.packages.... | 14,061 |
def unpack_text_io_wrapper(fp, encoding):
"""
If *fp* is a #io.TextIOWrapper object, this function returns the underlying
binary stream and the encoding of the IO-wrapper object. If *encoding* is not
None and does not match with the encoding specified in the IO-wrapper, a
#RuntimeError is raised.
"""
if ... | 14,062 |
def _reset_graphmode_for_inplaceassign(graph_list, graph_mode):
"""Operator with InplaceAssign should always be composite op"""
for i, g in enumerate(graph_list):
if any((op['name'] == 'InplaceAssign' for op in g['op_desc'])):
graph_mode[i] = 'composite' | 14,063 |
def main():
"""
Fill in this function.
"""
print("Hello World.") | 14,064 |
def dummy_blob(size_arr=(9, 9, 9), pixdim=(1, 1, 1), coordvox=None):
"""
Create an image with a non-null voxels at coordinates specified by coordvox.
:param size_arr:
:param pixdim:
:param coordvox: If None: will create a single voxel in the middle of the FOV.
If tuple: (x,y,z): Create single ... | 14,065 |
def main():
"""
example:
"a big dog fell down the stairs ." vs. "a big dog fallen down the stairs ."
"""
vocab = get_vocab_words()
modifiers = ['over there', 'some time ago', 'this morning', 'at home', 'last night']
names_ = (configs.Dirs.legal_words / 'names.txt').open().read().split()
... | 14,066 |
def poly_edges(P, T):
"""
Returns the ordered edges from the given polygons
Parameters
----------
P : Tensor
a (N, D,) points set tensor
T : LongTensor
a (M, T,) topology tensor
Returns
-------
tuple
a tuple containing the edges of the given polygons
"""... | 14,067 |
def make_list(v):
"""
If the object is not a list already, it converts it to one
Examples:
[1, 2, 3] -> [1, 2, 3]
[1] -> [1]
1 -> [1]
"""
if not jsoncfg.node_is_array(v):
if jsoncfg.node_is_scalar(v):
location = jsoncfg.node_location(v)
line = location.lin... | 14,068 |
def data_gen(V, batch, nbatches, max_words_in_sentence):
"""
Generate random data for a src-tgt copy task.
# 5: # of sentences per batch == batch(2nd arg)
# 4: # of words in each sentence
# 7: size of word dictionary
np.random.randint(low=1, high=7, size=(5, 4)) # 5 by 4 matrix
>>> gen = ... | 14,069 |
def score_game(game_core):
"""Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число"""
count_ls = []
np.random.seed(1) # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим!
random_array = np.random.randint(1, 101, 1000)
for number in random_array:
count_ls.appen... | 14,070 |
def add_plot(
lon, lat, kind=None, props=None, ax=None, break_on_change=False, transform=identity
):
"""Add a plot with different props for different 'kind' values to an existing map
Parameters
----------
lon : sequence of float
lat : sequence of float
kind : sequence of hashable, optional
... | 14,071 |
def polyExtrudeFacet(*args, **kwargs):
"""
Extrude faces. Faces can be extruded separately or together, and manipulations can be performed either in world or
object space.
Flags:
- attraction : att (float) [create,query,edit]
This flag specifies the attraction,... | 14,072 |
def create_testcase_list_file(testcase_file_paths, input_directory):
"""Store list of fuzzed testcases from fuzzer in a bot specific
testcase list file."""
if not testcase_file_paths:
logs.log_error('No testcases found, skipping list file.')
return
bot_testcases_file_path = utils.get_bot_testcases_file... | 14,073 |
def led_flash(e, t):
"""flash the led continously"""
while not e.isSet():
time.sleep(t)
GPIO.output(16, GPIO.LOW)
time.sleep(t)
GPIO.output(16, GPIO.HIGH) | 14,074 |
def test_lsp_code_action2() -> None:
"""Tests edge case for code actions.
Identified in: https://github.com/pappasam/jedi-language-server/issues/96
"""
with session.LspSession() as ls_session:
ls_session.initialize()
uri = as_uri((REFACTOR_TEST_ROOT / "code_action_test2.py"))
a... | 14,075 |
def can_review_faults(user):
"""
users can review faults if one of the the following applies:
a) No fault review groups exist and they have can_review permissions
b) Fault review groups exist, they are a member of one, and they have
review permissions
"""
can_review = user.h... | 14,076 |
def test_line_insert_start(tempfile_name, get_body):
"""
Test for file.line for insertion at the beginning of the file
:return:
"""
cfg_content = "everything: fantastic"
file_content = os.linesep.join(
["file_roots:", " base:", " - /srv/salt", " - /srv/sugar"]
)
file_modif... | 14,077 |
def create_freshservice_object(obj_type, data):
"""Use the Freshservice v2 API to create an object.
Accepts an object name (string) and a dict of key values.
"""
url = '{}/{}'.format(settings.FRESHSERVICE_ENDPOINT, obj_type)
resp = requests.post(url, auth=FRESHSERVICE_AUTH, json=data)
return res... | 14,078 |
def print_begin(*args, sep=' ', end='\n', file=None, ret_value='') -> str:
"""Print the function name and start."""
print(_prefix('begin'), *args, sep=sep, end=end, file=file, flush=True)
return ret_value | 14,079 |
def scale_bounding_box(bounding_box,scale):
"""Scales bounding box coords (in dict from {x1,y1,x2,y2}) by x and y given by sclae in dict form {x,y}"""
scaled_bounding_box = {
"x1" : int(round(bounding_box["x1"]*scale["x"]))
,"y1" : int(round(bounding_box["y1"]*scale["y"]))
,"x2" : int(ro... | 14,080 |
def is_command(obj) -> bool:
"""
Return whether ``obj`` is a click command.
:param obj:
"""
return isinstance(obj, click.Command) | 14,081 |
def GetContigs(orthologs):
"""get map of contigs to orthologs.
An ortholog can be part of only one contig, but the same ortholog_id can
be part of several contigs.
"""
contigs = {}
for id, oo in orthologs.items():
for o in oo:
if o.contig not in contigs:
con... | 14,082 |
def _save_training_results(
mltk_model:MltkModel,
keras_model:KerasModel,
training_history,
logger: logging.Logger,
show:bool = False
) -> TrainingResults:
"""Save the training history as .json and .png"""
results = TrainingResults(mltk_model, keras_model, training_history)
metric, b... | 14,083 |
def creating_windows(alpha):
"""
This function draws the last lines for the program to fill the box
"""
#First Window
alpha.setpos(25,25)
alpha.pencolor("purple")
alpha.fillcolor("purple")
alpha.begin_fill()
alpha.pendown()
for x in range(4): #making square
alpha.forward(... | 14,084 |
def client(client, inp):
"""Client handler for module.
Args:
client: instance of PoetClient class
inp: command string sent from server
"""
# your code goes here
pass | 14,085 |
def set_backwards_pass(op, backwards):
"""
Returns new operation which behaves like `op` in the forward pass but
like `backwards` in the backwards pass.
"""
return backwards + tf.stop_gradient(op - backwards) | 14,086 |
def remove_hydrogens(list_of_lines):
"""
Removes hydrogen from the pdb file.
To add back the hydrogens, run the reduce program on the file.
"""
return (line for line in list_of_lines if line['element']!=" H") | 14,087 |
def crash_random_instance(org: str, space: str, appname: str, configuration: Configuration, count: int = 1):
"""
Crash one or more random application instances.
:param org: String; Cloud Foundry organization containing the application.
:param space: String; Cloud Foundry space containing the application... | 14,088 |
def test_lildhtm():
"""Test lildhtm.pft database lilacs"""
config.load(join('fixtures','lilacs.ini'))
current_path = join(os.getcwd(),'fixtures')
collection = pyisis.files.IsisCollection('fixtures',[current_path],config=config)
database = collection['lilacs']
expr = ''.join(open(jo... | 14,089 |
def spc_dict_from_spc_info(spc_info: dict, resonance: bool = True) -> dict:
"""
Generate a species dictionary from species info.
Args:
spc_info (dict): Species info contains the label and species geom info.
resonance (bool): Whether generate resonance geom in the species dictionary.
Re... | 14,090 |
def test_pos_invalid_input_4():
"""
Tests get_pos function for NLPFrame with wrong column specified
"""
initial_df = nlp.NLPFrame({'text_col' : ['Today is a beautiful Monday and I would love getting a coffee. However, startbucks is closed.','It has been an amazing day today!']}, index = [0,1], column =... | 14,091 |
def label_smooth_loss(log_prob, label, confidence=0.9):
"""
:param log_prob: log probability
:param label: one hot encoded
:param confidence: we replace one (in the one hot) with confidence. 0 <= confidence <= 1.
:return:
"""
N = log_prob.size(0)
C = log_prob.size(1)
smoothed_label =... | 14,092 |
def update(self, using=None, **kwargs):
"""
Updates specified attributes on the current instance.
"""
assert self.pk, "Cannot update an instance that has not yet been created."
using = using or router.db_for_write(self.__class__, instance=self)
for field in self._meta.fields:
if getatt... | 14,093 |
def differential_privacy_with_risk( dfg_freq, dfg_time, delta, precision, aggregate_type=AggregateType.SUM):
"""
This method adds the differential privacy to the DFG of both time and frequencies.
* It calculates the epsilon using the guessing advantage technique.
* It adds laplace noise to the D... | 14,094 |
def get_all_values(string: str) -> Iterable[int]:
"""Return all kinds of candidates, with ordering: Dec, Hex, Oct, Bin."""
if string.startswith('0x'):
return filter(bool, [parse_hex(string[2:])]) # type: ignore[list-item]
if string.startswith('0o'):
return filter(bool, [parse_oct(string[2:]... | 14,095 |
def svn_auth_get_simple_provider(*args):
"""svn_auth_get_simple_provider(apr_pool_t pool)"""
return _core.svn_auth_get_simple_provider(*args) | 14,096 |
def preferred_language():
""" It just returns first language from acceptable
"""
return acceptable_languages()[0] | 14,097 |
def get_frequencies(trial = 1):
"""
get frequency lists
"""
if trial =="run_fast_publish":
lb_targ, ub_targ, obs_hz = 340, 350, 10
elif trial == 1:
lb_targ, ub_targ, obs_hz = 210, 560, int(320 / 2)
elif trial == 2:
lb_targ, ub_targ, obs_hz = 340, 640, 280
elif trial == 3:
lb_... | 14,098 |
def load_csv(file_path: str = None, clean: bool = True) -> pd.DataFrame:
"""Load the dataset CSV file.
Args:
file_path (str, optional): Path to CSV file. Can be omitted, to load the default dataset. Defaults to None.
drop (list[str], optional): Optionally supply a list of column names to drop. ... | 14,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.