content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def process_mailbox(M):
"""
Dump all emails in the folder to files in output directory.
"""
rv, data = M.search(None, "ALL")
if rv != 'OK':
print("No messages found!")
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
... | 5,323,800 |
def mkdir_p(path):
"""mkdir_p attempts to get the same functionality as mkdir -p
:param path: the path to create.
"""
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
bot.error("Error creating p... | 5,323,801 |
def sync_local(operations, sync_dir):
""" Transfer snapshots to local target """
trace = operations.trace
# find out what kind of snapshots exist on the remote host
targetsnaps = set(operations.listdir_path(sync_dir))
localsnaps = set(operations.listdir())
if len(localsnaps) == 0:
# no... | 5,323,802 |
def remove_element(list, remove):
"""[summary]
Args:
list ([list]): [List of objects]
remove ([]): [What element to remove]
Returns:
[list]: [A new list where the element has been removed]
"""
for object in list:
if object._id == remove[0]:
list.remove(o... | 5,323,803 |
def warmup_cosine_decay_schedule(
init_value: float,
peak_value: float,
warmup_steps: int,
decay_steps: int,
end_value: float = 0.0
) -> base.Schedule:
"""Linear warmup followed by cosine decay.
Args:
init_value: Initial value for the scalar to be annealed.
peak_value: Peak value for sc... | 5,323,804 |
def download_mission(vehicle):
"""
Download the current mission from the vehicle.
"""
cmds = vehicle.commands
cmds.download()
cmds.wait_ready() | 5,323,805 |
def test_add_list_returns_unprocessable_entity(client, token):
"""Check whether an UNPROCESSABLE ENTITY response is returned when POST body is invalid"""
res = client.post(
'/lists',
json={},
headers={'Authorization': f'Bearer {token}'},
allow_redirects=True
)
assert res... | 5,323,806 |
def test_input_json(dict_srv):
#Description
"""Test the entries in the json file.
"""
dict_srv_template = {"host": "", \
"user": "", \
"password": "", \
"port": "", \
"http_interface": "", \
"http_port": "", \
"servername": "", \
"serveradmin": "", \
"documentroot": "", \
"f... | 5,323,807 |
def save_url(url, path, filename, session):
"""
Args:
session: requests.Session()
url: str
path: str
filename: str
Returns: None, file written to path+filename
"""
result = session.get(url)
if result.status_code == 200:
f = open(path + filename, 'wb')
... | 5,323,808 |
def cleanup():
"""
deletes all primaryFsets that matches pattern pvc-
used for cleanup in case of parallel pvc.
Args:
None
Returns:
None
Raises:
None
"""
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
get_link = f'https://{test["guiHost"]... | 5,323,809 |
def plot_corr(data, figsize=None, xrot=0, yrot=0):
"""
corr_mat: Correlation matrix to visualize
figsize: Overall figure size for the overall plot
xrot: (Default = 0) Rotate x-labels
yrot: (Default = 0) Rotate y-labels
"""
fig, axis = plt.subplots(1, 1, figsize=figsize)
corr_mat = data.c... | 5,323,810 |
def uninstall():
"""Remove the import and regex compile timing hooks."""
__builtins__['__import__'] = _real_import
re._compile = _real_compile | 5,323,811 |
def __transform_template_to_graph(j):
"""
Transforms the simple format to a graph.
:param j:
:return:
"""
g = nx.DiGraph()
for a in j["nodes"]:
g.add_node(a[0], label = a[1], id = str(uuid.uuid4()))
for e in j["edges"]:
g.add_edge(e[0], e[1], label = e[2])
return g | 5,323,812 |
def datetime_to_string(dt):
"""
Convert a datetime object to the preferred format for the shopify api. (2016-01-01T11:00:00-5:00)
:param dt: Datetime object to convert to timestamp.
:return: Timestamp string for the datetime object.
"""
if not dt:
return None
if not isinstance(dt, d... | 5,323,813 |
def names(package: str) -> List[str]:
"""List all plug-ins in one package"""
_import_all(package)
return sorted(_PLUGINS[package].keys(), key=lambda p: info(package, p).sort_value) | 5,323,814 |
def _get_inner_text(html_node):
"""Returns the plaintext of an HTML node.
This turns out to do exactly what we want:
- strips out <br>s and other markup
- replace <a> tags with just their text
- converts HTML entities like and smart quotes into their
unicode equivalents... | 5,323,815 |
def test_hbonds():
"""H-Bonds test"""
hbonds_count = [hbonds(rec, mol)[2].sum() for mol in mols]
assert_array_equal(hbonds_count,
[6, 7, 5, 5, 6, 5, 6, 4, 6, 5, 4, 6, 6, 5, 8, 5, 6, 6,
6, 7, 6, 6, 5, 6, 7, 5, 5, 7, 6, 6, 7, 6, 6, 6, 6, 6,
... | 5,323,816 |
def get_all_commands() -> Iterable[Type[Cog]]:
"""
List all applications.
"""
loader = pkgutil.get_loader('figtag.apps')
filename = cast(Any, loader).get_filename()
pkg_dir = os.path.dirname(filename)
for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):
importlib.impo... | 5,323,817 |
def zern_normalisation(nmodes=30):
"""
Calculate normalisation vector.
This function calculates a **nmodes** element vector with normalisation constants for Zernike modes that have not already been normalised.
@param [in] nmodes Size of normalisation vector.
@see <http://research.opt.indiana.edu/Library/VSIA/VSI... | 5,323,818 |
def sample_without_replacement(n, N, dtype=np.int64):
"""Returns uniform samples in [0, N-1] without replacement. It will use
Knuth sampling or rejection sampling depending on the parameters n and N.
.. note::
the values 0.6 and 100 are based on empirical tests of the
functions and would n... | 5,323,819 |
def bustypes(bus, gen):
"""Builds index lists of each type of bus (C{REF}, C{PV}, C{PQ}).
Generators with "out-of-service" status are treated as L{PQ} buses with
zero generation (regardless of C{Pg}/C{Qg} values in gen). Expects C{bus}
and C{gen} have been converted to use internal consecutive bus numb... | 5,323,820 |
def update_and_return_dict(
dict_to_update: dict, update_values: Union[Mapping, Iterable[Tuple[Any, Any]]]
) -> dict:
"""Update a dictionary and return the ref to the dictionary that was updated.
Args:
dict_to_update (dict): the dict to update
update_values (Union[Mapping, Iterable[Tuple[An... | 5,323,821 |
def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
# In order to be consistent, always selects the minimum key
... | 5,323,822 |
def load(*path: str):
"""
Load multiple instances of fruit configurations into the current running instance of fruit.
Parameters
----------
*path: str
List of paths to load
"""
# TODO: Implement loading of multiple fruit configs
# TODO: Add load local option
for each_path i... | 5,323,823 |
def test_datetime():
"""Test serialization of datetime.
Procedure:
- Create a new serializer.
- Create a datetime object in proto for following cases.
* Without timezone.
* With timezone.
- Set values for hours, minutes and seconds.
- Set values for year, ... | 5,323,824 |
def main(event, context):
"""一个对时间序列进行线性插值的函数, 并且计算线性意义上的可信度。
"""
timeAxis = event["timeAxis"]
valueAxis = event["valueAxis"]
timeAxisNew = event["timeAxisNew"]
reliable_distance = event["reliable_distance"]
timeAxis = [totimestamp(parser.parse(i)) for i in timeAxis]
timeAxisNew = [... | 5,323,825 |
def Addon_Info(id='',addon_id=''):
"""
Retrieve details about an add-on, lots of built-in values are available
such as path, version, name etc.
CODE: Addon_Setting(id, [addon_id])
AVAILABLE PARAMS:
(*) id - This is the name of the id you want to retrieve.
The list of built in id's you can u... | 5,323,826 |
def _hash_string_to_color(string):
"""
Hash a string to color (using hashlib and not the built-in hash for consistency
between runs)
"""
return COLOR_ARRAY[
int(hashlib.sha1(string.encode("utf-8")).hexdigest(), 16) % len(COLOR_ARRAY)
] | 5,323,827 |
def get_build(id):
"""Show metadata for a single build.
**Example request**
.. code-block:: http
GET /builds/1 HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 367
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:2... | 5,323,828 |
def get_unity_snapshotschedule_parameters():
"""This method provide parameters required for the ansible snapshot
schedule module on Unity"""
return dict(
name=dict(type='str'),
id=dict(type='str'),
type=dict(type='str', choices=['every_n_hours', 'every_day',
... | 5,323,829 |
def create_bootloader_win(interpreter_zip, executable, argv):
"""
Prepares executable for execution on target machine. Appends client code to `interpreter_zip` archive. Embeds new
archive into `executable`.
:param interpreter_zip: Zip file containing python runtime, stdlib and essential dependencies.
... | 5,323,830 |
def gaussian_kernel(X, kernel_type="gaussian", sigma=3.0, k=5):
"""gaussian_kernel: Build an adjacency matrix for data using a Gaussian kernel
Args:
X (N x d np.ndarray): Input data
kernel_type: "gaussian" or "adaptive". Controls bandwidth
sigma (float): Scalar kernel bandwidth
k... | 5,323,831 |
def get_all_camera_shapes(full_path=True):
"""
Returns all cameras shapes available in the current scene
:param full_path: bool, Whether tor return full path to camera nodes or short ones
:return: list(str)
"""
return maya.cmds.ls(type='camera', long=full_path) or list() | 5,323,832 |
def CreateVGGishNetwork(hop_size=0.96): # Hop size is in seconds.
"""Define VGGish model, load the checkpoint, and return a dictionary that points
to the different tensors defined by the model.
"""
vggish_slim.define_vggish_slim()
checkpoint_path = 'vggish_model.ckpt'
vggish_params.EXAMPLE_HOP_SECONDS = h... | 5,323,833 |
def create_self_signed_cert():
""" Generates self signed SSL certificate. """
# Creates key pair.
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
# Creates self-signed certificate.
cert = crypto.X509()
cert.get_subject().C = "US"
cert.get_subject().ST = "New York"
cert.get_... | 5,323,834 |
def _inserir_dados() -> None:
"""Estrutura de Formulário para inserir novos dados de turno para o Banco de Dados.
"""
# Header
st.header("Inserir Dados")
col_shift, col_empty = st.columns([1,5])
with col_shift:
st.selectbox(label="Turno: ", options=["Selecione", "A", "B", "C"], key="s... | 5,323,835 |
def ping_observing_task(ext_io_connection, ping_ip):
"""
Here external-IO connection is abstract - we don't know its type.
What we know is just that it has .moler_connection attribute.
"""
logger = logging.getLogger('moler.user.app-code')
conn_addr = str(ext_io_connection)
# Layer 2 of Mole... | 5,323,836 |
def YumInstall(vm):
"""Installs the php package on the VM."""
_Install(vm) | 5,323,837 |
def create_directory_structure():
"""Generates the output mod directory structure
Raises:
If fails to create directory
"""
def ensure_directory(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
ens... | 5,323,838 |
def polyMergeFacetCtx(q=1,e=1,anq=1,ex=1,i1="string",i2="string",i3="string",im=1,n="string",pv=1,rs=1,tnq=1,cch=1,ch=1,ff="int",mm="int",nds="int",sf="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/polyMergeFacetCtx.html
-----------------------------------------
polyMergeF... | 5,323,839 |
def display_missing_info_OWNERS_files(stats, num_output_depth):
"""Display OWNERS files that have missing team and component by depth.
OWNERS files that have no team and no component information will be shown
for each depth level (up to the level given by num_output_depth).
Args:
stats (dict): The statist... | 5,323,840 |
def test_invalid_token(request, login, navigator, access_token):
"""
Send request via API docs `Authentication Providers Admin Portal List` endpoint
should return status code 200 for valid access token and 403 for invalid one.
"""
api_docs = navigator.navigate(APIDocsView)
token = request.getfix... | 5,323,841 |
def estimate_mpk_parms_1d(
pk_pos_0, x, f,
pktype='pvoigt', bgtype='linear',
fwhm_guess=0.07, center_bnd=0.02
):
"""
Generate function-specific estimate for multi-peak parameters.
Parameters
----------
pk_pos_0 : TYPE
DESCRIPTION.
x : TYPE
DESCRIP... | 5,323,842 |
def raise_(exc):
""" Raise provided exception.
Just a helper for raising exceptions from lambdas. """
raise exc | 5,323,843 |
async def _parse_collection_from_search(
request: Request,
) -> Tuple[Optional[str], Optional[str]]:
"""
Parse the collection id from a search request.
The search endpoint is a bit of a special case. If it's a GET, the collection
and item ids are in the querystring. If it's a POST, the collection a... | 5,323,844 |
def make_cnf_clauses_by_group(N_, board_group, varboard_group):
"""
:param board_group: e.g. a row of sudoku board, of shape (M...)
:param varboard_group: e.g. a row of sudoku variable id,
of shape (M..., N_)
"""
cclauses_local = []
board_group = board_group.reshape(-1)
varboard_g... | 5,323,845 |
def cacheFeatures():
"""
Utility function to get training data and parse into desired format writing it to file.
Writes to file:
Raw data converted to feature vector and its corresponding labelling yTr
"""
f = open(TRAINING_LOCATION)
a = f.readlines()
data = []
feature_vector = []
... | 5,323,846 |
def get_operations(
archive_action: str, archive_type: str, compression_type: str
) -> Tuple[Operation]:
"""
A function to fetch relevant operations based on type of archive
and compression if any.
"""
operations = {
"archive_ops": {
"zip": {
"extract": extrac... | 5,323,847 |
def import_spyview_dat(data_dir, filename):
"""
Returns a np.array in the same shape as the raw .dat file
"""
with open(os.path.join(data_dir, filename)) as f:
dat = np.loadtxt(f)
return dat | 5,323,848 |
def Norm(norm, *args, **kwargs):
"""
Return an arbitrary `~matplotlib.colors.Normalize` instance. Used to
interpret the `norm` and `norm_kw` arguments when passed to any plotting
method wrapped by `~proplot.axes.cmap_changer`. See
`this tutorial \
<https://matplotlib.org/tutorials/colors/colormapnor... | 5,323,849 |
def run_trajectory(
model, time_stop, time_step, initial_state,
seed, n_points=500, docker=None):
"""
Run one trajectory using the given model and initial state
Parameters
----------
model: str
smoldyn model description
time_stop: float
Simulation duration
ti... | 5,323,850 |
def get_project_root_dir() -> Path:
"""
Gets the Root path of Project
Returns:
Path: of Root project
"""
root_path = _get_script_file()
return root_path.parent | 5,323,851 |
def get_deployment_statuses() -> Dict[str, DeploymentStatusInfo]:
"""Returns a dictionary of deployment statuses.
A deployment's status is one of {UPDATING, UNHEALTHY, and HEALTHY}.
Example:
>>> from ray.serve.api import get_deployment_statuses
>>> statuses = get_deployment_statuses() # doctest: +... | 5,323,852 |
def dumps_tikz(g, scale='0.5em'):
"""Return TikZ code as `str` for `networkx` graph `g`."""
s = []
s.append(padding_remove(r"""
\begin{{tikzpicture}}[
signal flow,
pin distance=1pt,
label distance=-2pt,
x={scale}, y={scale},
baseline=(current bounding box.center),
]""").format(scale=scale))
... | 5,323,853 |
def drawModel(ax, model):
"""
将模型的分离超平面可视化
"""
x1 = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 100)
x2 = np.linspace(ax.get_ylim()[0], ax.get_ylim()[1], 100)
X1, X2 = np.meshgrid(x1, x2)
Y = model.predict_proba(np.c_[X1.ravel(), X2.ravel()])[:, 1]
Y = Y.reshape(X1.shape)
ax.cont... | 5,323,854 |
def keyboard_interrupt(func):
"""Decorator to be used on a method to check if there was a keyboard interrupt error that was raised."""
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except KeyboardInterrupt:
self.close() # this will close the vi... | 5,323,855 |
def correct_mpl(obj):
"""
This procedure corrects MPL data:
1.) Throw out data before laser firing (heights < 0).
2.) Remove background signal.
3.) Afterpulse Correction - Subtraction of (afterpulse-darkcount).
NOTE: Currently the Darkcount in VAPS is being calculated as
the afterpul... | 5,323,856 |
def main():
"""Provide BEL Statements from BEL graph."""
df = get_relations_df()
graph = build_relations_graph(df)
with open("famplex.bel", "w") as file:
to_bel(graph, file) | 5,323,857 |
def cutoff_depth(d: int):
"""A cutoff function that searches to depth d."""
return lambda game, state, depth: depth > d | 5,323,858 |
def players_age_in_days():
"""
This function will read the players.csv file
and convert the players age in years to days.
Use of DictWriter instead of writer.
Instead of nesting the read of the file and the
write of the new file, as in the function
decorator_enforce_argument_type, the player... | 5,323,859 |
def create_contributor_node(d: Dict, label: str = "Contributor") -> Node:
""" Using the k, v pairs in `d`, create a Node object with those properties.
Takes k, as-is except for 'uuid', which is cast to int.
Args:
d (dict): property k, v pairs
label (str): The py2neo.Node.__primarylabel__ to ... | 5,323,860 |
def extractLipsHaarCascade(haarDetector, frame):
"""Function to extract lips from a frame"""
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
roi_gray = 0
faces = haarDetector.detectMultiScale(gray, 1.3, 5)
if len(faces) == 0:
roi_gray = cv2.resize(gray, (150, 100))
return roi_gray
... | 5,323,861 |
def we_are_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return hasattr(sys, "frozen") | 5,323,862 |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given RGB color values."""
return '#%02x%02x%02x' % (int(red), int(green), int(blue)) | 5,323,863 |
def rescue(
function: Callable[
[_SecondType],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
],
) -> Kinded[Callable[
[KindN[_RescuableKind, _FirstType, _SecondType, _ThirdType]],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
]]:
"""
Turns function's... | 5,323,864 |
def disable():
"""
Disables logging to FreeCAD console (or STDOUT).
Note, logging may be enabled by another imported module, so this isn't a
guarentee; this function undoes logging_enable(), nothing more.
"""
global _logging_handler
if _logging_handler:
root_logger = logging.getLogge... | 5,323,865 |
def test_one_mw_failing(client: FlaskClient):
"""test GET method with one middlewares"""
resp = client.get('/get-with-auth')
assert resp.status_code == 403
assert not resp.json.get('success') | 5,323,866 |
def try_get_resource(_xmlroot, parent_node: str, child_node: str, _lang: str):
""" Получить ресурс (решение / условия) """
for tutorial in _xmlroot.find(parent_node).iter(child_node):
lang = tutorial.attrib['language']
_type = tutorial.attrib['type']
if lang == _lang and _type == 'applic... | 5,323,867 |
def main(pprmeta, finder, sorter, assembly, outdir):
"""Parse VirSorter, VirFinder and PPR-Meta outputs and merge the results.
"""
hc_contigs, lc_contigs, prophage_contigs, sorter_hc, sorter_lc, sorter_prophages = \
merge_annotations(pprmeta, finder, sorter, assembly)
at_least_one = False
i... | 5,323,868 |
def test_fail_missing_api(mock_va, config):
"""
Test fail missing api
"""
mock_va.return_value.auth_from_file = Mock(return_value=True)
mock_va.return_value.load = Mock(return_value=config)
with pytest.raises(RuntimeError):
bot.configure("test_config.yaml", "test_vault.yaml", "test_cred... | 5,323,869 |
def download_song(file_name, content):
""" Download the audio file from YouTube. """
_, extension = os.path.splitext(file_name)
if extension in ('.webm', '.m4a'):
link = content.getbestaudio(preftype=extension[1:])
else:
log.debug('No audio streams available for {} type'.format(extension... | 5,323,870 |
def load_distributed_dataset(split,
batch_size,
name,
drop_remainder,
use_bfloat16,
normalize=False,
with_info=False,
... | 5,323,871 |
def get_sample_media():
"""Gets the sample media.
Returns:
bytes
"""
path = request.args.get("path")
# `conditional`: support partial content
return send_file(path, conditional=True) | 5,323,872 |
def _is_swiftmodule(path):
"""Predicate to identify Swift modules/interfaces."""
return path.endswith((".swiftmodule", ".swiftinterface")) | 5,323,873 |
def _unpack_array(fmt, buff, offset, count):
"""Unpack an array of items.
:param fmt: The struct format string
:type fmt: str
:param buff: The buffer into which to unpack
:type buff: buffer
:param offset: The offset at which to start unpacking
:type offset: int
:param count: The number ... | 5,323,874 |
def _add_column_and_sort_table(sources, pointing_position):
"""Sort the table and add the column separation (offset from the source) and phi (position angle from the source)
Parameters
----------
sources : `~astropy.table.Table`
Table of excluded sources.
pointing_position : `~astropy.c... | 5,323,875 |
async def test_get_config_parameters(hass, multisensor_6, integration, hass_ws_client):
"""Test the get config parameters websocket command."""
entry = integration
ws_client = await hass_ws_client(hass)
node = multisensor_6
# Test getting configuration parameter values
await ws_client.send_json... | 5,323,876 |
async def test_wifi_hotspot_start_stop(
lifecycle: WiFiHotspotLifeCycle,
) -> None:
"""Test that we can start and stop the hotspot."""
assert not lifecycle._running
for _ in range(3):
# Start it
asyncio.ensure_future(lifecycle.run_hotspot())
await asyncio.sleep(0.02)
... | 5,323,877 |
def jsmin(content):
""" Minify your JavaScript code.
Use `jsmin <https://pypi.python.org/pypi/jsmin>`_ to compress JavaScript.
You must manually install jsmin if you want to use this processor.
Args:
content: your JavaScript code
Returns:
the minified version of your JavaScript co... | 5,323,878 |
def quit_app():
"""
Quits the script
"""
sys.exit() | 5,323,879 |
def generate_server_config() -> IO[bytes]:
"""Returns a temporary generated file for use as the server config."""
boards = stm32f429i_detector.detect_boards()
if not boards:
_LOG.critical('No attached boards detected')
sys.exit(1)
config_file = tempfile.NamedTemporaryFile()
_LOG.debu... | 5,323,880 |
def smooth_l1_loss_detectron2(input, target, beta: float, reduction: str = "none"):
"""
Smooth L1 loss defined in the Fast R-CNN paper as:
| 0.5 * x ** 2 / beta if abs(x) < beta
smoothl1(x) = |
| abs(x) - 0.5 * beta otherwise,
where x = input - target.
Smooth ... | 5,323,881 |
def png_to_jpg(png_path, jpg_path):
""" convert image format: png -> jpg, then save picture with jpg
Args:
png_path (str)
jpg_path (str)
Return:
True or False (bool)
"""
img = Image.open(png_path)
try:
if len(img.split()) == 4:
# preve... | 5,323,882 |
def split_lines_to_df(in_lines_trunc_df):
"""
For a column of strings that each represent the line of a CSV
(and each line may have a different number of separators),
read them into a DataFrame.
in_lines_trunc_df: Assumes that the relevant column is `0`
Returns: The resulting DataFrame
"""
... | 5,323,883 |
def run_front(url_prefix='', port=None):
""" Run the front end one.
"""
run_app([add_views_front], url_prefix, port) | 5,323,884 |
def init_seed(seed):
"""Disable cudnn to maximize reproducibility 禁用cudnn以最大限度地提高再现性"""
torch.cuda.cudnn_enabled = False
"""
cuDNN使用非确定性算法,并且可以使用torch.backends.cudnn.enabled = False来进行禁用
如果设置为torch.backends.cudnn.enabled =True,说明设置为使用使用非确定性算法
然后再设置:torch.backends.cudnn.benchmark = True,当这个flag为T... | 5,323,885 |
def generate_full_vast_beleg_ids_request_xml(form_data, th_fields=None, use_testmerker=False):
""" Generates the full xml for the Verfahren "ElsterDatenabholung" and the Datenart "ElsterVaStDaten",
including "Anfrage" field.
An example xml can be found in the Eric documentation under
common/... | 5,323,886 |
def apply_recursive(dic, func):
""" param dic is usually a dictionary, e.g. 'target' or 'condition'
child node. It can also be a child dict or child list of
these nodes/dicts
param func is a func to be applied to each child dictionary, taking
the dictionary as the o... | 5,323,887 |
def get_q_vocab(ques, count_thr=0, insert_unk=False):
"""
Args:
ques: ques[qid] = {tokenized_question, ...}
count_thr: int (not included)
insert_unk: bool, insert_unk or not
Return:
vocab: list of vocab
"""
counts = {}
for qid, content in ques.iteritems():
... | 5,323,888 |
def update_callable(buildable: Buildable,
new_callable: TypeOrCallableProducingT):
"""Updates `config` to build `new_callable` instead.
When extending a base configuration, it can often be useful to swap one class
for another. For example, an experiment may want to swap in a subclass that
h... | 5,323,889 |
def get_desc_dist(descriptors1, descriptors2):
""" Given two lists of descriptors compute the descriptor distance
between each pair of feature. """
#desc_dists = 2 - 2 * (descriptors1 @ descriptors2.transpose())
desc_sims = - descriptors1 @ descriptors2.transpose()
# desc_sims = d... | 5,323,890 |
def test_multiple_speakers():
"""
Test output exists with multiple speaker input
# GIVEN a sample file containing multiple speakers
# WHEN calling tscribe.write(...)
# THEN produce the .docx without errors
"""
# Setup
input_file = "sample_material/03-speaker-identification.json"
o... | 5,323,891 |
def _parse_cells_icdar(xml_table):
"""
Gets the table cells from a table in ICDAR-XML format.
"""
cells = list()
xml_cells = xml_table.findall(".//cell")
cell_id = 0
for xml_cell in xml_cells:
text = get_text(xml_cell)
start_row = get_attribute(xml_cell, "start-row"... | 5,323,892 |
def download(link: str,
method: str = "GET",
to_file: Optional[BinaryIO] = None,
headers: Optional[dict] = None,
allow_redirects: bool = True,
max_retries: int = 3) -> "Response":
"""
Return Response named tuple
Response.response - request... | 5,323,893 |
def get_mem_usage():
"""returns percentage and vsz mem usage of this script"""
pid = os.getpid()
psout = os.popen( "ps -p %s u"%pid ).read()
parsed_psout = psout.split("\n")[1].split()
return float(parsed_psout[3]), int( parsed_psout[4] ) | 5,323,894 |
def download_file(url, local_folder=None):
"""Downloads file pointed to by `url`.
If `local_folder` is not supplied, downloads to the current folder.
"""
filename = os.path.basename(url)
if local_folder:
filename = os.path.join(local_folder, filename)
# Download the file
print("Down... | 5,323,895 |
def test_ap_wpa2_psk_supp_proto_unexpected_group_msg(dev, apdev):
"""WPA2-PSK supplicant protocol testing: unexpected group message"""
(bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
# Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
msg = recv_eapol(hapd)
... | 5,323,896 |
def gist_ncar(range, **traits):
""" Generator for the 'gist_ncar' colormap from GIST.
"""
_data = dict(
red = [(0.0, 0.0, 0.0),
(0.0050505050458014011, 0.0, 0.0),
(0.010101010091602802, 0.0, 0.0),
(0.015151515603065491, 0.0, 0.0),
(0.020202020183205605... | 5,323,897 |
def main(request, username):
"""
User > Main
"""
namespace = CacheHelper.ns('user:views:main', username=username)
response_data = CacheHelper.io.get(namespace)
if response_data is None:
response_data, user = MainUserHelper.build_response(request, username)
if response_data['sta... | 5,323,898 |
def test_quiet(capsys: CaptureFixture, logger_name: str):
"""Test quiet.
:param capsys: pytest fixture.
:param logger_name: conftest fixture.
"""
log = setup_logging(logger_name=logger_name, verbose=-1)
assert not generate_log_statements(log)
stdout, stderr = [i.splitlines() for i in capsys... | 5,323,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.