content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def settings_finish(update: Update, context: CallbackContext) -> int:
""" Settings finish"""
devotional_type = update.message.text
chat_id = update.effective_chat.id
update.message.reply_text(
text=YOUR_CHOICE.replace("$choice", devotional_type),
parse_mode=ParseMode.HTML
)
if ... | 60,100 |
def dataframe_to_thrift_struct(df, name, roffset, coffset, rows, cols, format):
"""
:type df: pandas.core.frame.DataFrame
:type name: str
:type coffset: int
:type roffset: int
:type rows: int
:type cols: int
:type format: str
"""
dim = len(df.axes)
num_rows = df.shape[0]
... | 60,101 |
def find_medoid(indir, pangenome_list):
"""
Finds the medoid of the groups of nucleotide sequences
Picks a best representative sequence for each species and puts the results into self.cluster
"""
# If we do need to update this
seqs_all = [] # ffn sequence objects for everything in the distance ... | 60,102 |
def collect_args(args: ast.arguments):
"""Collect function arguments."""
all_args = args.args + args.kwonlyargs
all_args += [args.vararg, args.kwarg]
return [arg for arg in all_args if arg is not None] | 60,103 |
def getalllabels():
"""Get a dictionary of label name -> SNES address."""
labeldatas = _getall(_asar.dll.asar_getalllabels)
return {x.name.decode(): x.location for x in labeldatas} | 60,104 |
def update_eval_path_integral(data_dir, top_n=5, n_traj=10000, atom_followed="C", init_spe=114,
tau=10.0, begin_t=0.0, end_t=1.0, species_path=False):
"""
update settings.json, primarily for evaluate path integral
"""
# there will always be a current setting
fn0 = os.pa... | 60,105 |
def jinja2_enviroment(**options):
"""jinja2环境"""
#创建环境
env = Environment(**options)
#返回环境对象
env.globals.update({
"static":staticfiles_storage.url, #获取静态文件的前缀
"url":reverse, #反向解析
})
#自定义语法 : static. {{static{'静态文件相对路径') }}
#return 对象
return env | 60,106 |
def get_route53_id(region, name, profile=None):
"""Retrieve the id of a route53 hosted zone.
Args:
region (str): The AWS region.
name (str): The name of the route53 hosted zone.
Basic Usage:
>>> import boto3
>>> route53 = boto3.client('route53', 'us-west-2')
>>> id =... | 60,107 |
def pushmarker(repo, key, old, new):
"""Push markers over pushkey"""
if not key.startswith('dump'):
repo.ui.warn(_('unknown key: %r') % key)
return 0
if old:
repo.ui.warn(_('unexpected old value for %r') % key)
return 0
data = base85.b85decode(new)
lock = repo.lock()
... | 60,108 |
def remove_images():
"""Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used"""
client = get_docker_client()
removed = _remove_dangling_images()
dusty_images = get_dusty_images()
all_images = client.images(all=True)
for image in all_images:
... | 60,109 |
def test() -> None:
"""
A basic test-case to verify that the model can fit some randomly generated data
:return: None
"""
# Constants
input_dim = 44
output_dim = 44
hidden_dim = 64
batch_size = 64
# Create model
model = FNNwithSoftmax(input_dim, output_dim, hidden_dim, num_... | 60,110 |
def get_types_and_functions(root):
"""Return a list of types and functions from a root element."""
types = root.findall('%stype' % namespace)
functions = root.findall('%sfunction' % namespace)
logger.debug(types)
logger.debug(functions)
if len(types) == 0 and len(functions) == 0:
logge... | 60,111 |
def create_version_localization(
version_id: str,
locale: str,
localization_attributes: VersionLocalizationAttributes,
access_token: AccessToken,
):
"""Creates a new app store version localization."""
return fetch(
method=FetchMethod.POST,
path=f"/appStoreVersionLocalizations",
... | 60,112 |
def clean_build():
"""Remove build directory and recreate empty"""
shutil.rmtree("site_build", ignore_errors=True)
build_dir = Path("site_build")
build_dir.mkdir(exist_ok=True)
return build_dir | 60,113 |
def test_validator_anyof_error(setup):
""" Test NumberRange validator
No set - Error situation.
Field hobby has an invalid selection.
"""
post = deepcopy(setup)
post.add(u'hobby', 'photography')
dynamic_form = WTFormsDynamicFields()
dynamic_form.add_field('hobby','Hobby', TextField)
... | 60,114 |
def print_markers(f):
"""A decorator that prints the invoked command
before and after the command.
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
command = ctx.info_name
assert command is not None
command_name = ctx.command_path
click_extensions.echo_with... | 60,115 |
def gpsapi():
"""(re)Generate and/or present API key."""
form = ApiForm(request.form)
hasapi = ApiKey.query.filter_by(user_id=current_user.get_id()).all()
# Handle regeneration of API key
if request.method == "POST":
if form.validate_on_submit():
apikey = strgen.StringGenerator("... | 60,116 |
def _date_index(config):
"""Returns a pandas.DatetimeIndex for the given config, based on the values of
the options daily, monthly, year, month, day, dayofyear, latest, all, and
median.
For a median config, the base index is a single leap year; otherwise, the
base index is a date index from the beg... | 60,117 |
def get_key(dotenv_path, key_to_get):
"""
Gets the value of a given key from the given .env
If the .env path given doesn't exist, fails
"""
key_to_get = str(key_to_get)
if not os.path.exists(dotenv_path):
warnings.warn("can't read %s - it doesn't exist." % dotenv_path)
return No... | 60,118 |
def secret_exponent_to_wif(secret_exp, compressed=True, is_test=False):
"""Convert a secret exponent (correspdong to a private key) to WIF format."""
d = private_byte_prefix(is_test) + to_bytes_32(secret_exp)
if compressed: d += b'\01'
return b2a_hashed_base58(d) | 60,119 |
def diag_set(X, new):
"""
Sets the diagonal of a square matrix X to new.
[Added 5/1/19]
"""
for i in range(X.shape[1]): X[i, i] = new[i] | 60,120 |
def create_host(ec2_conn, ipa_client, image_id, count, domain,
secgroup_ids, instance_type, subnet, disk,
instance_vars, role=None, instance_profile=None,
hostgroups=None, hostname=None, ip_address=None,
eni=None, key=None, tags=None, spot=False,
... | 60,121 |
def extractAll(fname, notwilight=True):
""" extra data on all exposures from surveysim output
no cosmics split adds 20% to margin
total BGS time: 2839 hours
total BGS minus twilight: 2372
assuming 7.5 deg^2 per field
assumiong 68% open-dome fraction
"""
total_hours = 2839
if notwi... | 60,122 |
def check_new_labels_var(self, labels_df):
"""Check the new annotations labels, then set the labels_df index"""
if labels_df is None or labels_df.empty:
return
labels_df.index = self.get_var_index()
if labels_df.index.name is None:
labels_df.index.name = "index"
# all labels must h... | 60,123 |
def ajax_delete_widget(request):
""" Delete single widget """
if request.is_ajax():
if request.method == 'POST':
widget_id = request.POST.get('widget_id', 0)
if widget_id:
delete_widget(widget_id)
return HttpResponse(simplejson.dumps({'status':'succes... | 60,124 |
async def post_pack_response(repo_path: Path, pack_type: str) -> Response:
"""
Make the response for handling exchange pack responses,
uses 'BODY_TIMEOUT' for a timeout of a request.
A matching route should be: '/<repo_name>.git/<pack_type>'.
:param repo_path: Path to the repo
:param p... | 60,125 |
def api_login_view(request):
"""
Login a user based on some credentials.
POST with HTTPS: args that correspond to credentials passed to the authentication backends.
"""
if request.method != 'POST':
return render_error(request, __ERROR_NOT_ALLOWED, 405)
if not request.is_secure() and not... | 60,126 |
def get_geocoder_normalized_addr(address, addr_keys=ADDRESS_KEYS):
# type: (Union[Mapping, str], Optional[Sequence]) -> dict
"""Get geocoder normalized address parsed to dict with addr_keys.
:param address: string or dict-like containing address data
:param addr_keys: optional list of address keys. sta... | 60,127 |
def clear_handlers():
"""Clears registered type handlers."""
_content_handlers.clear()
_content_types.clear() | 60,128 |
def _read_csv(filepath: str, kwargs: Dict) -> Union[List, Dict]:
"""See documentation of mpu.io.read."""
if "delimiter" not in kwargs:
kwargs["delimiter"] = ","
if "quotechar" not in kwargs:
kwargs["quotechar"] = '"'
if "skiprows" not in kwargs:
kwargs["skiprows"] = []
if isi... | 60,129 |
def bbox_iou(box1, box2, x1y1x2y2=True):
"""
计算IOU
"""
if not x1y1x2y2:
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box... | 60,130 |
def tsdb_query(query, profile):
"""Perform a query using the tsdb commandline program. The query
argument to this function is used as the value of the tsdb -query
argument and the profile argument to this function is used as the
value of the tsdb -home argument."""
env = dict(os.environ)
env['LC... | 60,131 |
def points_extraction(images, nx, ny):
"""
perform the extraction of object points and image points
:param images: list of images
:param nx: the number of inside corners in x
:param ny: the number of inside corners in y
:return: object points, image points and retvalues
"""
# Arrays to ... | 60,132 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem
when corresponding `Profile` object is updated
with new file.
"""
if not instance.pk:
return False
try:
old_avatar = Profile.objects.get(pk=instance.pk).avatar
except Profile... | 60,133 |
def get_user_id(username):
"""Convenience method to look up the id for a username."""
rv = User.query.filter_by(username=username).first()
return rv.user_id if rv else None | 60,134 |
def tweet(ctx, created_at, twtfile, text):
"""Append a new tweet to your twtxt file."""
text = expand_mentions(text)
tweet = Tweet(text, created_at) if created_at else Tweet(text)
pre_tweet_hook = ctx.obj["conf"].pre_tweet_hook
if pre_tweet_hook:
run_pre_tweet_hook(pre_tweet_hook, ctx.obj["... | 60,135 |
def clean_toc(toc: str) -> str:
"""Each line in `toc` has 6 unnecessary spaces, so get rid of them"""
lines = toc.splitlines()
return "\n".join(line[6:] for line in lines) | 60,136 |
def run():
"""Executes script"""
username, email, password = get_user_login()
account = login(username, email, password)
inbox = account.inbox
get_attachments(inbox) | 60,137 |
def separate_means_and_sigma(O: np.ndarray, D: int):
"""
Retreive means and sigma from the outputted O matrix of
emission probabilities
"""
flat_sigma = O[D:]
assert len(flat_sigma) == D*(D + 1) // 2
return O[:D], flat_sigma | 60,138 |
def pickle_load(file_path):
""" data = pickle_load(file_path)
Load data from a pickle dump file
inputs:
file_path: str, path of the pickle file
output:
data: python object
"""
with open(file_path, 'rb') as file_ptr:
data = pickle.load(file_ptr)
return data | 60,139 |
async def account_add(request : VueRequest):
"""
添加用户的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
username = request['username... | 60,140 |
def port_available(port):
"""
Check is port sent available currently.
:return: {Tuple}
"""
status = False
error = {}
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
try:
s.bind(('0.0.0.0', port))
status = True
except socket.error ... | 60,141 |
def doctest_PJContainer_cache_events():
"""PJContainer: _cache insert/delete with events
(regression: events missed freshly inserted objects)
>>> ppl = dm.root['people'] = container.PJContainer('person')
Set cache complete
>>> ppl.clear()
>>> ppl._cache_complete
True
INSERT
... | 60,142 |
def checkClientConnected(cli, nodeNames, clientName):
"""
Checks whether client connected to nodes.
If you do not know the moment when it exactly happens consider using
'waitClientConnected' instead
"""
printedMsgs = set()
stackName = cli.clients[clientName].stackName
expectedMsgs = {'... | 60,143 |
def vtk_points_to_polyline(vtk_points):
"""
creates a polyline, creating lines along point path
:param vtk_points:
:return:
"""
lines = vtk.vtkCellArray()
for k in range(vtk_points.GetNumberOfPoints() - 1):
line = vtk.vtkLine()
line.GetPointIds().SetId(0, k)
line.Ge... | 60,144 |
def getLayerThicknesses(vessel):
"""returns a dataframe with thicknesses of each layer along the whole vessel"""
thicknesses = []
columns = ['lay{}_{:04.1f}'.format(i, angle) for i, angle in enumerate(getAnglesFromVessel(vessel))]
for layerNumber in range(vessel.getNumberOfLayers()):
vesselLayer... | 60,145 |
def test_update_set_invalid_data(client, admin, minimal_oai_set, headers):
"""Update a set with invalid data.
Most cases are already handled in test_create_set_invalid_data
"""
client = admin.login(client)
s1 = _create_set(client, minimal_oai_set, headers, 201).json
s = minimal_oai_set.copy()
... | 60,146 |
def get_transcription_files_by_dataset(
dataset: str, transcription_folder: str
) -> List[str]:
"""return paths of transcriptions from the given data set and the path of all of transcriptions"""
train_set = get_data_list(f"splits/{dataset}")
transcription_train_set = list(
map(lambda path: path.... | 60,147 |
def versiontuple(v):
"""Return the version as a tuple for easy comparison."""
return tuple(int(x) for x in v.split(".")) | 60,148 |
def validate_aliases(aliases):
"""Checks that each alias remains unique when converted to a valid filename."""
return len(set(get_valid_filename(s) for s in aliases)) == len(aliases) | 60,149 |
def apps(app_id=None):
"""Returns marathon apps together with corresponding tasks
:param str app_id: application id
"""
marathon_addresses = _addresses()
return _apps(marathon_addresses, app_id) | 60,150 |
def find_checksum(s):
"""Accepts a manifest-style filename and returns the embedded
checksum string, or None if no such string could be found."""
m = re.search(r"\b([a-z0-9]{32})\b", s, flags=re.IGNORECASE)
md5 = m.group(1).lower() if m else None
return md5 | 60,151 |
def data_null_check(df):
"""Prints out nulls of dataframe into a nice data frame format"""
if type(df) == pd.core.frame.DataFrame:
return df.isnull().sum() | 60,152 |
def sum_up_nums(*nums):
"""(int or float) -> int or float
Adds up as many numbers(separate arguments) as the caller can supply.
Returns the sum of <*nums>
"""
cntr = 0 # Init sum zero
for num in nums:
cntr += num
return cntr | 60,153 |
def _generate_random_example_for_one_session_and_one_marker(
rng: np.random.Generator,
) -> Tuple[List[EventMetaData], List[int]]:
"""Generates a random marker extraction result for a single session and marker.
Args:
rng: a random number generator
Returns:
the event list representing th... | 60,154 |
def real_rowcol_in_hunk(hunk, relative_rowcol):
# type: (str, RowCol) -> Optional[RowCol]
"""Translate relative to absolute row, col pair"""
hunk_lines = split_hunk(hunk)
if not hunk_lines:
return None
row_in_hunk, col = relative_rowcol
# If the user is on the header line ('@@ ..') pre... | 60,155 |
def set_stubs(test):
"""Set the stubs."""
test.stub_out('nova.virt.vmwareapi.network_util.get_network_with_the_name',
fake.fake_get_network)
test.stub_out('nova.virt.vmwareapi.images.upload_image_stream_optimized',
fake.fake_upload_image)
test.stub_out('nova.virt.vmw... | 60,156 |
def load_mrs_rsrf_file( filename ):
"""
Reads RSRF parameters from binary FITS table.
"""
# Read the RSRF data from file
try:
hdulist = pyfits.open(filename)
fits_hdr_prim = hdulist[0].header
fits_hdr_ext = hdulist[1].header
#fitsdata = hdulist[1].data[0]
... | 60,157 |
def enable_logging(
name: str, level: Union[int, str] = logging.DEBUG) -> None:
"""Function enable_logging() enables the logging of the given module.
It enables the logging of the given module by setting the logging level to the lowest
value as possible. It may also get a level value explicitly.
:Args... | 60,158 |
def recipe(index):
"""
Return (GET) or delete (DELETE) one recipe
"""
try:
if request.method == 'GET':
return Response(
json.dumps(recipebook.recipes[index].to_json_dict()),
mimetype="application/json")
elif request.method == 'DELETE':
... | 60,159 |
def eval_numerical_gradient_blobs(f, inputs, output, h=1e-5):
"""
Compute numeric gradients for a function that operates on input
and output blobs.
We assume that f accepts several input blobs as arguments, followed by a blob
into which outputs will be written. For example, f might be called like this:
... | 60,160 |
def poly_half_gcdex(f, g, *symbols):
"""Half extended Euclidean algorithm.
Efficiently computes gcd(f, g) and one of the coefficients
in extended Euclidean algorithm. Formally, given univariate
polynomials f and g over an Euclidean domain, computes s
and h, such that h = gcd(f, g) and ... | 60,161 |
def test_QKTO_multicomponent_extrapolation_binary_mixing(load_database):
"""Test extrapolation into multi-component from only binary excess parameters"""
dbf = load_database()
PD = v.Species("PD")
RU = v.Species("RU")
TC = v.Species("TC")
MO = v.Species("MO")
mod = Model(dbf, ["PD", "RU", "... | 60,162 |
def find_message(file_content):
"""Implmentation for Part 1."""
point_system = LightPointSystem(_parse_entry(entry)
for entry in file_content)
total_area = point_system.get_area()
seconds = 0
while True:
point_system.step_forward()
new_area = poin... | 60,163 |
def save_expr_file(exprs, file_expr_path=bank_of_expressions_path):
"""
Save a set of expression in the stored expressions file
file_expr_path : the path to the file
exprs : the set of expressions
"""
expr_df = pd.DataFrame(exprs, columns = ["expr_col"])
expr_df.to_csv(file_expr_pa... | 60,164 |
def get_convert_rgb_channels(channels_info):
"""Get first available RGB(A) group from channels info.
## Examples
```
# Ideal situation
channels_info: {
"R": ...,
"G": ...,
"B": ...,
"A": ...
}
```
Result will be `("R", "G", "B", "A")`
```
# Not i... | 60,165 |
def create_choice(question, choice_text ):
"""
Creates a choice for question.
"""
return Choice.objects.create(question=question, choice_text=choice_text) | 60,166 |
def GenerateTests():
"""Generate all tests."""
filelist = []
ii = 0
for iTarget in range(len(_TARGETS)):
for iFilter in range(len(_FILTERS)):
for iFunc in range(len(_COMPARE_FUNCS)):
item = _TARGETS[iTarget] + '_' + _FILTERS[iFilter] + '_' + _COMPARE_FUNCS[iFunc]
filename = GenerateFil... | 60,167 |
def validate_product_quantity(product, quantity: int):
"""
Receives a ProductModel *product* and a integer *quantity*
Verifies if the quantity passed is valid
"""
avaliable = product.avaliable
if quantity <= 0 or quantity > avaliable:
raise ZoasError(INVALID_PRODUCT_QUANTITY) | 60,168 |
def get_expts(context, expts):
"""Takes an expts list and returns a space separated list of expts."""
return '"' + ' '.join([expt['name'] for expt in expts]) + '"' | 60,169 |
def trivial_dce(func):
"""Iteratively remove dead instructions, stopping when nothing
remains to remove.
"""
# An exercise for the reader: prove that this loop terminates.
while trivial_dce_pass(func):
pass | 60,170 |
def to_timestamp(obj: datetime) -> int:
"""
秒值
"""
return int(obj.timestamp()) | 60,171 |
def make_model(model_type, dataset, from_logits=False):
"""Builds a model.
XXX: from_logits=True is incompatible with expected gradient length.
"""
model = MODELS[model_type](dataset, to_proba=not from_logits)
loss = keras.losses.CategoricalCrossentropy(from_logits=from_logits)
# XXX doesn't st... | 60,172 |
def test_release_line_regex_matching(line, package, version):
"""
The regex can extract a well-formatted package and version
"""
match = re.search(RELEASE_LINE_PATTERN, line)
assert match is not None
assert match.group(1) == package
assert match.group(2) == version | 60,173 |
def create_filename(last_element):
"""
For a given file, returns its name without the extension.
:param last_element: str, file name
:return: str, file name without extension
"""
return last_element[:-4] | 60,174 |
def ajax_popular_environment_external(request, form_acess, client):
"""
Method to call popular_environment_shared when use by external way
"""
return facade.popular_environment_shared(request, client) | 60,175 |
def cyclic_learning_rate(learning_rate, global_step, max_lr, step_size=10,
mode='tri', name='CyclicLearningRate'):
""" This function varies the learning rate between the
minimum (learning_rate) and the maximum (max_lr).
It returns the decayed learning rate.
Parameters
-----... | 60,176 |
def identify_duplicates(stats):
"""Search the file signatures for duplicates.
:param list[Stats] stats: the file signatures
:return: a generator of all duplicates or `None` if `stats` is falsy
"""
if not stats:
return
# else:
stats.sort(key=lambda s: s.size)
size_grouped = i... | 60,177 |
def fetch_local_config(default, config=None):
"""
Returns the content of a yml config file as a hash
Parameters:
- default: default file name to look for
- config: override with this file name instead. (optional)
Note: the pattern of using config is intended to make using this with
OptionsParser easier. ... | 60,178 |
def test_control_sanity_check():
"""Test that control works on a very standard usecase."""
def make_ops():
qml.RX(0.123, wires=0)
qml.RY(0.456, wires=2)
qml.RX(0.789, wires=0)
qml.Rot(0.111, 0.222, 0.333, wires=2),
qml.PauliX(wires=2)
qml.PauliY(wires=4)... | 60,179 |
def stop_logging(Name=None):
"""
Suspends the recording of AWS API calls and log file delivery for the specified trail. Under most circumstances, there is no need to use this action. You can update a trail without stopping it first. This action is the only way to stop recording. For a trail enabled in all regio... | 60,180 |
def detect_lang(text, hint_language=None, best_effort=False,
all_details=False, return_score=False,
logger=None):
"""
Detect language of the text using pycld2
Parameters
----------
text : string
Text to detect language for.
all_details : bool, optional
... | 60,181 |
def generateCropRowsLinesAll(cfgLinesGenerator):
"""
generateCropRowsLinesAll.
:param cfgLinesGenerator: (Array) config lines generator array.
:returns None: None.
"""
tilesDirName = cfgLinesGenerator[0]
meanAngleFitElipseContours = cfgLinesGenerator[1]
pixelSizeValue = cfgLinesGenerator[2]... | 60,182 |
def plot_elevation(msfile,config,logger):
"""
Plots the elevation of the fields in each SPW as a function of time.
Input:
msfile = Path to the MS. (String)
config = The parameters read from the configuration file. (Ordered dictionary)
"""
logger.info('Starting plotting elevation.')
... | 60,183 |
def is_number(value: Union[int, str]) -> bool:
"""
Is thing a number
"""
return isinstance(value, int) or (isinstance(value, str) and value.isnumeric()) | 60,184 |
def getCpuUsage():
"""Find and return CPU Usage
Returns:
int -- Cpu Usage
"""
cpuUsage = psutil.cpu_percent()
return int(cpuUsage) | 60,185 |
def e_step(sigma,X, mask_var, mask_samp,n_ul = 0):
"""
E step for MTL algorithm.
"""
n = X.shape[0]
n_tr = np.size(np.where(mask_samp == False)[0])-n_ul
mask_var_c = ((mask_var+1)%2).astype(bool)
mask_samp_c = ((mask_samp+1)%2).astype(bool)
if n_ul>0:
mask_samp_c[0:n_ul] =... | 60,186 |
def Semantic_check(GFiles, GRegex, save_results):
"""Write score in GL_Result_2"""
global GL_Result_2
for username, reportdict in GFiles.items():
print_blue(colored(_("Checking participant '{}':").format(username), attrs=['bold']))
for reportname, lines in reportdict.items():
pri... | 60,187 |
def chain_submission(gromosXX_bin_dir: str, in_imd_path: str, simSystem:Simulation_System,
out_dir_path: str, out_prefix: str,
chain_job_repetitions: int, slave_script: str,
job_submission_system: _SubmissionSystem, jobname: str, nmpi: int,
... | 60,188 |
def composite_coordinates_dictionary(dictified_values):
"""A dictionnary will be populated (or updated) with values from the
'dictified_values' dictionnary
Parameters
----------
dictified_values :
A dictionary of Sentinel-1 values
coordinates_dictionary :
A dictionnary matching... | 60,189 |
def fruit_flow_through_fruit_development_stage(jth: int, number_Fruits, sum_canopy_t, last_24_canopy_t):
"""
Equation 9.31
number_flow_Fruit_j_Fruit_jplus = fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * fruit_flow_inhibition_rate * number_fruit_j
Returns: fruit flow through fruit development s... | 60,190 |
def normalization(vector):
"""
Normalize scores in this vector
"""
x = vector[vector>0]
beta = x.quantile(0.9)
updated_vector = vector/beta
return updated_vector | 60,191 |
def integer_repr(bin_str, fixed_width=False):
"""integer_repr(bin_str, fixed_width=False)
Converts a binary representation to its integer number.
Examples
--------
>>> integer_repr(b'11')
3
>>> integer_repr(b'-11')
-3
>>> integer_repr(b'0011')
3
The two's complement is re... | 60,192 |
def emu(Omh2, ns, s8, fR0, n, z):
"""Returns the emulator prediction of Boost in power spectrum, for a redshift between 0 < z < 49
Parameters
----------
Omh2: float
Physical matter density parameter (O_m h^2) in range [0.12, 0.15]. Here h = 0.67, a constant in the emulator design
ns: floa... | 60,193 |
def lp_visual(lp: LP,
basic_sol: bool = True,
show_basis: bool = True,) -> plt.Figure:
"""Render a figure visualizing the geometry of an LP's feasible region.
Args:
lp (LP): LP whose feasible region is visualized.
basic_sol (bool): True if the entire BFS is shown. De... | 60,194 |
def pkg_deploy(host=None):
"""
Deploy package to AWS S3
:return:
"""
pkg_build()
local('aws s3 cp dist/{pkg_wheel_fname} {aws_s3base}/'.format(pkg_wheel_fname=PKG_WHEEL_FNAME,
aws_s3base=AWS_S3_BASE).format(version=get_version())... | 60,195 |
def _cofactor(M, i, j, method="berkowitz"):
"""Calculate the cofactor of an element.
Parameters
==========
method : string, optional
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
"lu".
Examples
========
>>> from sympy import Matrix
>>> M = Matr... | 60,196 |
def separateResults(parallelResults, numThreads):
"""
Routine for separate each quality metric vector
Parameters
----------
parallelResults: A tuple of quality of metrics, return of performCalc
numThreads: 1D Numpy array
-------
Return:
A tuple of 3D Numpy Array
[itera... | 60,197 |
def get_default_db():
"""Get the default database for the crawler.
Returns:
DB API v2 compliant connection to the crawler's default database.
"""
parent_dir = os.path.dirname(os.path.realpath(__file__))
loc = os.path.join(parent_dir, 'articles.db')
return sqlite3.connect(loc) | 60,198 |
def _add_path(root_path, relative_path):
"""Add another level to an LDAP path.
eg,
_add_path('LDAP://DC=gb,DC=vo,DC=local', "cn=Users")
=> "LDAP://cn=users,DC=gb,DC=vo,DC=local"
"""
protocol = u("LDAP://")
if relative_path.startswith(protocol):
return relative_p... | 60,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.