content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def portfolio_return(holdings: float,
asset_percent: float,
bond_percent: float,
asset_etfs: pd.DataFrame,
bond_etfs: pd.DataFrame,
start_date: datetime,
end_date: datetime) -> Tuple[pd.DataFram... | 5,319,800 |
def rewofzt2(x,y):
"""Real part of asymptotic representation of wofz function 1 for |z|**2 > 111 (for e = 10e-6)
See Zaghloul (2018) arxiv:1806.01656
Args:
x:
y:
Returns:
f: Real(wofz(x+iy))
"""
z=x+y*(1j)
q=(1j)*z/(jnp.sqrt(jnp.pi))*(z*z - 2.5)/(z*z*... | 5,319,801 |
def _macos_bundle_impl(ctx):
"""Implementation of the macos_bundle rule."""
additional_resource_sets = []
additional_resources = depset(ctx.files.app_icons)
if additional_resources:
additional_resource_sets.append(AppleResourceSet(
resources=additional_resources,
))
# TODO(b/36557429): Add su... | 5,319,802 |
def usage():
"""
Prints out usage information for the program and then exits.
:return: none
"""
print('Error. Usage:')
print('To start the client and connect to the server, use the following command and format:')
print('./ttweetcli.py <ServerIP> <ServerPort> <Username>')
print('')
pr... | 5,319,803 |
def combine_ecgs_and_clinical_parameters(ecgs, clinical_parameters):
"""
Combines ECGs and their corresponding clinical parameters
:param ecgs: List of ECGs
:param clinical_parameters: Corresponding clinical parameters
:return: Medical data for each patient including ECGs and the patients clinic... | 5,319,804 |
async def list_participants(channel):
"""現在の参加者の一覧を表示"""
# 最新の募集メッセージのmessageオブジェクトを取得
try:
message = await channel.fetch_message(int(os.environ['PW_BOT_MSG_ID']))
except discord.errors.NotFound:
await channel.send('募集メッセージが見つかりません')
return
user_list = []
# メッセージについているリ... | 5,319,805 |
def writePolarPlotData(dataX, dataY, suffix):
"""Write data for a polar plot, taking care of the center of inversion"""
print("var dataX" + suffix + " = [")
print((len(dataX) * "%.5f,") % tuple(dataX))
print(((len(dataX)-1) * "%.5f," + "%.5f") % tuple(-dataX))
print("];")
print("var dataY" + su... | 5,319,806 |
def test_rnmrtk_2d():
""" 2D freq rnmrtk, pipe <-> rnmrtk, pipe """
# prepare rnmrtk converter
rdic, rdata = ng.rnmrtk.read(
os.path.join(DATA_DIR, "rnmrtk_2d", "freq_2d.sec"))
urdic = ng.rnmrtk.guess_udic(rdic, rdata)
rC = ng.convert.converter()
rC.from_rnmrtk(rdic, rdata, urdic)
... | 5,319,807 |
def is_territory_group(group: inkex.ShapeElement) -> bool:
"""
Checks if element is a territory group. It is a territory group if it is a non-layer Group
and has two children, one of which is a territory, the other of which is a center point
group.
:param group:
:return:
"""
valid = isin... | 5,319,808 |
def filter_tracks(tracks, size_th, mask_file):
"""Filter tracks that doesn't fulfill requirement"""
print('filtering tracks...')
del_idx = []
for i,t in enumerate(tracks):
dets = t.dump()
if not np.any(filter_detections(dets, size_th, mask_file)):
del_idx.append(i)
prin... | 5,319,809 |
def disable_chat_bot_callback(message):
"""
Disable chat bot callback.
:param message: The message.
:return: The return from the function.
"""
return disable_chat_bot(message.guild.name) | 5,319,810 |
def write_anat(t1w, bids_path, raw=None, trans=None, landmarks=None,
deface=False, overwrite=False, verbose=False):
"""Put anatomical MRI data into a BIDS format.
Given a BIDS directory and a T1 weighted MRI scan for a certain subject,
format the MRI scan to be in BIDS format and put it into... | 5,319,811 |
def new_post(request):
"""The new post publication"""
form = PostForm(request.POST or None, files=request.FILES or None)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('/')
return render(request, 'new.html', {'form': form}) | 5,319,812 |
def test_codebook_loader():
"""Functionnal tests for the codebook loader"""
res = loader.load_codebook_matrix(Path(jpegdna.__path__[0] + "/data/codebook.pkl"))
assert res is not None
assert len(res) == 9
lengths = [10, 24, 130, 586, 1776, 7998, 24634, 110660, 464734]
for i, el in enumerate(res):... | 5,319,813 |
def get_fake_prediction(anchors, coords, config):
"""
Generates the anchor labels with random noise to fake a good prediction.
Used for testing non-model related code.
anchors
The list of anchor coordinates generated from get_anchors().
coords
The list of ground truth point coordina... | 5,319,814 |
def test_invalid_update_row():
"""Test error when instantiating update row without cells and position
arguments.
"""
prov = UpdateRow(key=0, position=UpdateValue(0, 1))
assert prov.is_update()
with pytest.raises(ValueError):
UpdateRow(key=0) | 5,319,815 |
def service(schema):
"""Service fixture"""
assert schema.namespaces # this is pythonic way how to check > 0
return pyodata.v2.service.Service(URL_ROOT, schema, requests) | 5,319,816 |
def upgrade():
"""upgrade to this revision"""
op.execute(
"""
ALTER TABLE
data.items
ALTER COLUMN datetime
TYPE timestamptz
;
"""
) | 5,319,817 |
def function2(parameter1, parameter2):
"""
This is another function example
:param parameter1: This is what the first parameter looks like
:param parameter2: And this is the second
:return: Another return value
"""
pass | 5,319,818 |
def register_handlers(cls, nsmap, events, stanzas):
"""Register all special handlers in a plugin."""
## Sanity check
st_handlers = set(m for (_, (_, m)) in stanzas)
for (_, callbacks) in events:
dup = st_handlers.intersection(set(callbacks))
if dup:
raise PluginError('Stanza... | 5,319,819 |
def get_question_types(container):
""" SELECTOR FOR RETURNING QUESTION TYPES """
return container.keys() | 5,319,820 |
def add_velocities(ax, c_L, c_S, c_R, x_max,
plt_kwargs={'color': 'k', 'ls': ':', 'lw': 0.5}):
"""Add horizontal lines indicating material velocities to a
matplotlib axes object.
Parameters
----------
ax : axes
Matplotlib axes in which the plot will be added... | 5,319,821 |
def _process_campaign_data(campaign, batch_user, campaign_type, max_count):
"""Process campaign data."""
# Validate campaign type
if not campaign_type in CAMPAIGN_TASK_TYPES.keys():
raise CommandError('Bad campaign type {0}'.format(campaign_type))
# TODO: add rollback in case of errors
for ... | 5,319,822 |
def test_transform_without_fitting():
"""HyperTransformer shouldn't transform when fit hasn't been called yet."""
# Setup
data = pd.DataFrame({'col1': [1, 2], 'col2': ['a', 'b']})
ht = HyperTransformer()
# Run / Assert
ht.detect_initial_config(data)
error_msg = (
'The HyperTransform... | 5,319,823 |
def uploader(dict_in):
"""Post the global dictionary to the server
This function contains a post request to the flask server. The global
dictionary in the patient GUI that saved all the information to be upload
will be posted. This function will also catch the exceptions that the
server can not be ... | 5,319,824 |
def _process_motion_command(command, opts):
"""
Process motion command.
:param command: Command tuple
:param opts: UserOptions tuple
:return:
"""
motion_data_type = None
motion_data = [] # empty data container
# Interpret linear motion command
if opts.Use_linear_motion:
... | 5,319,825 |
def test():
"""Tests all approaches developed."""
heuristic_solution = heuristic.knapsack(weights, utilities, knapsack_weight)
heuristic_weight = (heuristic_solution * weights).sum()
heuristic_utility = (heuristic_solution * utilities).sum()
headers = ['Method', 'Solution', 'Utility',
... | 5,319,826 |
def prepare_term_id(config, vocab_ids, term):
"""REST POST and PATCH operations require taxonomy term IDs, not term names. This
funtion checks its 'term' argument to see if it's numeric (i.e., a term ID) and
if it is, returns it as is. If it's not (i.e., a term name) it looks for the
term name ... | 5,319,827 |
def write_excel(cluster, wb):
"""create excel sheet and insert the data into the sheet"""
ws_net = wb.add_worksheet('net')
row_offset = 0
col_offset = 0
row_data = 0
col_data = 0
span = 1
fill_value = -1
tmp_new = []
count = 0
for node in cluster:
if hasattr(node, 'n... | 5,319,828 |
def simple_string(value: str) -> str:
"""
Returns a simplified value for loose comparison
"""
if not value:
return ""
value = strip_string(value) # Remove quotes
value = value.rstrip("\\") # Remove trailing backslashes
value = value.lower() # Lowercase
value = re.sub(r"[^a-z0-... | 5,319,829 |
def add_predict_args(parser: ArgumentParser):
"""
Adds predict arguments to an ArgumentParser.
:param parser: An ArgumentParser.
"""
parser.add_argument('--gpu', type=int,
choices=list(range(torch.cuda.device_count())),
help='Which GPU to use')
pa... | 5,319,830 |
def _strip_debug_object_data(instance: Dict[str, Any]) -> None:
"""Remove internal debug data from the given object."""
instance.pop('debug', None)
if 'shows' in instance:
for show in instance['shows']:
show.pop('boundingBox', None) | 5,319,831 |
def make_negative_fasta(seqlet_intervals, seqlet_dna, negatives_fasta_file, max_seqs=16384):
"""Write sampled seqlets as motif negatives."""
num_seqs = len(seqlet_intervals)
if num_seqs <= max_seqs:
sample_i = np.arange(num_seqs)
else:
sample_i = np.random.choice(num_seqs, max_seqs)
... | 5,319,832 |
def plot_energy_comparison(args):
"""Plot energy trajectories for comparison"""
outfile = (args.out_params + '.png').format(param='cmp_free_energy', **args.__dict__)
pyplot.figure()
names = args.cmp_energy.keys()
vals = -sp.array([args.cmp_energy[n] for n in names]).T
print names
print vals
... | 5,319,833 |
def current_name() -> str:
"""Return the current dataset name, with an empty name in default."""
return _current_name_context.get().name | 5,319,834 |
def open_zarr(path):
"""
Utility to open an xarray dataset from either dir that pytest might be called from.
If called from root the path will be different than in the test dir
"""
return xr.open_zarr(str(dir_.joinpath(path))) | 5,319,835 |
def download_training(c):
"""Download tfrecords training data from blob container specified in .env file
"""
env_values = load_config()
container_name = env_values.get("CONTAINER_NAME")
account_name = env_values.get("ACCOUNT_NAME")
account_key = env_values.get("ACCOUNT_KEY")
download_data_fr... | 5,319,836 |
def iid_log_probs(ids, batch_index, sequence_index, logp):
"""
Stacks the ids into a matrix that allows you to extract the corresponding logp
from the iid samples from the decoder.
:param ids: [B,T] tensor of ids in vocab
:param batch_index: [B,T] tensor of the batch size repeated for seq len
:p... | 5,319,837 |
def run_local(model_path, run_id, port, image):
"""
Serve model locally running in a Sagemaker-compatible Docker container.
"""
mlflow.sagemaker.run_local(model_path=model_path, run_id=run_id, port=port, image=image) | 5,319,838 |
def get_format_from_path(path):
""" Returns tuple of format , extension, unpacking function or None"""
if re.search(r'(\.tar\.gz$)|(\.tgz$)', path):
return ('gztar', 'tgz', unpack_tar)
elif path.endswith('.zip'):
return ('zip', 'zip', unpack_zip)
elif re.search(r'(\.tar\.bz2$)|(\.tbz2$)... | 5,319,839 |
def drawCoverageAndFeature(coverage_map, fov = 20, orient = 80, pa_feature_start = 30, seperation_feature_start = 8, pa_feature_end = None, seperation_feature_end = None, save_address = None, white_for_zero_coverage = False):
"""Draw feature on coverage map for given Field of View (FOV), ORIENT, and feature info (i... | 5,319,840 |
def a_test_mh():
"""
Tests an ARIMAX model estimated with Metropolis-Hastings, and tests that the latent variable
vector length is correct, and that value are not nan
"""
model = ARIMAX(formula="y ~ x1", data=data, ar=1, ma=1, family=Exponential())
x = model.fit('M-H',nsims=300)
assert(len(m... | 5,319,841 |
def tag(name, open=False, **options):
"""
Returns an XHTML compliant tag of type ``name``.
``open``
Set to True if the tag should remain open
All additional keyword args become attribute/value's for the tag. To pass in Python
reserved words, append _ to the name of the key. For att... | 5,319,842 |
def CMDarchive(parser, args):
"""Archives data to the server.
If a directory is specified, a .isolated file is created the whole directory
is uploaded. Then this .isolated file can be included in another one to run
commands.
The commands output each file that was processed with its content hash. For
direc... | 5,319,843 |
def test_configure_logger_intercept(
mocked_remove_handle: MagicMock, mocked_add_handle: MagicMock
):
"""Ensure calling configure_logger with intercept works."""
configure_logger(intercept=True)
mocked_add_handle.assert_called_once_with(loguru.logger)
mocked_remove_handle.assert_not_called()
m... | 5,319,844 |
def _validate_input(data = None, period = None):
"""
General function to validate specified user parameters.
"""
if data is not None:
if not isinstance(data, np.ndarray) or data.dtype != np.float64:
raise ValueError("Param 'data' needs to be of type numpy.ndarray with " \
... | 5,319,845 |
def get_ludo_user_id(ludo_username):
"""Returns the user id (number) for a given username in Ludopedia"""
session = requests.Session()
result = session.get(f'{LUDOPEDIA_USER_URL}/{ludo_username}')
match_id = re.search(LUDOPEDIA_USER_ID_REGEX, result.text)
if match_id:
# Return the user_id
... | 5,319,846 |
def test_list_string_max_length_nistxml_sv_iv_list_string_max_length_1_4(mode, save_output, output_format):
"""
Type list/string is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/string/Schema+Instance/NISTSchema-SV-IV-list-string-maxLength-1.xsd",
... | 5,319,847 |
def operations_get_notification_list_post(inline_object19=None): # noqa: E501
"""operations_get_notification_list_post
# noqa: E501
:param inline_object19:
:type inline_object19: dict | bytes
:rtype: TapiNotificationGetNotificationList
"""
if connexion.request.is_json:
inline_o... | 5,319,848 |
def project_block_to_graph(block_sizes, block_level_vals):
"""
Projects a set of values at the level of
blocks to the nodes in the graph.
"""
full_graph_values = []
for k, n in enumerate(block_sizes):
current_block = []
for q in range(n):
current_block.append(block_le... | 5,319,849 |
def run_game():
"""Инициализирует игру и создает объект экрана."""
pygame.init()
ai_settings = Settings_AI()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_icon(ai_settings.icon)
pygame.display.set_caption("Alien Invasion")
clock = ... | 5,319,850 |
def _write_gener(parameters, simulator="tough"):
"""Write GENER block data."""
from ._common import generators
# Format
label_length = max(
[
len(generator["label"]) if "label" in generator else 0
for generator in parameters["generators"]
]
)
label_length... | 5,319,851 |
def _find(condition):
"""Returns indices where ravel(a) is true.
Private implementation of deprecated matplotlib.mlab.find
"""
return np.nonzero(np.ravel(condition))[0] | 5,319,852 |
def get_weekends():
"""
Gets weekends from user input
"""
user_reply = input("What days of the week are your weekends? ")
days = weekday_dict.keys()
ret = []
for day in days:
if day.lower() in user_reply.lower():
ret.append(day)
if confirm_input(ret):
return r... | 5,319,853 |
def get_non_utf8_tables_columns(mysql_db_name, mysql_username, mysql_password):
"""Return two lists: the names of tables and columns that do not use the UTF-8 character set."""
sqlalchemy_url = 'mysql://%s:%s@localhost:3306/information_schema' % (mysql_username, mysql_password)
info_schema_engine = create_e... | 5,319,854 |
def fresh_db(app):
"""Fresh test db per function."""
with create_test_db(app) as test_db:
yield test_db | 5,319,855 |
def _fetch_file(url, data_dir=TEMP, uncompress=False, move=False,md5sum=None,
username=None, password=None, mock=False, handlers=[], resume=True, verbose=0):
"""Load requested dataset, downloading it if needed or requested.
This function retrieves files from the hard drive or download them from... | 5,319,856 |
def dataframe_from_dictionary(entry):
"""Create Pandas DataFrame from list of dictionary."""
return pd.DataFrame(entry) | 5,319,857 |
def label_skew_process(label_vocab, label_assignment, client_num, alpha, data_length):
"""
params
-------------------------------------------------------------------
label_vocab : dict label vocabulary of the dataset
label_assignment : 1d list a list of label, the index of list is the index ass... | 5,319,858 |
def test_get_stock_detail_page(test_client, add_stocks_for_default_user, mock_requests_get_success_weekly):
"""
GIVEN a Flask application configured for testing, with the default user logged in
and the default set of stocks in the database
WHEN the '/stocks/3' page is retrieved (GET) and the response fr... | 5,319,859 |
def can_item_circulate(item_pid):
"""Return True if Item can circulate."""
item = Item.get_record_by_pid(item_pid)
if item:
return item["status"] == "CAN_CIRCULATE"
return False | 5,319,860 |
def GetFocusThreadPB(filename):
"""
Get the focus thread for a pinball.
If the pinball log file format is version 2.4, or lower, the focus thread
info will be in a *.result file. However, as of version 2.5, this info is
now in the *.global.log file.
@return integer with focus thread
@retu... | 5,319,861 |
def refpoint(matrix, objectives, weights):
"""Execute reference point MOORA without any validation."""
# max and min reference points
rpmax = np.max(matrix, axis=0)
rpmin = np.min(matrix, axis=0)
# merge two reference points acoording objectives
mask = np.where(objectives == Objective.MAX.value... | 5,319,862 |
def init_fabric_device_step1(device_id: int, new_hostname: str, device_type: str,
neighbors: Optional[List[str]] = [],
job_id: Optional[str] = None,
scheduled_by: Optional[str] = None) -> NornirJobResult:
"""Initialize fabric (CO... | 5,319,863 |
def architecture_is_32bit(arch):
"""
Check if the architecture specified in *arch* is 32-bit.
:param str arch: The value to check.
:rtype: bool
"""
return bool(arch.lower() in ('i386', 'i686', 'x86')) | 5,319,864 |
def solve_captcha():
"""request the captcha solving from the website 2captcha.com"""
# Uses the API Key stored in the .env file (If you are not the developer you need to insert it)
load_dotenv()
data_sitekey = getenv('DATA_SITEKEY')
cap_key = getenv('CAP_KEY')
if cap_key == '' or data_sitekey =... | 5,319,865 |
def plot_bayesian_histogram(
bin_edges: np.ndarray,
data_dist: FrozenDistType,
color: Union[str, Iterable[float], None] = None,
label: Optional[str] = None,
ax: Any = None,
ci: Optional[Tuple[float, float]] = (0.01, 0.99)
) -> None:
"""Plot a Bayesian histogram as horizontal lines with credi... | 5,319,866 |
def StandardMajScale(frequency):
"""Takes one arguement, frequency. Returns an array of 8 frequencies from 12 TET chromatic scale"""
EightSteps = []
freqArray = Create12TETChromatic(frequency)
steps = (0, 2, 4, 5, 7, 9, 11, 12)
for i in steps:
scale = freqArray[i]
EightSteps.append(s... | 5,319,867 |
def write_lines_to_file(filename, lines):
"""
Don't do strip in line for white space in case it is part of schema name or table name
"""
with open(filename, 'w') as fp:
for line in lines:
fp.write("%s\n" % line.strip('\n')) | 5,319,868 |
def interpolate_observing_conditions(
timestamps: np.ndarray,
df: pd.DataFrame,
parameter_key: str,
) -> np.ndarray:
"""
Take the values of the observing conditions in the data frame
``df`` and interpolate them temporally so that we get values for
the timestamp of each frame.
The interp... | 5,319,869 |
def _mn_min_ ( self ,
maxcalls = 5000 ,
tolerance = 0.01 ,
method = 'MIGRADE' ) :
"""Perform the actual MINUIT minimization:
>>> m = ... #
>>> m.fit() ## run migrade!
>>> m.migrade () ## ditto
>>> m.fit ( method = ... | 5,319,870 |
def old_func4(self, x):
"""Summary.
Further info.
"""
return x | 5,319,871 |
def sensible_pname(egg_name):
"""Guess Debian package name from Egg name."""
egg_name = safe_name(egg_name).replace('_', '-')
if egg_name.startswith('python-'):
egg_name = egg_name[7:]
return "python-%s" % egg_name.lower() | 5,319,872 |
def shuffle_split_data(X, y):
""" Shuffles and splits data into 70% training and 30% testing subsets,
then returns the training and testing subsets. """
# Shuffle and split the data
X_train, X_test, y_train, y_test = crossval.train_test_split(X, y, test_size=0.30, random_state=101)
# Retur... | 5,319,873 |
def get_agent_params():
"""Gets parameters passed to the agent via kernel cmdline or vmedia.
Parameters can be passed using either the kernel commandline or through
virtual media. If boot_method is vmedia, merge params provided via vmedia
with those read from the kernel command line.
Although it s... | 5,319,874 |
def main():
"""
Entry point for the `hotreload` command line program.
"""
import argparse
parser = argparse.ArgumentParser(
prog='hotreload',
description='Run Python script with hotreload.')
parser.add_argument('-i', dest='interactive', action='store_const',
... | 5,319,875 |
def test_set_display():
"""Tests for display of sets."""
long_set = {i for i in range(100)}
# Simple set
assert value_to_display({1, 2, 3}) == '{1, 2, 3}'
# Long set
disp = '{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...}'
assert value_to_display(long_set) == disp
# Short list of sets
disp = ... | 5,319,876 |
def wrap_maya_ui(mayaname):
"""Given the name of a Maya UI element of any type,
return the corresponding QWidget or QAction.
If the object does not exist, returns None
:param mayaname: the maya ui element
:type mayaname: str
:returns: the wraped object
:rtype: QObject | None
:raises: No... | 5,319,877 |
def test_order_book_ask_strategy(default_conf, limit_buy_order_open, limit_buy_order, fee,
limit_sell_order_open, mocker, order_book_l2, caplog) -> None:
"""
test order book ask strategy
"""
mocker.patch('freqtrade.exchange.Exchange.fetch_l2_order_book', order_book_l2)
... | 5,319,878 |
def FloatSpin(parent, value=0, action=None, tooltip=None,
size=(100, -1), digits=1, increment=1, **kws):
"""FloatSpin with action and tooltip"""
if value is None:
value = 0
fs = fspin.FloatSpin(parent, -1, size=size, value=value,
digits=digits, increment=inc... | 5,319,879 |
def test_several_sources_2(test_dir: str) -> None:
"""cp a_file b_file -> c_file should fail"""
a_file = os.path.join(test_dir, "a_file")
b_file = os.path.join(test_dir, "b_file")
c_file = os.path.join(test_dir, "c_file")
sys.argv = ["pycp", a_file, b_file, c_file]
with pytest.raises(SystemExit)... | 5,319,880 |
def generate_config(context):
""" Entry point for the deployment resources. """
resources = []
project_id = context.env['project']
bucket_name = context.properties.get('name') or context.env['name']
# output variables
bucket_selflink = '$(ref.{}.selfLink)'.format(bucket_name)
buck... | 5,319,881 |
def test_exception_when_sending_text_message_to_invalid_recipient(client):
"""
GIVEN a client and a recipient id
WHEN a text message is sent to the recipient
THEN the status code of the response is 200
"""
invalid_recipient_id = 1234
with pytest.raises(OAuthException):
client.send_te... | 5,319,882 |
def get_vaccine_admin_summary():
"""Returns DataFrame about COVID-19 vaccine administration in Italy (summary version)
Parameters
----------
None
Raises
------
ItaCovidLibConnectionError
Raised when there are issues with Internet connection.
Returns
-------
... | 5,319,883 |
def _get_atlassian_plugin_xml_from_jar_bytes(jar_bytes: IO[bytes]) -> str:
"""Opens the jar on the provided path and tries to find the
atlassian-plugin.xml in this file
Args:
path (pathlib.Param): the path to the jar file
Returns:
str: the content of atlassian_plugin.xml
Raises:
... | 5,319,884 |
def update_translation(name: str):
"""
Usage: ./translate-vue.py src/components/ComponentName.vue
Will create locale/{lang}/components/ComponentName.yml
"""
base, ext = os.path.splitext(name)
assert base.startswith("src"), "File must be inside src directory."
for lang in LANGUAGES:
... | 5,319,885 |
def update_table_spec(project_id,
compute_region,
dataset_display_name,
time_column_spec_display_name):
"""Update table spec."""
# [START automl_tables_update_table_spec]
# TODO(developer): Uncomment and set the following variables
# proj... | 5,319,886 |
def apply_verif(self):
"""no particular order, used for diagnostic"""
if not (self.source or getattr(self, 'add_objects', None)):
raise Utils.WafError('no source files specified for %s' % self)
if not self.target:
raise Utils.WafError('no target for %s' % self) | 5,319,887 |
def get_objects(si, args):
"""
Return a dict containing the necessary objects for deployment.
"""
# Get datacenter object.
datacenter_list = si.content.rootFolder.childEntity
if args.datacenter_name:
datacenter_obj = get_obj_in_list(args.datacenter_name, datacenter_list)
else:
... | 5,319,888 |
def isPulledMayaReference(dagPath):
"""
Verifies if the DAG path refers to a pulled prim that is a Maya reference.
"""
_, _, _, prim = getPulledInfo(dagPath)
return prim and prim.GetTypeName() == 'MayaReference' | 5,319,889 |
def _read_record7(fid, key1, key2, line, data):
"""
Saves metadata to ``data.stations[key]`` and ``data.recording[key]`` that
is used to preallocate arrays for data recording for ``fort.7#`` type
ADCIRC output files
:param fid: :class:``file`` object
:param string key1: ADCIRC Output File Type ... | 5,319,890 |
def plot_zphot_comp():
"""
"""
path = "results/"
filename_1 = path + "best_fits_tot_68_emp" + ".dat"
filename_2 = path + "best_fits_tot_68_emp_sansy" + ".dat"
color_file = ["blue", "red", "green"]
label = ["no y band", "y band"]
for i, filename in enumerate([filename_2, filename_1]):
... | 5,319,891 |
def tw_mock():
"""Returns a mock terminal writer"""
class TWMock:
WRITE = object()
def __init__(self):
self.lines = []
self.is_writing = False
def sep(self, sep, line=None):
self.lines.append((sep, line))
def write(self, msg, **kw):
... | 5,319,892 |
def sql_get_user(mitarbeiter_id):
"""
SQL module for compiling user information. Name, Surname [and Mail Address]
:param mitarbeiter_id:
:return:
"""
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT name, nachname FROM mitarbeiter WHERE id_mitarbeiter=?", (mitarbeiter_id,))... | 5,319,893 |
def send_activation_email(activation_key, user, wi_data):
"""
@parameter{activation_key,string} activation key to be sent
@parameter{user,string} username of the user to activate
@parameter{wi_data}
Sends email with activation key to registred user.
"""
ctx_dict = {'activation_key':... | 5,319,894 |
def chtmpdir(tmpdir):
"""Change the current working directory to a temporary directory."""
with tmpdir.as_cwd():
yield | 5,319,895 |
def matsubtraction(A,B):
"""
Subtracts matrix B from matrix A and returns difference
:param A: The first matrix
:param B: The second matrix
:return: Matrix difference
"""
if(len(A)!=len(B) or len(A[0])!=len(B[0])):
return "Subtraction not possible"
for i in range(len(... | 5,319,896 |
def order_keys(order):
"""
Order keys for JSON readability when not using json_log=True
"""
def processor(logger, method_name, event_dict):
if not isinstance(event_dict, OrderedDict):
return event_dict
for key in reversed(order):
if key in event_dict:
... | 5,319,897 |
def test__ts_hr_hess():
""" test automech.py hr_scan
"""
tsks = '\tts hr_hess runlvl=lvl_scf inplvl=lvl_scf tors_model=1dhrfa'
drivers = '\tes'
# Format the run.dat with the run-save dir paths
with open(RUN_TEMP_PATH, 'r') as file_obj:
run_str = file_obj.read()
with open(RUN_DA... | 5,319,898 |
def print_simple_path(graph, sp):
""" Print a simple path or cycle.
Args:
graph (obj): a networkx graph
sp (list): a simple path
Returns:
None
"""
in_segment = False
for index, node in enumerate(sp[:-1]):
if in_segment:
print(node[-1], end='')
... | 5,319,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.