content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def friends(graph, user):
"""Returns a set of the friends of the given user, in the given graph"""
return set(graph.neighbors(user)) | 57,600 |
def print_to_template_simple(outputFile, presenter):
"""
simplest template example, an extandable function for starting new languages
"""
file_loader = FileSystemLoader('src/templates')
env = Environment(loader=file_loader)
template = env.get_template('classy.py.tmpl')
template.globals['now'] = datetime.dateti... | 57,601 |
def _ValueOrPlaceHolder(value_string, description):
"""Embeds a string inside an XML <value>...</value> element.
If the string is empty or None, an alternate string is used instead.
Args:
value_string: String to embed
description: String to be used if the value string is empty or None.
Returns:
A... | 57,602 |
def test_recover_sent_airdrops(web3, prepared_contracts, transactions, signed, airdrops,
creator):
"""
Assuming partially sent airdrops, when there's need to sign transactions again
e.g. when it turned out that too little gas was allowed (unlikely)
"""
airdropper, omg_... | 57,603 |
def get_input_labels(
io_gratings: List[ComponentReference],
ordered_ports: List[Port],
component_name: str,
layer_label: Tuple[int, int] = (10, 0),
gc_port_name: str = "o1",
port_index: int = 1,
get_input_label_text_function: Callable = get_input_label_text,
) -> List[Label]:
"""Return ... | 57,604 |
def process_NNC(chrom, positions, strand, edge_IDs, vertex_IDs, transcript_dict,
gene_starts, gene_ends, edge_dict, locations, vertex_2_gene, run_info):
""" Novel not in catalog case """
novelty = []
start_end_info = {}
gene_ID = find_gene_match_on_vertex_basis(vertex_IDs, strand, vert... | 57,605 |
def test_markdown_with_extensions_info_and_bad_filter():
"""
Test to make sure
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = ["extensions", "info", "abc.def"]
expected_return_code = 2
expected_output = ""
expected_error = """usage: main.py extensions info [-h] info... | 57,606 |
def RLT(n, f):
"""run length transform of a function f"""
return prod(f(len(d)) for d in split("0+", bin(n)[2:]) if d != "") if n > 0 else 1 | 57,607 |
def validate_operator(operator_list):
"""
Function to validate the OpenShift operators creation
"""
fetched_operators = []
print("Validating Operators...")
operator_details = get_details("/apis/operators.coreos.com/v1alpha1/subscriptions?limit=250")
try:
if isinstance(operator_detail... | 57,608 |
def diagonal(a, offset=0, axis1=None, axis2=None, extract=True, axes=None):
"""
diagonal(a, offset=0, axis1=None, axis2=None)
Return specified diagonals.
If `a` is 2-D, returns the diagonal of `a` with the given offset,
i.e., the collection of elements of the form ``a[i, i+offset]``. If
`a` h... | 57,609 |
def get_arguments():
"""
Defining the arguments available for the script
:return: argument parser
"""
parser = argparse.ArgumentParser()
# Ads setting
parser.add_argument("-bud", "--cum_budget", default=CUM_BUDGET,
help="Cumulative budget to be used for the simulati... | 57,610 |
def _check_expression(text, allowed_variables=None):
"""
>>> allowed_variables = ["c1", "c2", "c3", "c4", "c5"]
>>> _check_expression("c1", allowed_variables)
True
>>> _check_expression("eval('1+1')", allowed_variables)
False
>>> _check_expression("import sys", allowed_variables)
False
... | 57,611 |
def build_exception_info(item_name, exc_type, exc_value, traceback):
"""Generate description info about exceptions."""
exc_info = None
if exc_type and (exc_type, exc_value, traceback) != pytest.item_status_info[item_name].get("exc_info", None):
if exc_type is AssertionError:
# in case ... | 57,612 |
def web_scraping_nba():
"""
This functions uses all functions available in 'src/utils' to generate 6 datasets related to the National Basketball
League (or NBA) which are then stored in 'docs' folder. The 6 generated datasets contain data about NBA teams' standings,
NBA players' lists and NBA players' s... | 57,613 |
def test_strip_prefix_from_list():
"""
normalize_ops.py: Test strip_prefix_from_list()
The function should remove the specified prefix from entries that have
that prefix.
"""
a = ['./abc', 'def', './../heya']
strip_prefix_from_list(a, './')
print(a)
assert a == ['abc', 'def', '../he... | 57,614 |
def build_algod_local_client(data_dir: Path) -> AlgodClient:
"""
Build the `algod` client to interface with the local daemon whose
configuration is at `data_dir`.
Args:
data_dir: the path with the network data
Returns:
the client connected to the local algod daemon
"""
algo... | 57,615 |
def set_read_only(khoros_object, enable=True, msg_id=None, msg_url=None, suppress_warnings=False):
"""This function sets (i.e. enables or disables) the read-only flag for a given message.
:param khoros_object: The core :py:class:`khoros.Khoros` object
:type khoros_object: class[khoros.Khoros]
:param en... | 57,616 |
def reports_download(request, file_name):
"""Generic method for downloading files."""
try:
file_path = '%s/%s' % (MEDIA_ROOT, file_name)
fp = open(file_path, 'rb')
response = HttpResponse(fp.read())
fp.close()
mime_type, encoding = mimetypes.guess_type(file_name)
... | 57,617 |
def bucket_sort(array: list[int]) -> list[int]:
"""
Time Complexity of Solution:
Worst Case: occurs when all the elements are placed in a single bucket.
The overall performance would then be dominated by the algorithm used to sort each
bucket. In this case, O(n log n), because of TimSort.
Avera... | 57,618 |
def create_tokenizer_from_hub_module():
"""Get the vocab file and casing info from the Hub module."""
with tf.Graph().as_default():
bert_module = hub.Module(BERT_MODEL_HUB)
tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
with tf.Session() as sess:
vocab_file, do_lower_... | 57,619 |
def test_supplement_get_star_disable_context_manager():
"""Test that disable_supplement_mags context manager works.
This assumes a global default of AGASC_SUPPLEMENT_ENABLED=False for these
tests.
"""
agasc_id = 58720672
star1 = agasc.get_star(agasc_id, date='2020:001', use_supplement=True)
... | 57,620 |
def get(package, plugin):
"""Get a given plugin"""
_import(package, plugin)
return _PLUGINS[package][plugin].func | 57,621 |
def read_paragraph_element(element):
"""Returns the text in the given ParagraphElement.
Args:
element: a ParagraphElement from a Google Doc.
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content') | 57,622 |
def telnet_read_eager(tn: ConnectionInformation, wf: object, current_output_log: [str], enable_removeLF: bool) -> str:
"""
Dealing with unread material.
"""
if tn.eof:
return False
try:
# current_output = tn.read_very_lazy() # Not recommended because it will be blocked.
cur... | 57,623 |
def parse_play(play):
"""
Parses formatted PLAY and returns ??? FIXME
"""
return None | 57,624 |
def propagate_to_peers(self):
"""Propogates to peers"""
send_rels = set([Relationships.ORIGIN,
Relationships.CUSTOMERS])
self._propagate(Relationships.PEERS, send_rels) | 57,625 |
def parse_int(integer, default=None):
"""提取整数,若失败则返回default值"""
try:
return int(integer)
except Exception, e:
return default | 57,626 |
def test_medication_4(base_settings):
"""No. 4 tests collection for Medication.
Test File: medicationexample0306.json
"""
filename = base_settings["unittest_data_dir"] / "medicationexample0306.json"
inst = medication.Medication.parse_file(
filename, content_type="application/json", encoding=... | 57,627 |
def ctd_sbe16digi_preswat(p0, t0, C1, C2, C3, D1, D2, T1, T2, T3, T4, T5):
"""
Description:
OOI Level 1 Pressure (Depth) data product, which is calculated using
data from the Sea-Bird Electronics conductivity, temperature and depth
(CTD) family of instruments.
This data product... | 57,628 |
def sha256(file: str):
"""
Reads a file content and returns its sha256 hash.
"""
sha = hashlib.sha256()
with open(file, "rb") as content:
for line in content:
sha.update(line)
return sha.hexdigest() | 57,629 |
def make_div_share_variable(exposure_level=7, div_level=3):
"""Calculates the share of employment in a low diversification sector
Args:
exposure_level (int): min threshold for high exposure
div_leve (int): min threshold for low diversification
"""
_DIVISION_NAME_LOOKUP = extract_sic_cod... | 57,630 |
def recurseIncludeFiles(elements, pwd):
"""Recursively follows and parses /include/ directives an a tree"""
for e in elements:
if isinstance(e, Directive):
if e.directive == "/include/":
# Prefix with current directory if path is not absolute
if e.option[0] !=... | 57,631 |
def plot_diagnostics_lr(df, data_fe):
"""
plots multi-panel diagnostics of linear regression assumptions
arguments
---------
df: dataframe containing residuals columns
return
------
none
"""
fig3, ax3 = plt.subplots(3, 3, figsize=(20, 15))
ax3[0, 0].hist(... | 57,632 |
def read_version0 (self, fp, line, verbose):
"""
An concrete method for reading information for a single patch.
The following must mirror what is in `patch_mod.f90::output_legacy`.
"""
self.kind = 'ramses'
self.eos = 'ideal'
self.opacity = 'none'
self.gamma = 1.4
# line 1: t... | 57,633 |
def StiffenUpperBody(stiffness = True, int_time=0.1):
"""Make Nao stiffen its joints (Can be True or False)"""
motionProxy.setStiffnesses('HeadPitch',int(stiffness), int_time)
motionProxy.setStiffnesses('HeadYaw',int(stiffness), int_time)
motionProxy.setStiffnesses('LElbowRoll',int(stiffness), int_t... | 57,634 |
def test(regexp, string):
"""Evaluate a regular expression regexp against the input string, returning true if the string matches the pattern, false otherwise.
For example: test(/\\d{3}/, "32-21-9483") -> true.
"""
raise RuntimeError('test' + error_message) | 57,635 |
def _user_has_perm(user, perm, obj):
"""
A backend can raise `PermissionDenied` to short-circuit permission checking.
"""
for backend in auth.get_backends():
if not hasattr(backend, 'has_perm'):
continue
try:
if backend.has_perm(user, perm, obj):
r... | 57,636 |
def gcd(a, b):
""" Computes the greatest common divisor between the two numbers using
Euclid's algorithm.
"""
if b == 0:
return a
else:
return gcd(b, a % b) | 57,637 |
def rect_crop_2D(im, rect_spec):
"""following imageJ style rectangle specification"""
left, top, width, height = rect_spec
im_crop = im[top:top+height, left:left+width].copy()
return im_crop | 57,638 |
def compare_zw():
"""
Compares the performance of HQ vs zero-worker HQ.
"""
artifacts = list(iterate_binaries([BuildConfig(), BuildConfig(zero_worker=True)]))
identifiers = create_basic_hq_benchmarks(artifacts)
workdir = Path("benchmark/zw")
run_benchmarks_with_postprocessing(workdir, identi... | 57,639 |
def encode_multipart_formdata(fields, files):
"""
@param fields: sequence of (name, value) elements for regular form fields.
@param files: sequence of (name, filename, value) elements for data to be
uploaded as files
@return: (content_type, body) ready for httplib.HTTP instance
"""
boun... | 57,640 |
def coverage_err(y_true, y_pred):
"""
Coverage error:
For every sample, how far down the ranked list of predicted classes must we reach to get all
actual class labels? The average value of this metric across samples is the coverage error.
:param y_true: array of shape (n_samples, n_labels)
:par... | 57,641 |
def setjsonstatus():
"""
Turn JSON output format on/off.
"""
global JSON
if JSON:
JSON=False
else:
JSON=True
if DEBUG:
print("SETJSONSTATUS: ", JSON) | 57,642 |
def test_get_clicks_command(requests_mock):
"""
Scenario: Retrieves clicks to malicious URLs blocked and permitted in the specified time period.
Given:
- User has provided valid credentials and arguments.
When:
- A get-clicks command is called and there is clicks in the res... | 57,643 |
def login(*args, **kwargs):
"""
Override view to use a custom Form
"""
kwargs['authentication_form'] = AuthenticationFormAccounts
return login_base(*args, **kwargs) | 57,644 |
def _calculate_bearings(graph, nodes):
"""
Calculate the compass bearings for each sequential node paid in `nodes`. Lat/lon coordinates are expected to be
node attributes in `graph` named 'y' and 'x'.
Args:
graph (networkx graph): containing lat/lon coordinates of each node in `nodes`
... | 57,645 |
def fetch_perfmap(client_id=uuid.uuid4(), debug=False):
"""Grabs the perfmap information from the Fastly API endpoint
Returns:
json: the data to use for remaining perf data collection
"""
url = '/perfmapconfig.js?jsonp=FASTLY.setupPerfmap'
hostname = str(client_id) + "-perfmap.u.fastly-anal... | 57,646 |
def dyfunc_print_variable(x):
"""
PY2:
Print(dest=None, values=[Name(id='x_v', annotation=None, type_comment=None)], nl=True)],
PY3:
Expr(
value=Call(func=Name(id='print', annotation=None, type_comment=None),
args=[Name(id='x_v', annotation=None, type_comment=None)],
... | 57,647 |
def lookup_capacity(lookup, environment, ant_type, frequency,
bandwidth, generation):
"""
Use lookup table to find the combination of spectrum bands
which meets capacity by clutter environment geotype, frequency,
bandwidth, technology generation and site density.
"""
if (environment, ant_ty... | 57,648 |
def load_from_mzxml(filename: str, ms_level: int = 2) -> Generator[Spectrum, None, None]:
"""Load spectrum(s) from mzml file.
This function will create ~matchms.Spectrum for every spectrum of desired
ms_level found in a given MzXML file. For more extensive parsing options consider
using the pyteomics p... | 57,649 |
def option(parser: Parser, otherwise: Any = None) -> Parser:
"""Create a parser that succeeds even when the given parser does not.
If nothing was parsed, then the value that was parsed is |otherwise|.
"""
def fn(parse_state):
"""Parse with parser, return value of None if parser fails."""
... | 57,650 |
def to_json(response):
""" Return a response as JSON. """
assert response.status_code == 200
return json.loads(response.get_data(as_text=True)) | 57,651 |
def num(s):
"""This function is used to convert string to int or float."""
try:
return int(s)
except ValueError:
return float(s) | 57,652 |
def Prepend(filepath, text):
""" Prepends text to the file.
Creates the file if it does not exist.
"""
file_data = text
if os.path.exists(filepath):
file_data += open(filepath).read()
f = open(filepath, 'w')
f.write(file_data)
f.close() | 57,653 |
def test_run_develop():
"""Ensure we call setup.py develop correctly..."""
with mock.patch.object(commands, "pypackage_setup") as patched_setup:
commands.develop()
mock_call = patched_setup.mock_calls[0]
assert mock_call[1][0] == ["develop", "test"]
assert mock_call[1][-1] == commands.deve... | 57,654 |
def equalize(request):
"""ヒストグラム平坦化関数"""
# キャッシュディレクトリを作成
cache_dir = Path(__file__).parent.joinpath('cache').joinpath('equalize')
cache_dir.mkdir(parents=True, exist_ok=True)
# 画像データをbase64形式で取得
base64image = request.POST.get('image')
# base64をバイナリデータに変換し、ヘッダーも同時に保存する
if base64image.s... | 57,655 |
async def lsvaide():
"""" Print help """
help=("Un bot qui permet d'obtenir les informations du jour sur wikipedia\n\n"
"Commandes:\n"
"\t/lsvaide : Affiche l'aide\n"
"\t/lsvimage : Obtient l'image du jour\n"
"\t/lsvlumiere : Obtient l'article du jour\n"
... | 57,656 |
def mutation_frequency(H, D):
"""
# ========================================================================
MUTATION FREQUENCY
PURPOSE
-------
Calculates the mutation frequency.
INPUT
-----
[INT] [H]
The number of haplotypes.
[2D ARRAY] [D]
A distance mat... | 57,657 |
def _parse_given(rtype: str, report: str, opts: [str]) -> (dict, int):
"""
Attepts to parse a given report supplied by the user
"""
try:
ureport = _HANDLE_MAP[rtype]("KJFK") # We ignore the station
ureport.update(report)
resp = asdict(ureport.data[0])
resp["meta"] = {"ti... | 57,658 |
async def test_bad_request(aresponses):
"""Test that the proper exception is raised during a bad request."""
aresponses.add(
"api.openuv.io",
"/api/v1/bad_endpoint",
"get",
aresponses.Response(text="", status=500),
)
with pytest.raises(RequestError):
async with a... | 57,659 |
def new_feature(signal):
"""Computes a new feature
Parameters
----------
signal : nd-array
Input from which new feature is computed
Returns
-------
float
new feature
"""
return np.mean(signal)-np.std(signal) | 57,660 |
def __test_path(path, chk_type, nonexistent=None, not_ok_msg=None):
"""
Test a file path, to see if it is exists and is a file
:param path: path to filesystem object to check
:type chk_type: type to check for; __ISFILE or __ISDIR
:param nonexistent: message to display if nonexistent
:param not_o... | 57,661 |
def SKPD_processing(Cov_MPMB, opt_str):
"""SKPD_processing
Kernel of the Sum of Kronecker Product Decomposition.
INPUT
Cov_MPMB: [N*Npol x N*Npol] covariance matrix
opt_str.
N: number of images
Npol: number of polarization... | 57,662 |
def dhall_type(value: Property, name: str, types: Types, defs: Defs) -> Optional[Tuple[DhallType, Types]]:
"""Convert a property to a dhall type name. Also add newly discovered types to the list of types"""
_type: Optional[str] = None
# TODO: remove this work-around
if not value.get('type'):
if... | 57,663 |
def get_public_keys_of_user(session, user_id):
"""Retrieve all public keys for user.
Args:
session(models.base.session.Session): database session
user_id(int): id of user in question
Returns:
List of PublicKey model object representing the keys
"""
pkey = session.query(Publ... | 57,664 |
def avgFriendDegree(v, Giant):
""" Calculate the average degree of the neighbors of a node"""
degSum = 0
for u in Giant.neighbors(v):
degSum += Giant.degree(u)
return degSum / Giant.degree(v) | 57,665 |
def create_snapshot_if_not_exist(volume_id, tags, time_limit):
""" Create a snapshot of the volume in parameter only if any snapshot
exists for this volume_id and if it was created in the time delta
define by the difference between now and the time_limit value (in
minutes).
:param ... | 57,666 |
def calculate_sigma_v(depths, gammas):
"""
Calculates the vertical stress
"""
depth_incs = depths[1:] - depths[:-1]
depth_incs = np.insert(depth_incs, 0, depth_incs[0])
sigma_v_incs = depth_incs * gammas
sigma_v = np.cumsum(sigma_v_incs)
return sigma_v | 57,667 |
def test_experiment_same_name_wout_exv_w_child(
clean_db, three_experiments_family_same_name, capsys
):
"""Test status with two experiments having the same name and one with a child."""
orion.core.cli.main(["status"])
captured = capsys.readouterr().out
expected = """\
test_single_exp-v1
==========... | 57,668 |
def lon_lat_to_cartesian(lon, lat, radius=1):
"""
calculates lon, lat coordinates of a point on a sphere with
radius radius
"""
# Unpack xarray object into plane arrays
if hasattr(lon, 'data'):
lon = lon.data
if hasattr(lat, 'data'):
lat = lat.data
if lon.ndim != lat.nd... | 57,669 |
def get_eia860_xlsx(years, filename, data_dir):
"""Read in Excel files to create Excel objects.
Rather than reading in the same Excel files several times, we can just
read them each in once (one per year) and use the ExcelFile object to
refer back to the data in memory.
Args:
years (list):... | 57,670 |
def get_model_details(event, context):
"""
Extract the model attributes from the model passed as an argument
"""
# Get attributes from both the model and the associated dataset:
model_name = event['model_name']
model_response = l4e_client.describe_model(ModelName=model_name)
dataset... | 57,671 |
def main():
"""Sets up the devices and registers with the MQTT host.
"""
global settings
with open('settings.json') as settings_file:
settings = json.load(settings_file)
doors.append(GarageDoor("door1", state_pin=1))
relays.append(Relay("relay1", relay_pin=1))
client = mqtt.Client(s... | 57,672 |
def get_aligned_args(args):
"""Loading aligned from args namespace from argparse
"""
if args.aligned_dir is not None:
if args.aligned_name is not None:
raise ValueError(
"args -aligned_dir and -aligned_name should not be both set")
return get_aligned_dir(args.alig... | 57,673 |
def SmoothArray(xx: List[float]) -> List[float]:
"""Runs the 353QH algorithm twice and returns smooth version of the input.
For documentation see these proceedings https://cds.cern.ch/record/186223/ on page
292. The algorithm runs twice to avoid over-smoothing peaks and valleys. The
algorithm is not aw... | 57,674 |
def check_attack(board, bad_positions, snake):
""" Determines if we have the opportunity to attack - doesn't seek out attacking but will attack given the opportunity """
possible_attacks = []
available_moves = available_next_positions(board, snake)
# attack potential position that enemy would move into... | 57,675 |
def station():
"""
Return a list of all stations from database.
"""
session = Session(engine)
results = session.query(Station.name).all()
session.close()
station_dict = list(np.ravel(results))
return jsonify(station_dict) | 57,676 |
def dots2utf8(dots):
""" braille dots to utf-8 hex codes"""
code=0
for number in dots:
code += 2**(int(number)-1)
return hex(0x2800 + code) | 57,677 |
def set_domain_to_dns_name(session, domain_name, dns_resource, hosted_zone):
"""Updates or Creates a domain name with FQDN resource.
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
domain_n... | 57,678 |
def full_range_args_generator(**ranges):
"""
Cartesian production, generates all possible combinations of the arguments
:param ranges: range(...) objects or lists, defines arguments' domains
:return:
"""
res = itertools.product(*(r for r in ranges.values()))
res = (dict(zip(ranges.keys(), r)... | 57,679 |
def _can_view_courseware_with_prerequisites(user, course):
"""
Checks if a user has access to a course based on its prerequisites.
If the user is staff or anonymous, immediately grant access.
Else, return whether or not the prerequisite courses have been passed.
Arguments:
user (User): the... | 57,680 |
def _convert_to_coord_format(interaction_file, out_file):
"""make it easier to work with interaction file,
produces start_id, end_id, score
"""
assert interaction_file.endswith(".gz")
assert out_file.endswith(".gz")
# reformat
reformat = (
"zcat {} | "
"awk -F ',' '{{ pr... | 57,681 |
def is_non_zero_file(fpath):
# https://stackoverflow.com/a/15924160
"""Returns TRUE/FALSE if file exists and non zero"""
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0 | 57,682 |
def add_num_epochs_and_checkpoints(config):
"""Add number of epochs and checkpoints where model will be saved to config."""
problem_cls = config["problem_cls"]
num_epochs = DEFAULT_TEST_PROBLEMS_SETTINGS[problem_cls.__name__]["num_epochs"]
config["num_epochs"] = num_epochs
if "checkpoints" not in c... | 57,683 |
def doCompare(op, left, right):
"""Perform the given AST comparison on the values"""
top = type(op)
if top == ast.Eq:
return left == right
elif top == ast.NotEq:
return left != right
elif top == ast.Lt:
return left < right
elif top == ast.LtE:
return left <= right
elif top == ast.Gt:
return left > righ... | 57,684 |
def gen_html_report(summary, report_template=None, report_dir=None, report_file=None):
""" render html report with specified report name and template
Args:
summary (dict): test result summary data
report_template (str): specify html report template path, template should be in Jinja2 format.
... | 57,685 |
def import_class(module_base_name, script_name):
"""
导入指定模块的脚本,并返回
# from sys import stdin
# sys = __import__('sys', fromlist = ['stdin'])
:return: 所需模块
"""
module_levels = script_name.split(".")
file_module_name = module_levels[-1]
class_name = String().class_name_normalize(fil... | 57,686 |
def runGdScript(godot, filepath):
"""Run the given GdScript file and return the
results as an array of strings"""
return runGodot([godot, '-s', filepath]) | 57,687 |
def unmold_mask(masks, bboxes, image_shape):
"""Converts a mask generated by the neural network into a format similar to it's original shape,
using overlap-tile strategy here.
masks: [detect_num, depth, height, width, num_instances] of type float. A small, typically 28x28 mask.
bboxes: [detect_num, ... | 57,688 |
def create_link_atoms(mol, qmatoms):
""" Create hydrogen caps for bonds between QM and MM regions.
Each link atom will have ``metadata.mmatom``, ``metadata.mmpartner`` attributes to identify the
atom it replaces and the atom it's bonded to in the MM system.
Raises:
ValueError: if any MM/QM ato... | 57,689 |
def generate_signature(secret, verb, url, nonce, data):
"""Generate a request signature compatible with BitMEX."""
# Parse the url so we can remove the base and extract just the path.
parsedURL = urlparse(url)
path = parsedURL.path
if parsedURL.query:
path = path + '?' + parsedURL.query
... | 57,690 |
def get2(request):
"""一键多值"""
# 获取GET属性对应的queryDict类型的对象
query_dict = request.GET
a = query_dict.getlist('a') # query_dict.get('a') 只会获取最后一个值
b = query_dict.get('b')
c = query_dict.get('c') # 如果key不存在,返回None
str = '%s - %s -%s' % (a, b, c)
return HttpResponse(str) | 57,691 |
def signature(class_name):
"""return the signature for a port using one of the
module classes defined in this file"""
from __init__ import identifier
return ':'.join((identifier, class_name)) | 57,692 |
def get_volume_labels_from_src(src, subject, subjects_dir):
"""Return a list of Label of segmented volumes included in the src space.
Parameters
----------
src : instance of SourceSpaces
The source space containing the volume regions
subject: str
Subject name
subjects_dir: str
... | 57,693 |
def test():
"""Test"""
e = echo_server()
e.server() | 57,694 |
def get_path_name(obj_name, io=None):
""" Returns a path and a name for where the downloaded objects (list or excel file) will be stored.
:param str obj_name: a list name or a path to an excel file in sharepoint
:param str io: path to where downloaded objects (list or excel file) will be stored.
:return... | 57,695 |
def Lagrange_polynomials_01(x, N):
"""
Compute all the Lagrange polynomials (at x) for N+1 equally
spaced interpolation points on [0,1]. The polynomials
and points, as two separate lists, are returned.
Works for symbolic and numerical computation of the
polynomials and points (if x is sympy.Symb... | 57,696 |
def _random_integer(minval, maxval, seed):
"""Returns a random 0-D tensor between minval and maxval.
Args:
minval: minimum value of the random tensor.
maxval: maximum value of the random tensor.
seed: random seed.
Returns:
A random 0-D tensor between minval and maxval.
"""
return tf.random.u... | 57,697 |
def list_posts(page=1, num_items=10):
"""List all blog posts, in sets of 10."""
url = bottle.request.urlparts
page = bottle.request.query.page or 1
try:
page = int(page) if int(page) > 0 else 1
except:
bottle.abort(404, "Page not found")
count = db.zcard("content:posts:live")
... | 57,698 |
def read_dataset(path,
header=None,
columns=None,
make_binary=False,
binary_th=4.0,
user_key='user_id',
item_key='item_id',
rating_key='rating',
sep=',',
user_to_idx=N... | 57,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.