content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _previousSibling(self):
"""
Return the previous sibling
NOTE: This is fairly inefficient. The reason that it has
to be done this way is because Text nodes are a subclass of
`unicode` which is an immutable object. This means that
we can't have two references to the same Text object (i.... | 66,900 |
def file_mapper(json_: dict) -> File:
"""
Maps the json file response into a File object.
:param json_: The json obtained from the endpoint call
:type json_: dict
:return: A File instance
:rtype: :class:`vdx_helper.models.File`
"""
return File(
file_hash=json_["file_hash"],
... | 66,901 |
def ledit(shell, path):
""" Edit file in editor. """
shell.localhost.run("vim '%s'" % esc1(path)) | 66,902 |
def will_boom(message: str) -> None:
"""
This task will indirectly raise an exception.
"""
return boom(message) | 66,903 |
def boolean(value):
"""
Translate the given value to a boolean object.
Example:
>>> boolean(True)
True
>>> boolean(0)
False
>>> boolean('false')
False
>>> boolean('yes')
True
"""
if isinstance(value, bool):
return value
... | 66,904 |
def mppe_key_derivation_master_key(password_hash_hash, nt_response):
"""
RFC 3079 MPPE Key Derivation
3.4. Key Derivation Functions
GetMasterKey
:param password_hash_hash:
:param nt_response:
:return: master_key
"""
magic1 = "\x54\x68\x69\x73\x20\x69\x73\x20\x74\x68\x65\x20\x4d\x50\... | 66,905 |
def commutator (proc1, proc2):
"""Returns the commutator of A and B, i.e. [A, B], i.e. A * B * A^-1 * B^-1."""
return proc1 + proc2 + invert_moves(proc1) + invert_moves(proc2) | 66,906 |
def test_PipeJsonRpcSendAsync_3():
"""
Put multiple messages to the loop at once. The should be processed one by one.
"""
n_calls = 0
lock = threading.Lock()
def method_handler1():
nonlocal n_calls
with lock:
n_calls += 1
n_return = n_calls
ttime.... | 66,907 |
def get_phrase_ngrams(span, attrib='words', n_min=1, n_max=1, lower=True):
"""Get the ngrams that are in the Phrase of the given span, not including itself.
Note that if a candidate is passed in, all of its Spans will be searched.
:param span: The Span whose Phrase is being searched
:param attrib: The... | 66,908 |
def bind_floating_ip(floating_ip, check_exit_code=True):
"""Bind ip to public interface"""
_execute("sudo ip addr add %s dev %s" % (floating_ip,
FLAGS.public_interface),
check_exit_code=check_exit_code) | 66,909 |
def readTsv(fileLines, d="\t"):
"""
convenience method for reading TSV file lines into csv.DictReader obj.
"""
reader = csv.DictReader(fileLines, delimiter=d)
return reader | 66,910 |
def dispatch_unit_scada(file):
"""Extract generator dispatch data
Params
------
file : bytes IO object
Zipped CSV file of given MMSDM table
Returns
-------
df : pandas DataFrame
MMSDM table in formatted pandas DataFrame
"""
# Columns to extract
... | 66,911 |
def _get_weights(Y, dist, weights):
"""Get the weights from an array of rankings and distances."""
sample_weight = get_weights(dist, weights)
# Assign a constant value if applying a uniform weighting
# to weigh the samples by the number of available classes
sample_weight = sample_weight if sample_w... | 66,912 |
def irodsObjectStoreIterator(session, store):
"""Generator to yield Objects (e.g. Users) from an IrodsStore."""
for id, data in irodsStoreIterator(session, store):
rec = store._process_data(session, id, data)
obj = store._processRecord(session, id, rec)
yield obj | 66,913 |
def credit(order_number, pnref=None, amt=None):
"""
Return funds that have been previously settled.
:order_number: Order number
:pnref: The PNREF of the authorization transaction to use. If not
specified, the order number is used to retrieve the appropriate transaction.
:amt: A custom ... | 66,914 |
def get_location_data(location_list):
"""iterate through the list of locations and extract data from the API for each one. output the data in json format."""
location_data_json = {}
address = 'http://unlock.edina.ac.uk/ws/search?name=' # address of API
country_code = 'GB'
dups = set([x for x ... | 66,915 |
def config(auth, env):
"""
Create a config file.
"""
if auth:
config_path = Path("./config.json").resolve()
logger.info("Saving config to {}".format(config_path))
json_config = {
"project_id": auth.project_id,
"project_api_key": auth.project_api_key,
... | 66,916 |
def request_string_selection(string_options, dlg_kind="livemodal",
dlg_klass=None, **selector_traits):
""" Dialog to select a string among a list of options.
Parameters
----------
string_options : list
List of string values to choose from. Passed as the `string_opti... | 66,917 |
def kerberos_ccache_init(principal, keytab_file, ccache_file=None):
"""
Checks whether kerberos credential cache has ticket-granting ticket that is valid for at least
an hour.
Default ccache is used unless ccache_file is provided. In that case, KRB5CCNAME environment
variable is set to the value of... | 66,918 |
def index(args):
"""Mange the run index.
"""
from . import index_impl
index_impl.main(args) | 66,919 |
def extract_files(filename, file_type='target_files', tmp_folder=None, clean_tmp=False):
""" Read files from descriptor folder.
.. codeauthor:: Angelo Ziletti <angelo.ziletti@gmail.com>
"""
logger.debug('Loading file {0}'.format(filename))
if clean_tmp:
clean_folder(tmp_folder)
arch... | 66,920 |
def make_estimator(hparams):
"""Creates a TPU Estimator."""
generator = _get_generator(hparams)
discriminator = _get_discriminator(hparams)
if hparams.tpu_params.use_tpu_estimator:
config = est_lib.get_tpu_run_config_from_hparams(hparams)
return est_lib.get_tpu_estimator(generator, discriminator, hpara... | 66,921 |
def predict(model, data, batch, org_shape, rate, gpu):
"""
推論実行メイン部
[in] model: 推論実行に使用するモデル
[in] data: 分割(I.cnv.split)されたもの
[in] batch: バッチサイズ
[in] org_shape: 分割前のshape
[in] rate: 出力画像の拡大率
[in] gpu: GPU ID
[out] img: 推論実行で得られた生成画像
"""
# d... | 66,922 |
def describe_client_properties(ResourceIds=None):
"""
Retrieves a list that describes one or more specified Amazon WorkSpaces clients.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_client_properties(
ResourceIds=[
'string',
]
... | 66,923 |
def _gen_bids_layout(
bids_dir,
derivatives,
pybids_database_dir,
pybids_reset_database,
pybids_config=None,
):
"""Create (or reindex) the BIDSLayout if one doesn't exist,
which is only saved if a database directory path is provided
"""
# Set db dir to None (otherwise saves to paren... | 66,924 |
def plot_regime_diagram_background_L19(
ax=None,
):
"""Plot the background of the reegime diagram
in Li et al., 2019
:ax: (matplotlib.axes, optional) axis to plot figure on
"""
if ax is None:
ax = plt.gca()
# range of power
xpr = [-1, 1]
ypr = [-3, 3]
# r... | 66,925 |
def grep_candidate_papers(url):
"""scrape first 10 papers and choose one
:param url:
:return: target paper information (title, writer, year, citations, url, paper_id, snippet)
"""
html_doc = requests.get(url).text
soup = BeautifulSoup(html_doc, "html.parser")
title_list, url_list = get_titl... | 66,926 |
async def test_calc_metrics_prs_all_time(client, headers):
"""https://athenianco.atlassian.net/browse/ENG-116"""
devs = ["github.com/vmarkovtsev", "github.com/mcuadros"]
for_block = {
"with": {
"author": devs,
"merger": devs,
"releaser": devs,
"comment... | 66,927 |
def atan(x: float) -> float:
"""
Return the arc tangent of ``x``, in radians.
"""
... | 66,928 |
def output_pil (im, fn, format='PNG'):
"""
Output an image to a file using PIL.
Arguments:
im image to be output
fn name of the file to be written
format the format of the file to be written (default: 'PNG')
"""
import Image
ny, nx, nc = sizes (im)
bim = im.astype ('B')... | 66,929 |
def friendly_filename(filename):
"""
Creates a 'friendly' filename based on the given filename. The
transformation process is as follows:
- Get everything after the last slash
- Remove the extension
- Convert slashes, underscores, bracket, pound to space
- Convert consecutive spaces to just ... | 66,930 |
def has_double_letters(string):
"""Tests if a string contains forbidden text"""
return check_for_contents(string, DOUBLE_LETTERS) | 66,931 |
def preprocess_images_from_directory_val_separate(train_dir_path, test_dir_path,
val_dir_path,
label_mode, img_size, seed=45,
batch_size=32, val_split=0.2, ):
"""
... | 66,932 |
def ensure_same_dims(a, b):
"""Checks if the ``a`` and ``b`` image objects have the same number
of dimensions.
Parameters
==========
a: ``casacore.images.image.image`` object
In-memory CASAImage
b: ``casacore.images.image.image`` object
In-memory CASAImage
Raises
... | 66,933 |
def test__get_transparent_cmap() -> None:
"""
Test `hsr4hci.plotting.get_transparent_cmap`.
"""
cmap = get_transparent_cmap('red')
assert cmap.name == 'from_list'
assert cmap.colors == [(0, 0, 0, 0), 'red'] | 66,934 |
def tosVersion(file):
"""Display TOS version and date.
"""
rom = open(file, 'rb').read(32)
try:
lang = ("US", "German", "French", "UK", "Spanish", "Italian",
"Swedish", "Swiss French", "Swiss German", "Turkish",
"Finnish", "Norwegian", "Danish", "Saudi", "Dutch")[... | 66,935 |
async def _async_setup_entity(hass, config, async_add_entities, connection):
"""Set up the Node-RED button."""
async_add_entities([NodeRedButton(hass, config, connection)]) | 66,936 |
def transform_matrix_for_non_uniform_scale(
x_factor, y_factor, z_factor, allow_flipping=False, ret_inverse_matrix=False
):
"""
Create a transformation matrix that scales by the given factors along
`x`, `y`, and `z`.
Forward:
[[ s_0, 0, 0, 0 ],
[ 0, s_1, 0, 0 ],
[ ... | 66,937 |
def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):
"""
Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wy + b)
z = t * g(Wy + b) + (1 - t) * y
where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
"""
with tf.variable_sco... | 66,938 |
def test_load_configuration_recorders(neo4j_session, *args):
"""
Ensure that expected configuration recorders get loaded with their key fields.
"""
data = tests.data.aws.config.LIST_CONFIGURATION_RECORDERS
cartography.intel.aws.config.load_configuration_recorders(
neo4j_session,
data... | 66,939 |
def test_labels_added(repo, pull_num, labels, session):
"""
Test whether the labels were added correctly (permissions etc.)
:param repo: repository
:param pull_num: number of pull request
:param labels: labels that were added
:param session: open github session
:type repo... | 66,940 |
def test_create_from_utm_params___missing_params():
"""Check failure on missing medium and content."""
user = User.objects.create(username="Bob")
utm_params = {"utm_source": "source"}
with pytest.raises(ValueError):
LeadSource.objects.create_from_utm_params(user, utm_params)
utm_params = {"... | 66,941 |
def final_html_output(df: pd.DataFrame) -> str:
"""Get final html output
Args:
df: dataframe object
Returns:
html string
"""
with open("./assets/index.html") as file:
html_string = file.read()
if not os.path.exists("build"):
os.mkdir("build")
with open("bui... | 66,942 |
def run_tests(system, timeout):
"""
Builds and runs all tests for all architectures for a given system
"""
print('<testsuite>')
for arch in ARCHITECTURES:
run_arch_tests(arch, system, timeout)
print('</testsuite>') | 66,943 |
async def provider(cid: int) -> Dict[str, Any]:
"""获取漫画章节."""
link = f"https://www.manhuagui.com/comic/{cid}/"
async with HTTPClient() as client:
response = await client.get(link)
dom = PyQuery(response.text)
title = dom(".book-title h1").text()
description = dom("#intro-cut").text()
... | 66,944 |
def causal_numerator(qs, ks, vs):
"""Computes not-normalized FAVOR causal attention A_{masked}V.
Args:
qs: query_prime tensor of the shape [L,B,H,M].
ks: key_prime tensor of the shape [L,B,H,M].
vs: value tensor of the shape [L,B,H,D].
Returns:
Not-normalized FAVOR causal attention A_{masked}V.
... | 66,945 |
def uninstall_daemon():
"""
TODO:
"""
remove_config() | 66,946 |
def _get_key_by_keyid(keyid):
"""Get a key via HTTPS from the Ubuntu keyserver.
Different key ID formats are supported by SKS keyservers (the longer ones
are more secure, see "dead beef attack" and https://evil32.com/). Since
HTTPS is used, if SSLBump-like HTTPS proxies are in place, they will
imper... | 66,947 |
def lt(t):
"""
Turns left for t seconds.
Example:
import AOLMERobots as gopi
gopi.lt(1)
"""
if DEBUG:
print("\tTurning left for",t,"sec")
dexgp = gopigo3.GoPiGo3()
for i in range(0, int(t*100+1)):
dexgp.set_motor_power(dexgp.MOTOR_LEFT, 0)
dexgp.set_motor_pow... | 66,948 |
def token_to_char_offset(e, candidate_idx, token_idx):
"""Converts a token index to the char offset within the candidate."""
c = e["long_answer_candidates"][candidate_idx]
char_offset = 0
for i in range(c["start_token"], token_idx):
t = e["document_tokens"][i]
if not t["html_token"]:
token = t["to... | 66,949 |
def FixedRateBondAddRedemption(builder, redemption):
"""This method is deprecated. Please switch to AddRedemption."""
return AddRedemption(builder, redemption) | 66,950 |
def proto_dict(message,
including_default_value_fields=False,
preserving_proto_field_name=True):
"""Convert a proto message to a standard dict object"""
return json_format.MessageToDict(
message,
including_default_value_fields=including_default_value_fields,
... | 66,951 |
def _coalescer_cleanup(temp_dir: TemporaryDirectory,
tmpfile):
"""Cleanup the test dir and such
:param temp_dir: TemporaryDirectory, the temp parquet dir
:param tmpfile: tempfile._TemporaryFileWrapper, the temp config file
:returns: Nothing
:rtype: None
"""
assert(is... | 66,952 |
def test_backend_initialisation() -> None:
"""Test that we can initialise an SBArduinoHardwareBackend."""
backend = make_backend()
assert backend.serial_port == "COM0"
assert isinstance(backend._serial, SBArduinoSerial)
assert all(
pin.mode is GPIOPinMode.DIGITAL_INPUT for pin in backend._di... | 66,953 |
def get_arrow(delta):
"""Create glyphicon chevron
:param delta: change in rankings from previous week
:return: html code for arrow
"""
# Define html snippets to build arrow code
snu = ' <span class="text-success">'
snd = ' <span class="text-danger">'
ns = '</span>'
up = '<span cla... | 66,954 |
def GetHighlightColour():
"""Get the default highlight color
@return: wx.Colour
"""
if wx.Platform == '__WXMAC__':
if CARBON:
if hasattr(wx, 'MacThemeColour'):
color = wx.MacThemeColour(Carbon.Appearance.kThemeBrushFocusHighlight)
return color
... | 66,955 |
def plot_bins(X, y, splits, space="%"):
"""
Plots target rates & counts for bins of splits
Numeric column, split by 'splits' thresholds
Categorical column, split by category
Args:
X (dataframe): columns to be plotted
y (target): target series
splits (dictionary): splits t... | 66,956 |
def different_ways_memoization(n):
"""Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[0] = 1
def different_ways_memoization_helper(k):
if k < 0:
return 0
if d[k] == 0:
d[k] = differen... | 66,957 |
def get_mask_voxels(mask):
"""
Compute x,y,z coordinates of a binary mask
Input:
- mask: binary mask
Output:
- list of tuples containing the (x,y,z) coordinate for each of the input voxels
"""
indices = np.stack(np.nonzero(mask), axis=1)
indices = [tuple(idx) for idx in indi... | 66,958 |
def __virtual__():
"""
Only make this state available if the azurearm_resource module is available.
"""
if "azurearm_resource.resource_group_check_existence" in __salt__:
return __virtualname__
return (False, "azurearm_resource module could not be loaded") | 66,959 |
def test_link_reference_definitions_184():
"""
Test case 184: (part 2) However, it can directly follow other block elements, such as headings and thematic breaks, and it need not be followed by a blank line.
"""
# Arrange
source_markdown = """[foo]: /url
bar
===
[foo]"""
expected_tokens = [
... | 66,960 |
def video_list(request):
"""
*/entry/videos*
The entry interface's videos list. This view lists all videos,
their description, and allows you to click on them to view/edit the
video.
"""
message = ""
if request.GET.get('success') == 'true':
message = "Video deleted successfully... | 66,961 |
def check_status(r: Response) -> Response:
"""Check the status code of a response and return it."""
if not r.status_code == codes.ok:
if r.url.startswith(BASE_ENDPOINT) and not r.json()["success"]:
errors = "\n".join(f"{err['code']}: {err['message']}" for err in r.json()["errors"])
... | 66,962 |
def get_execution_platform(command, filename):
"""
<Purpose>
Returns the execution platform based on a best-guess approach using
the specified command, as well as the a file's extension. The
command takes precedence over the file extension. If the extension
is not recognized, then it will be assum... | 66,963 |
def test_ass_script_info_emits_change_event() -> None:
"""Test that changing script info emits a change event."""
subscriber = Mock()
obj = AssScriptInfo()
obj.changed.subscribe(subscriber)
obj["key"] = "value"
subscriber.assert_called_once() | 66,964 |
def _binary_to_string_handle(handle):
"""Treat a binary (bytes) handle like a text (unicode) handle (PRIVATE)."""
try:
# If this is a network handle from urllib,
# the HTTP headers may tell us the encoding.
encoding = handle.headers.get_content_charset()
except AttributeError:
... | 66,965 |
def read(path):
"""读取路径下的文件"""
user_id = os.environ.get("JUPYTERHUB_USER") or ""
if not path.startswith("/"):
path = rela2abs(path)
with get_engine().begin() as db:
src_file = get_file(
db,
user_id,
path,
True,
crypto.NoEncrypt... | 66,966 |
def get_cardlist_from_filename(filename) -> CardList:
""" Returns pandas database with parsed filename
File should contain list of cards with number and card names
"""
_, file_extension = os.path.splitext(filename)
if file_extension == '.cod':
cardlist = _parse_cod(filename)
... | 66,967 |
def list_of_combs(arr):
"""returns a list of all subsets of a list"""
combs = []
for i in range(0, len(arr) + 1):
listing = [list(x) for x in combinations(arr, i)]
combs.extend(listing)
return combs | 66,968 |
def model_details(model_id):
"""
Summarize the model.
Parameters
----------
model_id: str
A valid id for a model in BiGG.
"""
response = requests.get(BASE_URL + "models/%s" % model_id)
response.raise_for_status()
return response.json() | 66,969 |
def appearance_app_templates(context, template_name):
"""
Fetch the app templates for the requested `template_name`, render it with
the current `request` from the `context`, and cache it for future use
unless the template has the no caching comment.
"""
result = []
for app in apps.get_app_c... | 66,970 |
def unique_addons(addons_list):
"""Validate that an add-on is unique."""
single = set(addon[ATTR_SLUG] for addon in addons_list)
if len(single) != len(addons_list):
raise vol.Invalid("Invalid addon list on snapshot!")
return addons_list | 66,971 |
def signals():
"""
Use this decorator to identify the enumeration within your observable class that defines the class' signals.
"""
# We need an inner function that actually adds the logger instance to the class.
def add_signals(cls):
# If the class doesn't already extend SignalsEnum...
... | 66,972 |
def mod(x):
"""
Devuelve el modulo del vector x
"""
s = 0
for c in x:
s += c**2
return sqrt(s) | 66,973 |
def calculate_heat_capacity(thm_dstr, temp):
""" Calculate the Heat Capacity [Cp(T)] of a species using the
coefficients of its NASA polynomial
"""
cfts = _coefficients_for_specific_temperature(thm_dstr, temp)
if cfts is not None:
heat_capacity = (
cfts[0] +
(cft... | 66,974 |
async def get_provider_icons(mass: MusicAssistant) -> Dict[str, str]:
"""Get Provider icons as base64 strings."""
return {
prov.id: await get_provider_icon(prov.id)
for prov in mass.get_providers(include_unavailable=True)
} | 66,975 |
def test_OneHotEncode_dtype():
"""Test that OneHotEncode() returns a float array."""
data = data_generators.OneHotEncode(np.array([0, 1, 2]), 3)
assert data.dtype == np.float64 | 66,976 |
def take(a, indices, axis=None, out=None, mode='raise'):
"""
Take elements from an array along an axis.
When axis is not None, this function does the same thing as "fancy"
indexing (indexing arrays using arrays); however, it can be easier to use
if you need elements along a given axis. A call such ... | 66,977 |
def _create_xclbin(mem_dict):
"""Create an XCLBIN file containing the specified memories
"""
import tempfile
import subprocess
import json
with tempfile.TemporaryDirectory() as td:
td = Path(td)
(td / 'metadata.xml').write_text(BLANK_METADATA)
(td / 'mem.json').write_tex... | 66,978 |
def GenAnkiFromAllYamlTLM(args):
""" genearte ANKI notes from all YAML files"""
logging.info("processing YAML lesson model for all YAML files...")
logging.info("-output is ignored when YAML TLM file is input.")
md = MultiChineseDict()
for yaml_fn in args.input_yaml_tlm:
GenAnkiFromOneYamlTLM... | 66,979 |
def run(argv=None, save_main_session=True):
"""Main entry point; defines and runs the wordcount pipeline."""
parser = argparse.ArgumentParser()
#1 Replace your hackathon-edem with your project id
parser.add_argument('--input_topic_park',
dest='input_topic_park',
... | 66,980 |
def _process_image_files_batch(dataframe, thread_index, ranges, name, num_shards, label_map):
"""adapted from models.research.inception.inception.data.build_imagenet_data
TODO: make sure this docstring looks okay
Processes and saves list of images as TFRecord in 1 thread.
Args:
dataframe: pd.DataF... | 66,981 |
def get_random_string():
""" generates a random string """
random_string = ''.join(
[random.choice(string.ascii_letters + string.digits) for n in range(32)]
)
return random_string | 66,982 |
def p_top_fieldlist(p):
"""topcmd : TOP fieldlist
| SITOP fieldlist"""
p[0] = ParseTreeNode('COMMAND', raw=p[1])
p[0].add_children(p[2].children) | 66,983 |
def calc_slope_components(dem, dx):
"""Calculate finite slopes."""
# sx,sy = calcFiniteDiffs(elevGrid,dx)
# calculates finite differences in X and Y direction using the
# 2nd order/centered difference method.
# Applies a boundary condition such that the size and location
# of the grids in is t... | 66,984 |
def merge_neighbor_dims(x, axis=0):
"""Merge neighbor dimension of x, start by axis"""
if len(x.get_shape().as_list()) < axis + 2:
return x
shape = shape_list(x)
shape[axis] *= shape[axis+1]
shape.pop(axis+1)
return tf.reshape(x, shape) | 66,985 |
def post_transfer(from_address: Union[UInt160, None], to_address: Union[UInt160, None], amount: int, data: Any):
"""
Checks if the one receiving NEP17 tokens is a smart contract and if it's one the onPayment method will be called
:param from_address: the address of the sender
:type from_address: UInt16... | 66,986 |
def matrix_transpose(matrix):
"""
function to transpose a matrix
"""
return [[row[i] for row in matrix] for i in range(len(matrix[0]))] | 66,987 |
def from_xml(df, column):
"""
Takes a dataframe with XML-encoded bundles in the given column and returns
a Java RDD of Bundle records. Note this
RDD contains Bundle records that aren't serializable in Python,
so users should use this class as merely a parameter to other methods
in this module, l... | 66,988 |
def has_s_dismantlable_vertex(graph):
"""Returns whether a graph has s-dismantlable vertices
Args:
graph (networkx.classes.graph.Graph): graph
Returns:
If the graph has dominated vertices, returns a list which only element
is the first s-dismantlable vertex. Otherwise, return False
... | 66,989 |
def write_data_to_file(file: str, data: str) -> None:
"""
读取文件,并将数据插入第一行
:param file: 读取文件路径
:param data: 插入数据
:return:
"""
with open(file, "r+", encoding="u8") as fp:
tmp_data = fp.read() # 读取所有文件, 文件太大时不用使用此方法
fp.seek(0) # 移动游标
fp.write(data + "\n" + tmp_data) | 66,990 |
def evaluate(model, eval_fn, data_loader, batch_axis=0, max_steps=None, verbose=True, print_every=10):
"""Computes the loss and accuracy on the given dataset in test mode.
Example of how to use the evaluation function:
```
def my_eval_fn(model, x, y):
return evaluate_on_batch(model, x, y, c... | 66,991 |
def from_auto_ml(model, shape=None, dtype="float32", func_name="transform"):
"""
Import scikit-learn model to Relay.
"""
try:
import sklearn # pylint: disable=unused-import
except ImportError as e:
raise ImportError("Unable to import scikit-learn which is required {}".format(e))
... | 66,992 |
def restart_cluster(body, status, name, namespace, memo: kopf.Memo, **kwargs):
"""On increment of status.autoscalerRetries, restart Ray processes.
Increment of autoscalerRetries happens when cluster's monitor fails,
for example due to Ray head failure.
"""
# Don't act on initialization of status.au... | 66,993 |
def con_str(image):
"""Doing contrast stretch and count the time for processing
Args:
image: input image data (should be ndarray)
returns:
img_str: image after contrast stretch
time_process: time for doing the processing
"""
start = timeit.default_timer()
img_str = ski.... | 66,994 |
def text():
"""Returns text equivalent of the W3C text"""
return {
"@context": "http://www.w3.org/ns/anno.jsonld",
"type": "Annotation",
"body": {
"creator": "user",
"type": "TextualBody",
"value": "string"
},
"generator": {
... | 66,995 |
def run(
input_image_path: Path,
output_directory: Path,
identifier: str,
scale: float = None,
start_column: int = 0,
show: bool = False,
show_step: bool = False
):
"""Digitise *a single* eeg trace.
input_image_path:
Path to segmented EEG trace.
output_directory:
... | 66,996 |
def load_deputati(legislatura):
"""
Carica lista dei deputati
NOTA: Include anche i deputati che si sono dimessi e quindi raggiunge
un numero totale maggiore di 630.
:param legislatura: url identificativo della legislatura.
:return: lista di deputati con nome e cognome, ordinata per cogn... | 66,997 |
def create_connection(graph, node1, node2, linktype, propertydict=None, allow_dup=False):
"""
:param graph:
:param node1:
:param node2:
:param linktype:
:param propertydict:
:return:
"""
graph = graphs[graph]
anode = node1
bnode = node2
if isinstance(node1, dict):
... | 66,998 |
def download_log(request, log_id):
"""
"""
user = request.user
# Check that the user is allowed to download the log
if not (user.is_authenticated and (user.has_perm("jobs.view_joblog"))):
return HttpResponse("Not authorized to view logs", status=401)
try:
log = JobLog.objects.g... | 66,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.