content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def action_create(name, args):
"""create a llvmlab installation"""
import llvmlab
from optparse import OptionParser, OptionGroup
parser = OptionParser("%%prog %s [options] <path>" % name)
group = OptionGroup(parser, "CONFIG OPTIONS")
group.add_option("", "--admin-login", dest="admin_login",
... | 5,345,900 |
def convert_to_github_url_with_token(url, token):
"""
Convert a Github URL to a git+https url that identifies via an Oauth token. This allows for installation of
private packages.
:param url: The url to convert into a Github access token oauth url.
:param token: The Github access token to use for th... | 5,345,901 |
def test_owner_approval_apply_failed(test1_token, empty_device_apply_record, execute_sql):
"""
owner审批失败,不能审批其他owner的
:param test1_token:
:param empty_device_apply_record:
:param execute_sql:
:return:
"""
empty_device_apply_record(1, 1)
sql = """INSERT INTO device_apply_record VALUES... | 5,345,902 |
def get_numbers_of_papers(metrics):
"""
Convert the metrics into a format that is easier to work with. Year-ordered
numpy arrays.
"""
publications = metrics['histograms']['publications']
year, total, year_refereed, refereed = [], [], [], []
y = list(publications['all publications'].keys())
... | 5,345,903 |
def show_warning(parent, title, message):
""" Helper method for opening a simple yes/no dialog and getting the answer
"""
dialog = Gtk.MessageDialog(parent=parent, flags=0,
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK, text=title)
dialog.format_secondary_text(message)
dialog.run()
dialog.d... | 5,345,904 |
def test_base_provider_get_transform_json_exception(mock_name, mock_value):
"""
Test BaseProvider.get() with a json transform that raises an exception
"""
mock_data = json.dumps({mock_name: mock_value}) + "{"
class TestProvider(BaseProvider):
def _get(self, name: str, **kwargs) -> str:
... | 5,345,905 |
def load_check_definitions(lang):
"""
Retrieve Trust Advisor check definitions
"""
retval = {}
resp = TA_C.describe_trusted_advisor_checks(language=lang)
if resp:
try:
checks = resp['checks']
retval = {a['id']:a for a in checks}
except ValueError:
... | 5,345,906 |
def test_register_again_deserializer(deserializer_type):
"""
Test registering a deserializer again.
"""
with pytest.raises(ValueError):
register_deserializer(*deserializer_type) | 5,345,907 |
def filter_phrase(comments, phrase):
"""Returns list of comments and replies filtered by substring."""
results = []
for comment in comments:
if phrase.lower() in comment.message.lower():
results.append(comment)
for reply in comment.replies:
if phrase.lower() in... | 5,345,908 |
def get_available_plugins():
"""
Print a list of available plugins
:return:
"""
print("Available plugins:\n")
for instrument, class_name in _working_plugins.items():
print("%s for %s" % (class_name, instrument)) | 5,345,909 |
def asses_completeness(language_code: str, sw: ServiceWorker = Depends(get_sw)):
"""
make a completion test for language: check fe,be, domains and entries
@param language_code:
@param sw:
@return:
"""
if language_code not in sw.messages.get_added_languages():
raise ApplicationExcepti... | 5,345,910 |
def create_intrinsic_node_class(cls):
"""
Create dynamic sub class
"""
class intrinsic_class(cls):
"""Node class created based on the input class"""
def is_valid(self):
raise TemplateAttributeError('intrisnic class shouldn\'t be directly used')
intrinsic_class.__name__ =... | 5,345,911 |
def delete_assessment_run(assessmentRunArn=None):
"""
Deletes the assessment run that is specified by the ARN of the assessment run.
See also: AWS API Documentation
Exceptions
Examples
Deletes the assessment run that is specified by the ARN of the assessment run.
Expected Output:
... | 5,345,912 |
def load(provider, config_location=DEFAULT_CONFIG_DIR):
"""Load provider specific auth info from file """
auth = None
auth_file = None
try:
config_dir = os.path.join(config_location, NOIPY_CONFIG)
print("Loading stored auth info [%s]... " % config_dir, end="")
auth_file = os.pat... | 5,345,913 |
def segment_fish(image):
"""Attempts to segment the clown fish out of the provided image."""
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
light_orange = (1, 190, 200)
dark_orange = (18, 255, 255)
mask = cv2.inRange(hsv_image, light_orange, dark_orange)
light_white = (0, 0, 200)
dark_wh... | 5,345,914 |
def get_bugzilla_url(bug_id):
"""Return bugzilla url for bug_id."""
return u'https://bugzilla.mozilla.org/show_bug.cgi?id=%d' % bug_id | 5,345,915 |
def enable_faster_encoder(self, need_build=True, use_fp16=False):
"""
Compiles fusion encoder operator intergrated FasterTransformer using the
method of JIT(Just-In-Time) and replaces the `forward` function of
`paddle.nn.TransformerEncoder` and `paddle.nn.TransformerEncoderLayer`
objects inherited f... | 5,345,916 |
def func(*x):
""" Compute the function to minimise.
Vector reshaped for more readability.
"""
res = 0
x = np.array(x)
x = x.reshape((n, 2))
for i in range(n):
for j in range(i+1, n):
(x1, y1), (x2, y2) = x[i, :], x[j, :]
delta = (x2 - x1)**2 + (y2 - y1)**2 - ... | 5,345,917 |
def transform_target(target, classes=None):
"""
Accepts target value either single dimensional torch.Tensor or (int, float)
:param target:
:param classes:
:return:
"""
if isinstance(target, torch.Tensor):
if target.ndim == 1:
target = target.item() if target.shape[0] ==... | 5,345,918 |
def test_delete_without_resource_typeerror():
"""If entity= is not a Resource, create() should raise TypeError"""
auth = mock_auth()
base = Rest(auth)
# Resource without change
resource = Mock(Collection)
assert_raises(TypeError, base.delete, resource) | 5,345,919 |
def called_on_joined():
""" Loop sending the state of this machine using WAMP every x seconds.
This function is executed when the client joins the router, which
means it's connected and authenticated, ready to send WAMP messages.
"""
print("Connected")
# Then we make a POST request to ... | 5,345,920 |
def toggle_display_backlight_brightness(low_brightness=12):
"""Reads Raspberry pi touch display's current brightness values from system
file and toggles it between low and max (255) values depending on the
current value.
"""
old = _get_current_display_backlight_brightness()
# set to furthest aw... | 5,345,921 |
def merge_all_regions(out_path: str, id_regions: List[Tuple[int, File]]) -> Tuple[int, int, File]:
"""
Recursively merge a list of region files.
"""
if len(id_regions) == 1:
# Base case 1.
[(sample_id, region_file)] = id_regions
return (sample_id, sample_id, region_file)
elif... | 5,345,922 |
def write_champ_file_geometry(filename, nucleus_num, nucleus_label, nucleus_coord):
"""Writes the geometry data from the quantum
chemistry calculation to a champ v2.0 format file.
Returns:
None as a function value
"""
if filename is not None:
if isinstance(filename, str):
... | 5,345,923 |
def check_for_collision(sprite1: arcade.Sprite,
sprite2: arcade.Sprite) -> bool:
"""Check for collision between two sprites.
Used instead of Arcade's default implementation as we need a hack to
return False if there is just a one pixel overlap, if it's not
multiplayer...
"""... | 5,345,924 |
def maybe_insert_input_equalization_observers_for_node(
node: Node,
equalization_qconfig: Any,
model: torch.nn.Module,
modules: Dict[str, torch.nn.Module],
graph: Graph,
node_name_to_target_dtype: Dict[str, Any],
is_branch: bool,
) -> None:
"""
If `node` needs to be equalized, find t... | 5,345,925 |
def _bootstrap0(registry_client, executor_manager, store_client,
store_command, release_store, formation):
"""Bootstrap the scheduler.
The steps (and hops) we need to go through to get this up and
running:
1. read the release manifest (release.yml)
2. create instances based on the ... | 5,345,926 |
def test_equality_numpy_scalar():
"""
A regression test to ensure that numpy scalars are correctly compared
(which originally failed due to the lack of ``__array_priority__``).
"""
assert 10 != 10. * u.m
assert np.int64(10) != 10 * u.m
assert 10 * u.m != np.int64(10) | 5,345,927 |
def modify_color(hsbk, **kwargs):
"""
Helper function to make new colors from an existing color by modifying it.
:param hsbk: The base color
:param hue: The new Hue value (optional)
:param saturation: The new Saturation value (optional)
:param brightness: The new Brightness value (optional)
... | 5,345,928 |
def train_val_test_split(df, train_p=0.8, val_p=0.1, state=1, shuffle=True):
"""Wrapper to split data into train, validation, and test sets.
Parameters
-----------
df: pd.DataFrame, np.ndarray
Dataframe containing features (X) and labels (y).
train_p: float
Percent of data to assign... | 5,345,929 |
def add_logs_to_table_heads(max_logs):
"""Adds log headers to table data depending on the maximum number of logs from trees within the stand"""
master = []
for i in range(2, max_logs + 1):
for name in ['Length', 'Grade', 'Defect']:
master.append(f'Log {i} {name}')
if i < max_logs... | 5,345,930 |
def stations_at_risk(stations, level):
"""Returns a list of tuples, (station, risk_level) for all stations with risk above level"""
level = risk_level(level)
stations = [(i, station_flood_risk(i)) for i in stations]
return [i for i in stations if risk_level(i[1]) >= level] | 5,345,931 |
def try_to_acquire_archive_contents(pull_from: str, extract_to: Path) -> bool:
"""Try to acquire the contents of the archive.
Priority:
1. (already extracted) local contents
2. adress-specified (local|remote) archive through fsspec
Returns:
True if success_acquisition else False
""... | 5,345,932 |
def unproxy(proxy):
"""Return a new copy of the original function of method behind a proxy.
The result behaves like the original function in that calling it
does not trigger compilation nor execution of any compiled code."""
if isinstance(proxy, types.FunctionType):
return _psyco.unproxycode(proxy.func_... | 5,345,933 |
def get_measured_attribute(data_model, metric_type: str, source_type: str) -> Optional[str]:
"""Return the attribute of the entities of a source that are measured in the context of a metric.
For example, when using Jira as source for user story points, the points of user stories (the source entities) are
s... | 5,345,934 |
def collect_app_manager_information(ID_person, subtitle):
"""
Method that is able to collect data and call personal information page constructor
:param ID_person: id inserted by the app manager
"""
# no integer or empty
try:
ID = int(ID_person)
except ValueError:
canvas.item... | 5,345,935 |
def get_one_frame_stack_dynamic(sp, idx):
"""
for a given sp and index number in a dynamic caller operand_stack data, return its
data type and value.
Note, at runtime, caller.operand_stack is dynamic, sp, idx, types and values are all
changing during the run time.
"""
if idx > sp:
r... | 5,345,936 |
def getIntArg(arg, optional=False):
"""
Similar to "getArg" but return the integer value of the arg.
Args:
arg (str): arg to get
optional (bool): argument to get
Returns:
int: arg value
"""
return(int(getArg(arg, optional))) | 5,345,937 |
def erase_all_simulators(path=None):
"""Erases all simulator devices.
Args:
path: (str) A path with simulators
"""
command = ['xcrun', 'simctl']
if path:
command += ['--set', path]
LOGGER.info('Erasing all simulators from folder %s.' % path)
else:
LOGGER.info('Erasing all simulators.')
t... | 5,345,938 |
def test_sync_bulk(mocker):
"""Test the hubspot bulk sync function"""
mock_request = mocker.patch("hubspot.tasks.send_hubspot_request")
profile = ProfileFactory.create()
sync_bulk_with_hubspot([profile.user], make_contact_sync_message, "CONTACT")
mock_request.assert_called_once() | 5,345,939 |
def get_in_with_default(keys: Iterable, default):
"""`get_in` function, returning `default` if a key is not there.
>>> get_in_with_default(["a", "b", 1], 0)({"a": {"b": [0, 1, 2]}})
1
>>> get_in_with_default(["a", "c", 1], 0)({"a": {"b": [0, 1, 2]}})
0
"""
getter = get_in(keys)
def get... | 5,345,940 |
def conv_HSV2BGR(hsv_img):
"""HSV画像をBGR画像に変換します。
Arguments:
hsv_img {numpy.ndarray} -- HSV画像(3ch)
Returns:
numpy.ndarray -- BGR画像(3ch)
"""
V = hsv_img[:, :, 2]
C = hsv_img[:, :, 1]
H_p = hsv_img[:, :, 0] / 60
X = C * (1 - np.abs(H_p % 2 - 1))
Z = np.zeros_like(C)
... | 5,345,941 |
def remap(tensor, map_x, map_y, align_corners=False):
"""
Applies a generic geometrical transformation to a tensor.
"""
if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]:
raise ValueError("Inputs last two dimensions must match.")
batch_size, _, height, width = tensor.sha... | 5,345,942 |
def run_zero_filled_sense(args, data_loader):
""" Run Adjoint (zero-filled SENSE) reconstruction """
logging.info('Run zero-filled SENSE reconstruction')
logging.info(f'Arguments: {args}')
reconstructions = defaultdict(list)
with torch.no_grad():
for sample in tqdm(iter(data_loader)):
... | 5,345,943 |
def main():
"""Parameter handling main method."""
parser = argparse.ArgumentParser(description="Mel spectrograph using librosa.")
parser.add_argument("-f", "--filename", type=str, help="mp3 or wav file to analyze")
parser.add_argument("--full_mel", action="store_true", help="full mel spectrograph")
... | 5,345,944 |
def AutoRegression(df_input,
target_column,
time_column,
epochs_to_forecast=1,
epochs_to_test=1,
hyper_params_ar={}):
"""
This function performs regression using feature augmentation and then training XGB with C... | 5,345,945 |
def VMACD(prices, timeperiod1=12, timeperiod2=26, timeperiod3=9):
"""
39. VMACD量指数平滑异同移动平均线
(Vol Moving Average Convergence and Divergence,VMACD)
说明:
量平滑异同移动平均线(VMACD)用于衡量量能的发展趋势,属于量能引趋向指标。
MACD称为指数平滑异同平均线。分析的数学公式都是一样的,只是分析的物理量不同。
VMACD对成交量VOL进行分析计算,而MACD对收盘价CLOSE进行分析计算。
计算方法:
SHORT=... | 5,345,946 |
def try_compress_numbers_to_range(elements):
"""
Map the "number" attribute of any element in `elements` to the most compact
range possible (starting from 1). If the resulting numbers are within
[MIN_RANGE, MAX_RANGE], return True, otherwise, return False. If it is not
possible to obtain a mapping w... | 5,345,947 |
def merge_all_mods(list_of_mods, gfx=None):
"""Merges the specified list of mods, starting with graphics if set to
pre-merge (or if a pack is specified explicitly).
Params:
list_of_mods
a list of the names of mods to merge
gfx
a graphics pack to be merged in
Ret... | 5,345,948 |
def pearson_r_p_value(a, b, dim):
"""
2-tailed p-value associated with pearson's correlation coefficient.
Parameters
----------
a : Dataset, DataArray, GroupBy, Variable, numpy/dask arrays or scalars
Mix of labeled and/or unlabeled arrays to which to apply the function.
b : Dataset, Dat... | 5,345,949 |
def get_ceilometer_usages(date, connection_string):
"""
Function which talks with openstack
"""
today = datetime.datetime.combine(date, datetime.datetime.min.time())
yesterday = today - datetime.timedelta(days=1)
engine = create_engine(connection_string)
connection = engine.connect()
qu... | 5,345,950 |
def _do_artifact_mapping(query_definition, event_message, metadata,
response, res_client, context_token,
additional_map_data=None):
""" Map query results to new artifact and add to Resilient """
incident = event_message.get("incident", {})
incident_id = inci... | 5,345,951 |
def fit_kij(kij_bounds, eos, mix, datavle=None, datalle=None, datavlle=None,
weights_vle=[1., 1.], weights_lle=[1., 1.],
weights_vlle=[1., 1., 1., 1.], minimize_options={}):
"""
fit_kij: attemps to fit kij to VLE, LLE, VLLE
Parameters
----------
kij_bounds : tuple
bo... | 5,345,952 |
def pickle_photospheres(photosphere_filenames, kind, meta=None):
"""
Load all model photospheres, parse the points and photospheric structures.
"""
if meta is None:
meta = {
"kind": kind,
"source_directory": os.path.dirname(photosphere_filenames[0])
}
elif no... | 5,345,953 |
def get_pid_and_server():
"""Find process id and name of server the analysis is running on
Use the platform.uname to find servername instead of os.uname because the latter is not supported on Windows.
"""
pid = os.getpid()
server = platform.uname().node
return f"{pid}@{server}" | 5,345,954 |
def cal_embedding(sents, model_path, word_idx, mode='mean'):
"""Calculate the embedding for each sentence
Args:
sents (list): a list of sentences
model_path (str): keras model path
word_idx (dict): a dictionary of mapping between words and indices
mode (str): current support mea... | 5,345,955 |
def MemGetSize(BlockID):
"""
Returns the size of a memory block (Also useful for determining if a memory block already exists
Output: Returns the size of the memory block. Returns 0 if data block could not be found.
"""
pass | 5,345,956 |
def calc_ac_score(labels_true, labels_pred):
"""calculate unsupervised accuracy score
Parameters
----------
labels_true: labels from ground truth
labels_pred: labels form clustering
Return
-------
ac: accuracy score
"""
nclass = len(np.unique(labels_true))
labels_size =... | 5,345,957 |
def main(**kwargs):
"""Update info in AWS_EC2 and AWS_IP redis-helper collections"""
if kwargs['all'] is True:
for profile in get_profiles():
ec2 = EC2(profile)
ec2.update_collection()
else:
ec2 = EC2(kwargs['profile'])
ec2.update_collection()
if kwargs['n... | 5,345,958 |
def wave_ode_gamma_neq0(t, X, *f_args):
"""
Right hand side of the wave equation ODE when gamma > 0
"""
C = f_args[0]
D = f_args[1]
CD = C*D
x, y, z = X
return np.array([-(1./(1.+y) + CD)*x + C*(1+D*CD)*(z-y), x, CD*(z-y)]) | 5,345,959 |
def populate_daily_metrics_for_site(site_id, date_for, force_update=False):
"""Collect metrics for the given site and date
"""
try:
site = Site.objects.get(id=site_id)
except Site.DoesNotExist as e:
msg = ('{prefix}:SITE:FAIL:populate_daily_metrics_for_site:site_id: '
'{si... | 5,345,960 |
def run_workflow(
config: Dict,
form_data: ImmutableMultiDict,
*args,
**kwargs
) -> Dict:
"""Executes workflow and save info to database; returns unique run id."""
# Validate data and prepare run environment
form_data_dict = __immutable_multi_dict_to_nested_dict(
multi_dict=form_data... | 5,345,961 |
def insertion_stack(nums: List[int]) -> List[int]:
""" A helper function that sort the data in an ascending order
Args:
nums: The original data
Returns:
a sorted list in ascending order
"""
left = []
right = []
for num in nums:
while left and left[-1] > num:
... | 5,345,962 |
def svn_wc_get_pristine_contents(*args):
"""svn_wc_get_pristine_contents(char const * path, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t"""
return _wc.svn_wc_get_pristine_contents(*args) | 5,345,963 |
def _FindAllPossibleBrowsers(finder_options, android_platform):
"""Testable version of FindAllAvailableBrowsers."""
if not android_platform:
return []
possible_browsers = []
if finder_options.webview_embedder_apk and not os.path.exists(
finder_options.webview_embedder_apk):
raise exceptions.PathM... | 5,345,964 |
def test_populate_intended_for(tmpdir, folder, expected_prefix, simulation_function):
"""
Test populate_intended_for.
Parameters:
----------
tmpdir
folder : str or os.path
path to BIDS study to be simulated, relative to tmpdir
expected_prefix : str
expected start of the "Inte... | 5,345,965 |
def getLanguageSpecification(lang):
"""
Return a dictionary which contains the specification of a language.
Specifically, return the key-value pairs defined in the 'lang.yaml' file as
a dictionary, i.e. for the language cpp return the contents of
'plugins/cpp/lang.yaml'.
Raise an IOError if the... | 5,345,966 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a connection
with the context.
"""
with engine().connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with conte... | 5,345,967 |
def _is_valid_file(file):
"""Returns whether a file is valid.
This means that it is a file and not a directory, but also that
it isn't an unnecessary dummy file like `.DS_Store` on MacOS.
"""
if os.path.isfile(file):
if not file.startswith('.git') and file not in ['.DS_Store']:
... | 5,345,968 |
def create_cache_key(func, key_dict=None, self=None):
"""Get a cache namespace and key used by the beaker_cache decorator.
Example::
from tg import cache
from tg.caching import create_cache_key
namespace, key = create_cache_key(MyController.some_method)
cache.get_cache(namespace... | 5,345,969 |
def longest_common_substring(s, t):
"""
Find the longest common substring between the given two strings
:param s: source string
:type s: str
:param t: target string
:type t: str
:return: the length of the longest common substring
:rtype: int
"""
if s == '' or t == '':
r... | 5,345,970 |
def add_cutoff_freqs(ax, mode, arrow_dir, y_max, c_L, c_S,
plt_kwargs={'color': 'k', 'ls': '--', 'lw': 0.5}):
"""Add vertical lines indicating cutoff frequencies to a matplotlib
axes object.
Parameters
----------
ax : axes
Matplotlib axes in which the plot ... | 5,345,971 |
def pytest_addoption(parser):
""" Load in config path. """
group = parser.getgroup("Agent Test Suite Configuration", "agent", after="general")
group.addoption(
"--sc",
"--suite-config",
dest='suite_config',
action="store",
metavar="SUITE_CONFIG",
help="Load su... | 5,345,972 |
def correct_predictions(output_probabilities, targets):
"""
Compute the number of predictions that match some target classes in the
output of a model.
Args:
output_probabilities: A tensor of probabilities for different output
classes.
targets: The indices of the actual targe... | 5,345,973 |
def resolve_all(anno, task):
"""Resolve all pending annotations."""
return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x) | 5,345,974 |
def get_free_port():
""" Find and returns free port number. """
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("", 0))
free_port = soc.getsockname()[1]
soc.close()
return free_port | 5,345,975 |
def test_upload_subtitles_authentication(
mock_user_moira_lists, logged_in_apiclient, mocker
):
"""
Tests that only authenticated users with collection admin permissions can call UploadVideoSubtitle
"""
client, user = logged_in_apiclient
client.logout()
url = reverse("upload-subtitles")
... | 5,345,976 |
def get_diff_list(small_list, big_list):
"""
Get the difference set of the two list.
:param small_list: The small data list.
:param big_list: The bigger data list.
:return: diff_list: The difference set list of the two list.
"""
# big_list有而small_list没有的元素
diff_list = list(set(big_list).... | 5,345,977 |
def blend_weight_arrays(n_weightsA, n_weightsB, value=1.0, weights_pp=None):
"""
Blend two 2d weight arrays with a global mult factor, and per point weight values.
The incoming weights_pp should be a 1d array, as it's reshaped for the number of influences.
Args:
n_weightsA (np.array): Weight ar... | 5,345,978 |
def weight_kabsch_dist(x1, x2, weights):
"""
Compute the Mahalabonis distance between positions x1 and x2 given Kabsch weights (inverse variance)
x1 (required) : float64 array with dimensions (n_atoms,3) of one molecular configuration
x2 (required) : float64 a... | 5,345,979 |
def calc_color_rarity(color_frequencies: dict) -> float:
"""
Return rarity value normalized to 64.
Value ascending from 0 (most rare) to 64 (most common).
"""
percentages = calc_pixel_percentages(color_frequencies)
weighted_rarity = [PERCENTAGES_NORMALIZED.get(k) * v * 64 for k,v in percentages.... | 5,345,980 |
def exp_map(x, r, tangent_point=None):
"""
Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the
tangent plane of the CCM at point \(p\) (`tangent_point`).
This function maps a point `x` on the tangent plane to the CCM, using the
Riemannian exponential map.
:param x: np.array,... | 5,345,981 |
def test_parser_read(fresh_aiida_env):
"""Test to read a INCAR file."""
path = data_path('phonondb', 'INCAR')
parser = IncarParser(file_path=path)
incar = parser.incar
assert incar['prec'] == 'Accurate'
assert incar['ibrion'] == -1
assert incar['encut'] == 359.7399
assert incar['lreal']... | 5,345,982 |
def get_python_msvcrt_version():
"""Return the Visual C runtime version Python is linked to, as an int"""
python_version = sys.version_info[0:2]
if python_version < (2.4):
return 60
if python_version < (2.6):
return 71
return 90 | 5,345,983 |
def _get_data_column_label_in_name(item_name):
"""
:param item_name: Name of a group or dataset
:return: Data column label or ``None``
:rtype: str on None
"""
# /1.1/measurement/mca_0 should not be interpreted as the label of a
# data column (let's hope no-one ever uses mca_0 as a label)
... | 5,345,984 |
def _auto_backward(loss,
startup_program=None,
parameter_list=None,
no_grad_set=None,
callbacks=None,
distop_context=None):
"""
modification is inplaced
"""
act_no_grad_set = _get_no_grad_set(loss, no_grad_set... | 5,345,985 |
def strip_from_ansi_esc_sequences(text):
"""
find ANSI escape sequences in text and remove them
:param text: str
:return: list, should be passed to ListBox
"""
# esc[ + values + control character
# h, l, p commands are complicated, let's ignore them
seq_regex = r"\x1b\[[0-9;]*[mKJusDCBA... | 5,345,986 |
def test_steamgameentity_extra_state_attributes_property(manager_mock):
"""Test the device_state_attributes property."""
game_id = "975150"
game = util.get_steam_game(game_id, manager_mock.coordinator.data[game_id])
entity = SteamGameEntity(manager_mock, game)
expected = {
"box_art_url": "ht... | 5,345,987 |
def periodic_task1():
"""
@summary: 周期性任务执行函数
"""
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
try:
import requests
req = requests.get('http://www.baidu.com')
print req.status_code
logger.info(u"Celery 周期任务调用成功,当前时间:{}".format(now))
except Exception... | 5,345,988 |
def _concat_columns(args: list):
"""Dispatch function to concatenate DataFrames with axis=1"""
if len(args) == 1:
return args[0]
else:
_lib = cudf if HAS_GPU and isinstance(args[0], cudf.DataFrame) else pd
return _lib.concat(
[a.reset_index(drop=True) for a in args],
... | 5,345,989 |
def test_grdinfo():
"""
Make sure grdinfo works as expected.
"""
grid = load_earth_relief(registration="gridline")
result = grdinfo(grid=grid, force_scan=0, per_column="n")
assert result.strip() == "-180 180 -90 90 -8592.5 5559 1 1 361 181 0 1" | 5,345,990 |
def applyRegexToList(list, regex, separator=' '):
"""Apply a list of regex to list and return result"""
if type(regex) != type(list):
regex = [regex]
regexList = [re.compile(r) for r in regex]
for r in regexList:
list = [l for l in list if r.match(l)]
list = [l.split(separator) for l in list]
ret... | 5,345,991 |
def tomorrow(event):
""" show todo items for tomorrow. """
if not event._parsed.rest:
event.reply("tomorrow <txt>")
return
event.tomorrow = event.txt.replace("tomorrow", "").strip()
event.prefix = "tomorrow"
event.save()
event.ok() | 5,345,992 |
def pathsplit(path):
""" This version, in contrast to the original version, permits trailing
slashes in the pathname (in the event that it is a directory).
It also uses no recursion """
return path.split(os.path.sep) | 5,345,993 |
def GetFileName(path: str) -> str:
"""Get the name of the file from the path
:type path: str
:rtype: str
"""
return splitext(basename(path))[0] | 5,345,994 |
async def test_new_ignored_users_available(
hass, caplog, entry, mock_websocket, setup_plex_server
):
"""Test setting up when new users available on Plex server but are ignored."""
MONITORED_USERS = {"Owner": {"enabled": True}}
OPTIONS_WITH_USERS = copy.deepcopy(DEFAULT_OPTIONS)
OPTIONS_WITH_USERS[M... | 5,345,995 |
def get_dnssec_output(hosted_zone_id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDNSSECResult]:
"""
Resource used to control (enable/disable) DNSSEC in a specific hosted zone.
:param str hosted_zone_id: The unique string (ID) ... | 5,345,996 |
def test_reset_password(client, user_info):
"""A user can reset their password using a link sent to their email."""
new_password = 'New_Password123'
assert new_password != user_info['password']
register_user(client, user_info)
log_out_current_user(client)
with mail.record_messages() as outbox:
... | 5,345,997 |
def main(out_path, ud_dir, check_parse=False, langs=ALL_LANGUAGES, exclude_trained_models=False, exclude_multi=False,
hide_freq=False, corpus='train', best_per_language=False):
""""
Assemble all treebanks and models to run evaluations with.
When setting check_parse to True, the default models will ... | 5,345,998 |
def collapse(individual_refs):
"""Collapse references like [C1,C2,C3,C7,C10,C11,C12,C13] into 'C1-C3, C7, C10-C13'.
Args:
individual_refs (string): Uncollapsed references.
Returns:
string: Collapsed references.
"""
parts = []
for ref in individual_refs:
mtch = re.match... | 5,345,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.