content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def white_noise(template, rms_uKarcmin_T, rms_uKarcmin_pol=None):
"""Generate a white noise realisation corresponding to the template pixellisation
Parameters
----------
template: ``so_map`` template
the template for the white noise generalisation
rms_uKarcmin_T: float
the white noise t... | 34,100 |
def run_state_machine(state, rate, domain=None):
""" Convenience method for running a state machine. Equivalent to RunState(state, rate).run().
"""
RunState(state, rate, domain).run() | 34,101 |
def index():
"""process request to the root."""
return render_template('index.html') | 34,102 |
def aromatic_bonds(mol: IndigoObject) -> dict:
"""Get whether bonds in a molecule are aromatic or not.
Args:
IndigoObject: molecule object
Returns:
dict: key - feature name, value - torch.tensor of booleans
"""
is_aromatic = []
for bond in mol.iterateBonds():
is_aromati... | 34,103 |
def dt_bestrefs_na_undefined_single_ctx_na_matters():
"""
>>> old_state = test_config.setup()
Instantiate a BestrefsScript with default settings and dummy parameters, simulating pipeline bestrefs defaults:
>>> script = BestrefsScript(argv="crds.bestrefs --load-pickles data/bestrefs.special.json --na-... | 34,104 |
def get_unitroot(df: pd.DataFrame, fuller_reg: str, kpss_reg: str) -> pd.DataFrame:
"""Calculate test statistics for unit roots
Parameters
----------
df : pd.DataFrame
DataFrame of target variable
fuller_reg : str
Type of regression of ADF test
kpss_reg : str
Type of reg... | 34,105 |
def visit_desc(translator: LaTeXTranslator, node: addnodes.desc) -> None:
"""
Visit an :class:`addnodes.desc` node and add a custom table of contents label for the item, if required.
:param translator:
:param node:
"""
if node["domain"] == "py":
translator.body.append(r"\needspace{5\baselineskip}")
if "sphi... | 34,106 |
def lat_avg(data, lat_wgt):
"""Perform latitude average of data:
Inputs:
data - n dimensional spatial data. The last 2 dimensions are assumed to lat and
lon respectively
lat_wgt - weights by latitudes"""
lat_shape = lat_wgt.shape
data_shape = data.shape
# If one dimension... | 34,107 |
def create_line(line_coefficients, height=5, step=0.5, vis=False):
"""
Args:
line_coefficients: A dictionary containing cylindrical coefficients:
(r, x0, y0, z0_, a, b, c
r not used: to keep the same form between cylinder coefficient... | 34,108 |
def get_result_summaries_query(start, end, sort, state, tags):
"""Returns TaskResultSummary.query() with these filters.
Arguments:
start: Earliest creation date of retrieved tasks.
end: Most recent creation date of retrieved tasks, normally None.
sort: Order to use. Must default to 'created_ts' to use ... | 34,109 |
def approx_jacobian(tform, image, delta=0.01):
"""approximate the image pixel gradient wrt tform using central differences
(This has been so helpful while troubleshooting jacobians,
let's keep it around for unit testing.
Parameters
----------
tform : TForm
current transform, to be appl... | 34,110 |
def assert_equal(
actual: statsmodels.tools.tools.Bunch, desired: statsmodels.tools.tools.Bunch
):
"""
usage.statsmodels: 8
"""
... | 34,111 |
def built_in_demo():
"""Using built-in sequence functions.
>>> bcd = ['b', 'c', 'd']
>>> [x.upper() for x in bcd]
['B', 'C', 'D']
>>> caps = map(lambda x: x.upper(), bcd)
>>> next(caps)
'B'
>>> next(caps)
'C'
>>> s = range(3, 7)
>>> doubled = map(double, s)
>>> next(doub... | 34,112 |
def create_collection(collection_id: str) -> Collection:
"""Creates a STAC Collection for Landsat Collection 2 Level-1 or Level-2
data.
Args:
collection_id (str): ID of the STAC Collection. Must be one of
"landsat-c2-l1" or "landsat-c2-l2".
Returns:
Collection: The created S... | 34,113 |
def rician_noise(image, sigma, rng=None):
"""
Add Rician distributed noise to the input image.
Parameters
----------
image : array-like, shape ``(dim_x, dim_y, dim_z)`` or ``(dim_x, dim_y,
dim_z, K)``
sigma : double
rng : random number generator (a numpy.random.RandomState instance)... | 34,114 |
def compose_pinned_post(post):
"""
1.Verify that this is the pinned post
2.Obtain the results json from the results rig
3.Compose the HTML for the compact graphic
"""
pinned_post = post
# Get the timestamps collection
client = MongoClient(app_config.MONGODB_URL)
database = client['li... | 34,115 |
def panLeft(self):
"""
TOWRITE
"""
qDebug("panLeft()")
gview = self.activeView() # View*
stack = gview.getUndoStack() # QUndoStack*
if gview and stack:
cmd = UndoableNavCommand("PanLeft", gview, None)
stack.push(cmd) | 34,116 |
def compute_composition_df(seq_df):
"""
Compute the composition matrix for all proteins.
Args:
seq_df: df, dataframe with sequences
Returns:
df, with the composition of the proteins
"""
# get composition table
df_seq_comp = pd.DataFrame(
list(seq_df["sequence"].app... | 34,117 |
def make_gradient_squared(
grid: CylindricalSymGrid, central: bool = True
) -> OperatorType:
"""make a discretized gradient squared operator for a cylindrical grid
{DESCR_CYLINDRICAL_GRID}
Args:
grid (:class:`~pde.grids.cylindrical.CylindricalSymGrid`):
The grid for which the opera... | 34,118 |
def test_frame_attr_getattr():
"""
When accessing frame attributes like equinox, the value should come
from self.frame when that object has the relevant attribute, otherwise
from self.
"""
sc = SkyCoord(1, 2, frame='icrs', unit='deg', equinox='J1999', obstime='J2001')
assert sc.equinox == 'J... | 34,119 |
def state(git_root):
"""Return a hash of the current state of the .git directory. Only considers
fsck verbose output and refs.
"""
if not git_root.is_dir():
return 0
rc, stdout, stderr = util.captured_run(*"git fsck --full -v".split(), cwd=git_root)
refs = "".join([ref.name + ref.value f... | 34,120 |
def search_handler(data_type_name, search_key=None, search_value=None):
"""
Purpose: Adapt PathError and QueryError to appropriate Django error types.
Input Parameters:
data_type_name - One of the searchable types 'PasswordData' or 'GroupData'.
search_key - Name of searchable field for type ... | 34,121 |
def render_CardsCounter_edit(self, h, comp, *args):
"""Render the title of the associated object"""
text = var.Var(self.text)
with h.div(class_='list-counter'):
with h.div(class_='cardCounter'):
with h.form(onsubmit='return false;'):
action = h.input(type='submit').action... | 34,122 |
def get_embedding_tids(tids, mapping):
"""Obtain token IDs based on our own tokenization, through the mapping to BERT tokens."""
mapped = []
for t in tids:
mapped += mapping[t]
return mapped | 34,123 |
def reloadConfiguration():
"""Reloads the configuration.
This can be used for reloading a new configuration from disk.
At the present time it has no use other than setting different configurations
for testing, since the framework is restarted every time an analysis is
performed."""
global _config
_config... | 34,124 |
def delete_configuration(timestamp: AnyStr) -> AnyStr:
"""
Delete the configuration folder.
:timestamp (AnyStr) The name of the configuration to delete
Return the name of the deleted configuration, or crash
"""
rating_rates_dir = envvar('RATING_RATES_DIR')
with Lockfile(rating_rates_dir):... | 34,125 |
def extract_stream_url(ashx_url):
""" Extract real stream url from tunein stream url """
r = requests.get(ashx_url)
for l in r.text.splitlines():
if len(l) != 0:
return l | 34,126 |
def check_for_rematch(player_id1, player_id2):
"""Checks whether the two players specified have played a match before.
Args:
player_id1: ID of first player
player_id2: ID of second player
Returns:
Bool: True if they have met before, False if they have not.
"""
query = """SE... | 34,127 |
def nextrandombitsAES(cipher, bitlength):
"""
<Purpose>
generate random bits using AES-CTR
<Arguments>
bitlength: the lenght of the random string in BITS
<Side Effects>
Increases the AES counter
<Returns>
A random string with the supplied bitlength (the rightmost bits are zero if bitlength is not a mult... | 34,128 |
def _binparams2img(mc, param):
"""
Maximum data of all the bins
Parameters
----------
mc : dict
Molecular cloud dimensions
param : boolean
Parameter
----------
"""
if not param in sos.all_params:
raise Exception('Parameter not v... | 34,129 |
def setup_sample_weighting_columns(df):
"""
"""
# samples will be weighted twice as highly compared to 1 season before
df["1_season_half_life_weight"] = (2**1) ** (df["season"] - 2001)
# samples will be weighted twice as highly compared to 2 seasons before
df["2_season_half_life_weight"] = (2**... | 34,130 |
def arccos(x):
"""
Compute the inverse cosine of x.
Return the "principal value" (for a description of this, see
`numpy.arccos`) of the inverse cosine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[0, \\pi]`. Otherwise, the complex principle ... | 34,131 |
def assert_topic_lists_are_equal_without_automatic_topics(expected, actual):
"""Check for equality in topic lists after filtering topics that start with
an underscore."""
filtered_actual = list(filter(lambda x: not x.startswith('_'), actual))
assert expected == filtered_actual | 34,132 |
def request_authentication(user, organization_id, short_code):
"""
Request for an authentication token from Safaricom's MPesa API
"""
mpesa_api_account = get_object_or_404(
MpesaAPIAccount.objects.filter(
organization__owner=user,
linked_account__identifier=short_code,
... | 34,133 |
def test_basic():
"""
The test launches the simulator, loads the system and prints the kinematic chain and state of the robot.
"""
# Setup simulator
kit, system = setup_kit_and_system()
# display information
system.robot.display() | 34,134 |
def none_to_null(value):
""" Returns None if the specified value is null, else returns the value
"""
return "null" if value == None else value | 34,135 |
def get_dsd_url():
"""Returns the remote URL to the global SDMX DSD for the SDGs."""
return 'https://registry.sdmx.org/ws/public/sdmxapi/rest/datastructure/IAEG-SDGs/SDG/latest/?format=sdmx-2.1&detail=full&references=children' | 34,136 |
def PrintUsageString():
"""Prints the correct call for running the sample."""
print ('python emailsettings_pop_settings.py'
'--consumer_key [ConsumerKey] --consumer_secret [ConsumerSecret]'
'--domain [domain]') | 34,137 |
def range_closest(ranges, b, left=True):
"""
Returns the range that's closest to the given position. Notice that the
behavior is to return ONE closest range to the left end (if left is True).
This is a SLOW method.
>>> ranges = [("1", 30, 40), ("1", 33, 35), ("1", 10, 20)]
>>> b = ("1", 22, 25)... | 34,138 |
def _fill_array(data, mask=None, fill_value=None):
"""
Mask numpy array and/or fill array value without demasking.
Additionally set fill_value to value.
If data is not a MaskedArray and mask is None returns silently data.
:param mask: apply mask to array
:param fill_value: fill value
"""
... | 34,139 |
def make_Dog(size, name):
"""Create dog entity."""
new_dog = Dog(size=size, name=str(name))
if new_dog.called() == "":
return f"The {size} dog says {new_dog.talk()}."
return f"{new_dog.called()}, the {size} dog says {new_dog.talk()}." | 34,140 |
def get_spectra_onepixel(data, indx, MakeMock, seed, log, ntarget,
maxiter=1, no_spectra=False, calib_only=False):
"""Wrapper function to generate spectra for all targets on a single healpixel.
Parameters
----------
data : :class:`dict`
Dictionary with all the mock data... | 34,141 |
def one_way_mi(df, feature_list, group_column, y_var, bins):
"""
Calculates one-way mutual information group variable and a
target variable (y) given a feature list regarding.
Parameters
----------
df : pandas DataFrame
df with features used to train model, plus a target variable
... | 34,142 |
def test_whole_range_same(check_ranges, accounts, nft):
"""whole range, merge both sides"""
nft.transferRange(accounts[3], 5000, 10001, {"from": accounts[1]})
nft.transferRange(accounts[1], 25001, 30001, {"from": accounts[3]})
nft.transferRange(accounts[3], 10001, 20001, {"from": accounts[2]})
check... | 34,143 |
def _comments_for_2zxglv(sc, submission_id):
"""Shared set of assertions for submission 2zxglv.
"""
assert isinstance(sc, list)
assert len(sc) == 7
# matchup first comment keys with DB model schema
assert sorted(sc[0].keys()) == sorted(scraper._model_columns(Comment))
# first comment indiv... | 34,144 |
def draw_parametric_bs_reps_mle(
mle_fun, gen_fun, data, args=(), size=1, progress_bar=False
):
"""Draw parametric bootstrap replicates of maximum likelihood estimator.
Parameters
----------
mle_fun : function
Function with call signature mle_fun(data, *args) that computes
a MLE for... | 34,145 |
def parse_subpalette(words):
"""Turn palette entry into a list of color-to-index mappings.
For example, #AAA=2 or #AAAAAA=2 means that (170, 170, 170) will be
recognized as color 2 in that subpalette.
If no =number is specified, indices are recognized sequentially from 1.
Return a list of ((r, g, b), index) tuple... | 34,146 |
def data_word2vec(input_file, num_labels, word2vec_model):
"""
Create the research data tokenindex based on the word2vec model file.
Return the class _Data() (includes the data tokenindex and data labels).
Args:
input_file: The research data
num_labels: The number of classes
wor... | 34,147 |
def find_version_files(
root_dir: str, dont_search_dir_names: set = {"tests", "test"}
) -> list:
"""You can use this.
This function will recursively find the __init__.py(s) in a nontest directory.
:param str root_dir: Description of parameter `root_dir`.
:return: Description of returned object.
... | 34,148 |
def test_out_of_permission_scope(tesla_model_s):
"""
status code: 403, no "error" code
"""
try:
tesla_model_s.odometer()
except Exception as e:
assert isinstance(e, SmartcarException)
# 8 fields stated in exception.py + 'message'
assert len(e.__dict__.keys()) == 9
... | 34,149 |
def object_difference():
"""Compute the difference parts between selected shapes.
- Select two objects.
Original code from HighlightDifference.FCMacro
https://github.com/FreeCAD/FreeCAD-macros/blob/master/Utility/HighlightDifference.FCMacro
Authors = 2015 Gaël Ecorchard (Galou)
"""
global v... | 34,150 |
def diffusionkernel(sigma, N=4, returnt=False):
""" diffusionkernel(sigma, N=4, returnt=False)
A discrete analog to the continuous Gaussian kernel,
as proposed by Toni Lindeberg.
N is the tail length factor (relative to sigma).
"""
# Make sure sigma is float
sigma = floa... | 34,151 |
def CalculateTopologicalTorsionFingerprint(mol):
"""
#################################################################
Calculate Topological Torsion Fingerprints
Usage:
result=CalculateTopologicalTorsionFingerprint(mol)
Input: mol is a molecule object.
... | 34,152 |
def prepare_answer_extraction_samples(context: str, answer_list: List[Dict] = None):
"""
Args:
context: str (assumed to be normalized via normalize_text)
answer_list: [
{'text': str, 'answer_start': int},
{'text': str, 'answer_start': int},
...
]
"... | 34,153 |
def mix_in(
source: type,
target: type,
should_copy: Optional[Callable[[str, bool], bool]] = None,
) -> List[str]:
"""
Copy all defined functions from mixin into target. It could be
usefull when you cannot inherit from mixin because incompatible
metaclass. It does not copy abstract functions... | 34,154 |
def get_img_num_per_cls(cifar_version, imb_factor=None):
"""
Get a list of image numbers for each class, given cifar version
Num of imgs follows emponential distribution
img max: 5000 / 500 * e^(-lambda * 0);
img min: 5000 / 500 * e^(-lambda * int(cifar_version - 1))
exp(-lambda * (int(cifar_ver... | 34,155 |
async def cmd_tournament_next(ctx: discord.ext.commands.Context):
"""
Get information about the starting time of the next month's tournament.
Usage:
/tournament next
/tourney next
Examples:
/tournament next - Displays information about the starting time of next month's tournament.
... | 34,156 |
def report_model_activations(model, labels=None, output_folder=None, model_name="model",
categories="none",
conv_layers="all", conv_layer_filters="all"):
"""
Plots the convolution filters and predictions activation images for the given model.
:param ... | 34,157 |
def xml():
"""
Returns the lti.xml file for the app.
"""
try:
return Response(render_template(
'lti.xml'), mimetype='application/xml'
)
except:
app.logger.error("Error with XML.")
return return_error('''Error with XML. Please refresh and try again. If this... | 34,158 |
async def test_siren_change_default_tone(hass: HomeAssistant):
"""Test changing the default tone on message."""
entry = configure_integration(hass)
test_gateway = HomeControlMockSiren()
test_gateway.devices["Test"].status = 0
with patch(
"homeassistant.components.devolo_home_control.HomeCont... | 34,159 |
def log_get_level(client):
"""Get log level
Returns:
Current log level
"""
return client.call('log_get_level') | 34,160 |
def cal_pivot(n_losses,network_block_num):
"""
Calculate the inserted layer for additional loss
"""
num_segments = n_losses + 1
num_block_per_segment = (network_block_num // num_segments) + 1
pivot_set = []
for i in range(num_segments - 1):
pivot_set.append(min(num_block_per_se... | 34,161 |
async def scan_host(
host: IPv4Address,
semaphore: asyncio.Semaphore,
timeout: int,
verbose: bool,
):
"""
Locks the "semaphore" and tries to ping "host" with timeout "timeout" s.
Prints out the result of the ping to the standard output.
"""
async with semaphore:
try:
... | 34,162 |
def _emit_post_update_statements(
base_mapper, uowtransaction, cached_connections, mapper, table, update
):
"""Emit UPDATE statements corresponding to value lists collected
by _collect_post_update_commands()."""
needs_version_id = (
mapper.version_id_col is not None
and mapper.version_i... | 34,163 |
def build_grid_search_config(params_dict):
"""
传入一个json,按网格搜索的方式构造出符合条件的N个json, 目前网格搜索只作用在optimization范围内
:param params_dict:
:return: param_config_list
"""
model_params_dict = params_dict.get("model")
opt_params = model_params_dict.get("optimization", None)
if not opt_params:
ra... | 34,164 |
def test_ses_get_subarray_id_for_requested_pid():
"""
Verify that the private method _get_subarray_id returns
subarray id correctly
"""
subarray_id = 123
process_pid = 456
procedure = Procedure("test://a")
init_args = ProcedureInput(subarray_id=subarray_id)
procedure.script_args["in... | 34,165 |
def cutoff_countmin_wscore(y, scores, score_cutoff, n_cm_buckets, n_hashes):
""" Learned Count-Min (use predicted scores to identify heavy hitters)
Args:
y: true counts of each item (sorted, largest first), float - [num_items]
scores: predicted scores of each item - [num_items]
score_cut... | 34,166 |
def test_lcc_like_epi():
"""
Takes about 5 mins with epicyclic
If burnin is too short (say 200 steps) won't actually find true solution
"""
TORB_FUNC = trace_epicyclic_orbit
mean_now = np.array([50., -100., 25., 1.1, -7.76, 2.25])
age = 10.
mean = TORB_FUNC(mean_now, times=-age)
dx... | 34,167 |
def uniquePandasIndexMapping(inputColumn):
"""quickly mapps the unique name entries back to input entries
Keyword arguments:
inputDataToAssess -- a SINGLE column from a pandas dataframe, presumably with
duplications. Will create a frequency table and a mapping back to the source entries.
"""
... | 34,168 |
def non_max_suppression(boxlist, thresh, max_output_size, scope=None):
"""Non maximum suppression.
This op greedily selects a subset of detection bounding boxes, pruning
away boxes that have high IOU (intersection over union) overlap (> thresh)
with already selected boxes. Note that this only works for a sing... | 34,169 |
def client_role_setting(realm, client_id):
"""クライアントロール設定 client role setting
Args:
realm (str): realm
client_id (str): client id
Returns:
[type]: [description]
"""
try:
globals.logger.debug('#' * 50)
globals.logger.debug('CALL {}: realm[{}] client_id[{}]'.f... | 34,170 |
def gen_weekly_ccy_df( start,end ):
""" Generate weekly ccy data table
"""
currency_li =[ "USD_Index",
"EURUSD","GBPUSD","AUDUSD","CADUSD",
"JPYUSD",
"CNYUSD","HKDUSD","TWDUSD",
"KRWUSD","THBUSD","SGDUSD","MYRUSD",
... | 34,171 |
def compute_stats_array(
cfg,
dem,
ref,
dem_nodata=None,
ref_nodata=None,
display=False,
final_json_file=None,
):
"""
Compute Stats from numpy arrays
:param cfg: configuration dictionary
:param dem: numpy array, dem raster
:param ref: numpy array, reference dem raster to... | 34,172 |
def remove_group_common(group_id, username, org_id=None):
"""Common function to remove a group, and it's repos,
If ``org_id`` is provided, also remove org group.
Arguments:
- `group_id`:
"""
seaserv.ccnet_threaded_rpc.remove_group(group_id, username)
seaserv.seafserv_threaded_rpc.remove_rep... | 34,173 |
def demean_and_normalise(points_a: np.ndarray,
points_b: np.ndarray):
"""
Independently centre each point cloud around 0,0,0, then normalise
both to [-1,1].
:param points_a: 1st point cloud
:type points_a: np.ndarray
:param points_b: 2nd point cloud
:type points_b: ... | 34,174 |
def parallel_login_of_multiple_users(self, ldap_server, ldap_user, timeout=200, role_count=10):
"""Check that valid and invalid logins of multiple LDAP authenticated users
with mapped roles works in parallel.
"""
parallel_login(user_count=10, ldap_user=ldap_user,ldap_server=ldap_server,
timeout=... | 34,175 |
def save_json(data, filepath: PathLike):
"""Saves a dictionary as a json file"""
with open(filepath, "w") as outfile:
json.dump(data, outfile, indent=3) | 34,176 |
def test_get_common_option_defaults_from_configuration():
"""Defaults should come from configuration file.
"""
defaults = orchestrate.utils.get_common_option_defaults()
expected = dict(
project='gcloud_project',
zone='gcloud_zone',
api_project='config_project',
api_host='config_host',
... | 34,177 |
def ParseCustomLevel(api_version):
"""Wrapper around ParseCustomLevel to accept api version."""
def VersionedParseCustomLevel(path):
"""Parse a YAML representation of custom level conditions.
Args:
path: str, path to file containing custom level expression
Returns:
string of CEL expressio... | 34,178 |
def specMergeMSA(*msa, **kwargs):
"""Returns an :class:`.MSA` obtained from merging parts of the sequences
of proteins present in multiple *msa* instances. Sequences are matched
based on species section of protein identifiers found in the sequence labels.
Order of sequences in the merged MSA will fol... | 34,179 |
def parse(filePath):
"""
Returns a full parsed Maya ASCII file.
:type filePath: str
:rtype: mason.asciiscene.AsciiScene
"""
return asciifileparser.AsciiFileParser(filePath).scene | 34,180 |
def test_records_match_shapes():
"""
Assert that the number of records matches
the number of shapes in the shapefile.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
records = sf.records()
shapes = sf.shapes()
assert len(records) == len(shapes) | 34,181 |
def getSpectrumFromMlinptFolder(inpFolder, fwhm, hv, angle, polarised=None, multEnergiesByMinusOne=True, database=None):
""" Description of function
Args:
inpFolder: (str) Path to folder containing *MLinpt.txt files
fwhm: (float) Full-Width at half maximum for the broadening function
hv: (float) Photon energy... | 34,182 |
def extract_events_from_stream(stream_df, event_type):
""" Extracts specific event from stream.
"""
events = stream_df.loc[stream_df.EventType == event_type][['EventTime', 'Event']]
events_json = events['Event'].to_json(orient="records")
json_struct = json.loads(events_json)
# TODO : get rid of... | 34,183 |
def d_psi(t):
"""Compute the derivative of the variable transform from Ogata 2005."""
t = np.array(t, dtype=float)
a = np.ones_like(t)
mask = t < 6
t = t[mask]
a[mask] = (np.pi * t * np.cosh(t) + np.sinh(np.pi * np.sinh(t))) / (
1.0 + np.cosh(np.pi * np.sinh(t))
)
return a | 34,184 |
def build_environ(request: HTTPRequest, errors: Errors) -> Dict[str, Any]:
"""
参考 https://www.python.org/dev/peps/pep-3333/ 构建 environ
"""
headers = {
f"HTTP_{k.upper().replace('-','_')}": v for k, v in request.header.items()
}
environ = {
# 保持与阿里云函数计算 HTTP 触发器的一致
"fc.con... | 34,185 |
def test_peekleft_after_two_appendleft(deque_fixture):
"""Test peekleft after appending to the left of deque."""
deque_fixture.appendleft(7)
deque_fixture.appendleft(8)
assert deque_fixture.peekleft() == 8 | 34,186 |
def loadPage(url, filename):
"""
作用:根据url发送请求,获取服务器响应文件
url: 需要爬取的url地址
filename : 处理的文件名
"""
print "正在下载 " + filename
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11... | 34,187 |
def get_exporter_class():
"""Returns exporter class based on preferences and support."""
if _use_xlsx() is True:
return XLSXExporter
else:
return CSVExporter | 34,188 |
def get_twitter_token():
"""This is used by the API to look for the auth token and secret
it should use for API calls. During the authorization handshake
a temporary set of token and secret is used, but afterwards this
function has to return the token and secret. If you don't want
to store this in... | 34,189 |
def is_text_serializer(serializer):
"""Checks whether a serializer generates text or binary."""
return isinstance(serializer.dumps({}), str) | 34,190 |
def plot_power(ngroups, mesh_shape, directory, mode="show"):
"""Plot the integrated fission rates from OpenMC and OpenMOC, as well as
the relative and absolute error of OpenMOC relative to OpenMC.
Parameters:
-----------
ngroups: int; number of energy groups
mesh_shape: str; name of the mesh shape
di... | 34,191 |
def glDeleteFramebuffersEXT( baseOperation, n, framebuffers=None ):
"""glDeleteFramebuffersEXT( framebuffers ) -> None
"""
if framebuffers is None:
framebuffers = arrays.GLuintArray.asArray( n )
n = arrays.GLuintArray.arraySize( framebuffers )
return baseOperation( n, framebuffers ) | 34,192 |
def projection_matching(input_model, projs, nside, dir_suffix=None, **kwargs):
"""
Parameters:
-------
input_model: path of input mrc file
projections: numpy array
"""
try:
WD = kwargs['WD']
except KeyError as error:
raise KeyError('lack working directory')
EAs_grid ... | 34,193 |
def backtostr(dayback=1, format="%Y/%m/%d", thedate=date.today()):
"""Print backto datetime in string format."""
return(backto(dayback=dayback, thedate=thedate).strftime(format)) | 34,194 |
def main():
"""Framework for cross test generation and execution.
Builds and executes cross tests from the space of all possible attribute
combinations. The space can be restricted by providing subsets of attributes
to specifically include or exclude.
"""
# pypath is where to find other Subzero python scr... | 34,195 |
def test_two_underscores():
"""escape two or more underscores inside words."""
assert_equal(
GithubMarkdown.gfm('foo_bar_baz'),
'foo\\_bar\\_baz',
) | 34,196 |
def no_conflict_require_POST(f):
"""
Catches resource conflicts on save and returns a 409 error.
Also includes require_POST decorator
"""
@require_POST
@wraps(f)
def _no_conflict(*args, **kwargs):
try:
return f(*args, **kwargs)
except ResourceConflict:
... | 34,197 |
def test_paragraph_series_m_fb_ol_ol_nl_fb():
"""
Test case: Ordered list x2 newline fenced block
"""
# Arrange
source_markdown = """1. 1.
```
foo
```
"""
expected_tokens = [
"[olist(1,1):.:1:3:]",
"[olist(1,4):.:1:6: ]",
"[BLANK(1,6):]",
"[end-olist:::True]",... | 34,198 |
def test_JanusVariableManager_return_type_policy():
# sourcery skip: equality-identity, use-assigned-variable
"""
This checks any return value policies that are not on the default policy
`return_value_policy::automatic`
Reference: <https://pybind11.readthedocs.io/en/stable/advanced/functions.html#r... | 34,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.