uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
746cc554aee3c2072a2c5c68 | train | class | class TopKOutputTypeTest(trt_test.TfTrtIntegrationTestBase):
"""Testing that output type of engine using Top-K is set correctly."""
def GraphFn(self, x):
k = 5
k_tensor = constant_op.constant(k, dtype=dtypes.int32, name="Const")
values, indices = nn_ops.top_k(x, k_tensor, name="TopK")
# Resh... | class TopKOutputTypeTest(trt_test.TfTrtIntegrationTestBase):
| """Testing that output type of engine using Top-K is set correctly."""
def GraphFn(self, x):
k = 5
k_tensor = constant_op.constant(k, dtype=dtypes.int32, name="Const")
values, indices = nn_ops.top_k(x, k_tensor, name="TopK")
# Reshape will act as a layer between the TopK output and the engine... | Fn, dtypes.float32, [[100, 100]],
[[100, k], [100, k]])
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {"TRTEngineOp_0": ["Const", "TopK"]}
class TopKOutputTypeTest(trt_test.TfTrtIntegrationTestBase):
| 82 | 83 | 278 | 17 | 66 | uve/tensorflow | tensorflow/python/compiler/tensorrt/test/topk_test.py | Python | TopKOutputTypeTest | TopKOutputTypeTest | 50 | 72 | 50 | 50 | 4339c9f447bf98eb4580adf92b703548ca665bdd | bigcode/the-stack | train |
a5b5674b28c5b09a07309995 | train | class | class TopKTest(trt_test.TfTrtIntegrationTestBase):
"""Testing Top-K in TF-TRT conversion."""
def GraphFn(self, x):
k = 5
k_tensor = constant_op.constant(k, dtype=dtypes.int32, name="Const")
values, indices = nn_ops.top_k(x, k_tensor, name="TopK")
values = array_ops.identity(values, name="out... | class TopKTest(trt_test.TfTrtIntegrationTestBase):
| """Testing Top-K in TF-TRT conversion."""
def GraphFn(self, x):
k = 5
k_tensor = constant_op.constant(k, dtype=dtypes.int32, name="Const")
values, indices = nn_ops.top_k(x, k_tensor, name="TopK")
values = array_ops.identity(values, name="output_0")
indices = array_ops.identity(indices, n... | t_integration_test_base as trt_test
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test
class TopKTest(trt_test.TfTrtIntegrationTestBase):
... | 64 | 64 | 199 | 15 | 48 | uve/tensorflow | tensorflow/python/compiler/tensorrt/test/topk_test.py | Python | TopKTest | TopKTest | 29 | 47 | 29 | 29 | ce6a0e0b5d9c3173098206e0e66a58b00a61b7b4 | bigcode/the-stack | train |
ae4b482813d60b1b1efc94af | train | class | class LogicalInterconnectModule(OneViewModule):
MSG_CONSISTENT = 'Logical Interconnect returned to a consistent state.'
MSG_ETH_SETTINGS_UPDATED = 'Ethernet settings updated successfully.'
MSG_INTERNAL_NETWORKS_UPDATED = 'Internal networks updated successfully.'
MSG_SETTINGS_UPDATED = 'Logical Interconn... | class LogicalInterconnectModule(OneViewModule):
| MSG_CONSISTENT = 'Logical Interconnect returned to a consistent state.'
MSG_ETH_SETTINGS_UPDATED = 'Ethernet settings updated successfully.'
MSG_INTERNAL_NETWORKS_UPDATED = 'Internal networks updated successfully.'
MSG_SETTINGS_UPDATED = 'Logical Interconnect setttings updated successfully.'
MSG_QOS... | _settings:
description: Has the OneView facts about the Port Flap Settings.
returned: On 'port_flap_settings_updated' state, but can be null.
type: dict
li_firmware:
description: Has the OneView facts about the installed Firmware.
returned: On 'firmware_installed' state, but can be null.
type: ... | 256 | 256 | 2,973 | 10 | 245 | chebroluharika/oneview-ansible-collection | plugins/modules/oneview_logical_interconnect.py | Python | LogicalInterconnectModule | LogicalInterconnectModule | 337 | 648 | 337 | 337 | 012ac7e7c17ec0a61bc58f45e1fa6c59d30798ac | bigcode/the-stack | train |
204032f48784bce4f87be7ad | train | function | def main():
LogicalInterconnectModule().run()
| def main():
| LogicalInterconnectModule().run()
| data):
if 'ethernetSettings' not in data and 'fcoeSettings' not in data:
raise OneViewModuleValueError(self.MSG_NO_OPTIONS_PROVIDED)
def __build_firmware_uri(self, filename):
return '/rest/firmware-drivers/' + filename
def main():
| 64 | 64 | 11 | 3 | 60 | chebroluharika/oneview-ansible-collection | plugins/modules/oneview_logical_interconnect.py | Python | main | main | 651 | 652 | 651 | 651 | 2cad96913a5d5eec246b1262f77dfe6d8c8a5e5e | bigcode/the-stack | train |
7798b4e710d829295b2d32e6 | train | class | class LinearRegression(LinearRegression_original):
__doc__ = LinearRegression_original.__doc__
def __init__(self, fit_intercept=True, normalize=False, copy_X=True,
n_jobs=None):
super(LinearRegression, self).__init__(
fit_intercept=fit_intercept, normalize=normalize,
... | class LinearRegression(LinearRegression_original):
| __doc__ = LinearRegression_original.__doc__
def __init__(self, fit_intercept=True, normalize=False, copy_X=True,
n_jobs=None):
super(LinearRegression, self).__init__(
fit_intercept=fit_intercept, normalize=normalize,
copy_X=copy_X, n_jobs=n_jobs)
def fit(se... | (self, 'sample_weight_') and self.sample_weight_ is not None)):
return self._decision_function(X)
else:
X = check_array(X)
return _daal4py_predict(self, X)
_fit_copy = fit
_predict_copy = predict
class LinearRegression(LinearRegression_original):
| 64 | 64 | 124 | 8 | 55 | Surfndez/daal4py | daal4py/sklearn/linear_model/linear.py | Python | LinearRegression | LinearRegression | 187 | 200 | 187 | 187 | af0e2b36c288fade7f4afde5383fbb244c1ba48a | bigcode/the-stack | train |
ad03e278f0df0e06f83d86e5 | train | function | def fit(self, X, y, sample_weight=None):
"""
Fit linear model.
Parameters
----------
X : numpy array or sparse matrix of shape [n_samples,n_features]
Training data
y : numpy array of shape [n_samples, n_targets]
Target values
sample_weight : numpy array of shape [n_samples... | def fit(self, X, y, sample_weight=None):
| """
Fit linear model.
Parameters
----------
X : numpy array or sparse matrix of shape [n_samples,n_features]
Training data
y : numpy array of shape [n_samples, n_targets]
Target values
sample_weight : numpy array of shape [n_samples]
Individual weights for each sam... | copy(order='C')
if self.coef_.shape[0] == 1 and y_.ndim == 1:
self.coef_ = np.ravel(self.coef_)
self.intercept_ = self.intercept_[0]
return self
def _daal4py_predict(self, X):
X = make2d(X)
_fptype = getFPType(self.coef_)
lr_pred = daal4py.linear_regression_prediction(
fp... | 183 | 183 | 612 | 12 | 170 | Surfndez/daal4py | daal4py/sklearn/linear_model/linear.py | Python | fit | fit | 87 | 154 | 87 | 87 | 939bd833620e8dbe5756ca962398e5afc9ea9676 | bigcode/the-stack | train |
5a8758b71e366e3d7a2d6306 | train | function | def predict(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
Samples.
Returns
-------
C : array, shape = (n_samples,)
Returns predicted values.
"""
X = np.asarray(X) if not sp.issparse... | def predict(self, X):
| """Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
Samples.
Returns
-------
C : array, shape = (n_samples,)
Returns predicted values.
"""
X = np.asarray(X) if not sp.issparse(X) else X
good_sh... | linalg.lstsq(X, y)
self.coef_ = self.coef_.T
if y.ndim == 1:
self.coef_ = np.ravel(self.coef_)
self._set_intercept(X_offset, y_offset, X_scale)
return self
def predict(self, X):
| 68 | 68 | 228 | 6 | 61 | Surfndez/daal4py | daal4py/sklearn/linear_model/linear.py | Python | predict | predict | 156 | 181 | 156 | 156 | d644ed14b87f07965ef6bd0c7ad7f9318fa80831 | bigcode/the-stack | train |
e8e7a5286e1f139b590fdb5d | train | function | def _daal4py_predict(self, X):
X = make2d(X)
_fptype = getFPType(self.coef_)
lr_pred = daal4py.linear_regression_prediction(
fptype=_fptype,
method='defaultDense'
)
lr_res = lr_pred.compute(X, self.daal_model_)
res = lr_res.prediction
if res.shape[1] == 1 and self.coef_.ndim... | def _daal4py_predict(self, X):
| X = make2d(X)
_fptype = getFPType(self.coef_)
lr_pred = daal4py.linear_regression_prediction(
fptype=_fptype,
method='defaultDense'
)
lr_res = lr_pred.compute(X, self.daal_model_)
res = lr_res.prediction
if res.shape[1] == 1 and self.coef_.ndim == 1:
res = np.ravel(r... | C')
if self.coef_.shape[0] == 1 and y_.ndim == 1:
self.coef_ = np.ravel(self.coef_)
self.intercept_ = self.intercept_[0]
return self
def _daal4py_predict(self, X):
| 64 | 64 | 115 | 11 | 52 | Surfndez/daal4py | daal4py/sklearn/linear_model/linear.py | Python | _daal4py_predict | _daal4py_predict | 71 | 84 | 71 | 71 | bdaafee7ae367fc55b4d16e1870927a59a717883 | bigcode/the-stack | train |
9d5673799ab79e2b1daae495 | train | function | def _daal4py_fit(self, X, y_):
y = make2d(y_)
X_fptype = getFPType(X)
try:
lr_algorithm = daal4py.linear_regression_training(
fptype=X_fptype,
interceptFlag=bool(self.fit_intercept),
method='defaultDense'
)
lr_res = lr_algorithm.compute(X, y)
... | def _daal4py_fit(self, X, y_):
| y = make2d(y_)
X_fptype = getFPType(X)
try:
lr_algorithm = daal4py.linear_regression_training(
fptype=X_fptype,
interceptFlag=bool(self.fit_intercept),
method='defaultDense'
)
lr_res = lr_algorithm.compute(X, y)
except RuntimeError:
# ... | _lsqr
from sklearn.linear_model import LinearRegression as LinearRegression_original
try:
from sklearn.utils._joblib import Parallel, delayed
except ImportError:
from sklearn.externals.joblib import Parallel, delayed
import daal4py
from ..utils import (make2d, getFPType)
def _daal4py_fit(self, X, y_):
| 78 | 78 | 261 | 14 | 64 | Surfndez/daal4py | daal4py/sklearn/linear_model/linear.py | Python | _daal4py_fit | _daal4py_fit | 36 | 68 | 36 | 36 | 1f431391e209a936813d6226114390efad0e8c6c | bigcode/the-stack | train |
644de68d445120c9fc1e6339 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primar... | class Migration(migrations.Migration):
| initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_nam... | # Generated by Django 2.2.3 on 2019-08-08 03:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 118 | 7 | 43 | sv-team-yourchef/Server | onlyyou/users/migrations/0001_initial.py | Python | Migration | Migration | 8 | 25 | 8 | 9 | c2cc5e24d4b9745f2bfa59c16595b1f8c0277640 | bigcode/the-stack | train |
58ef1b439b949758e35f023a | train | function | def get_data():
for country_code in country_codes:
country_data = [",".join(header)] + get_pages(country_code)
write_to_file(country_code, country_data)
| def get_data():
| for country_code in country_codes:
country_data = [",".join(header)] + get_pages(country_code)
write_to_file(country_code, country_data)
| _dir):
os.makedirs(output_dir)
with open(f"{output_dir}/{time.strftime('%y.%d.%m')}_{country_code}_videos.csv", "w+", encoding='utf-8') as file:
for row in country_data:
file.write(f"{row}\n")
def get_data():
| 64 | 64 | 37 | 4 | 60 | devianpctek/TeleScraper | scraper.py | Python | get_data | get_data | 151 | 154 | 151 | 151 | 57adcdb457a951d8876cab5b568c9c7d88610af1 | bigcode/the-stack | train |
ead80e3e900ef048dbc092bc | train | function | def write_to_file(country_code, country_data):
print(f"Writing {country_code} data to file...")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(f"{output_dir}/{time.strftime('%y.%d.%m')}_{country_code}_videos.csv", "w+", encoding='utf-8') as file:
for row in country_d... | def write_to_file(country_code, country_data):
| print(f"Writing {country_code} data to file...")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(f"{output_dir}/{time.strftime('%y.%d.%m')}_{country_code}_videos.csv", "w+", encoding='utf-8') as file:
for row in country_data:
file.write(f"{row}\n")
| not None else next_page_token
# Get all of the items as a list and let get_videos return the needed features
items = video_data_page.get('items', [])
country_data += get_videos(items)
return country_data
def write_to_file(country_code, country_data):
| 64 | 64 | 91 | 10 | 53 | devianpctek/TeleScraper | scraper.py | Python | write_to_file | write_to_file | 140 | 149 | 140 | 141 | 2832acfd15e9c7ba13c8820ade17283c9fe95fcb | bigcode/the-stack | train |
850514e42d3335055ce5ed52 | train | function | def setup(api_path, code_path):
with open(api_path, 'r') as file:
api_key = file.readline().strip()
with open(code_path) as file:
country_codes = [x.rstrip() for x in file]
return api_key, country_codes
| def setup(api_path, code_path):
| with open(api_path, 'r') as file:
api_key = file.readline().strip()
with open(code_path) as file:
country_codes = [x.rstrip() for x in file]
return api_key, country_codes
| tags", "view_count", "likes", "dislikes",
"comment_count", "thumbnail_link", "comments_disabled",
"ratings_disabled", "description","Duration"]
#I declared this as global so I can read it from the duration code
api_key = ''
def set... | 64 | 64 | 59 | 8 | 56 | devianpctek/TeleScraper | scraper.py | Python | setup | setup | 24 | 31 | 24 | 24 | fc2dfdf02426efcc91608688b7736fb2008816f3 | bigcode/the-stack | train |
b1e4674378bb45be476269c6 | train | function | def api_request(page_token, country_code,api):
# Builds the URL and requests the JSON from it
request_url = f'https://www.googleapis.com/youtube/v3/videos?part=id,statistics,snippet{page_token}chart=mostPopular®ionCode={country_code}&maxResults=50&key={api_key}'
request = requests.get(str(request_url))
... | def api_request(page_token, country_code,api):
# Builds the URL and requests the JSON from it
| request_url = f'https://www.googleapis.com/youtube/v3/videos?part=id,statistics,snippet{page_token}chart=mostPopular®ionCode={country_code}&maxResults=50&key={api_key}'
request = requests.get(str(request_url))
#print (request.json())
if request.status_code == 429:
print("Temp-Banned due t... | any character from the unsafe characters list and surrounds the whole item in quotes
for ch in unsafe_characters:
feature = str(feature).replace(ch, "")
return f'"{feature}"'
def api_request(page_token, country_code,api):
# Builds the URL and requests the JSON from it
| 64 | 64 | 123 | 23 | 41 | devianpctek/TeleScraper | scraper.py | Python | api_request | api_request | 41 | 50 | 41 | 42 | afdbe742155d7f666bff83f38a02ec1c08e05830 | bigcode/the-stack | train |
392565c969e611863cf48c8e | train | function | def get_videos(items):
lines = []
for video in items:
comments_disabled = False
ratings_disabled = False
#print (video)
# We can assume something is wrong with the video if it has no statistics, often this means it has been deleted
# so we can just skip it
if... | def get_videos(items):
| lines = []
for video in items:
comments_disabled = False
ratings_disabled = False
#print (video)
# We can assume something is wrong with the video if it has no statistics, often this means it has been deleted
# so we can just skip it
if "statistics" not in video:
... | return f'"{feature}"'
def api_request(page_token, country_code,api):
# Builds the URL and requests the JSON from it
request_url = f'https://www.googleapis.com/youtube/v3/videos?part=id,statistics,snippet{page_token}chart=mostPopular®ionCode={country_code}&maxResults=50&key={api_key}'
request = req... | 176 | 176 | 588 | 7 | 169 | devianpctek/TeleScraper | scraper.py | Python | get_videos | get_videos | 58 | 116 | 58 | 59 | 46dfa7b3a2b904b08423e7a4ca9964117f87b10e | bigcode/the-stack | train |
b0c82380d2cf64e7add1fb06 | train | function | def prepare_feature(feature):
# Removes any character from the unsafe characters list and surrounds the whole item in quotes
for ch in unsafe_characters:
feature = str(feature).replace(ch, "")
return f'"{feature}"'
| def prepare_feature(feature):
# Removes any character from the unsafe characters list and surrounds the whole item in quotes
| for ch in unsafe_characters:
feature = str(feature).replace(ch, "")
return f'"{feature}"'
| file:
api_key = file.readline().strip()
with open(code_path) as file:
country_codes = [x.rstrip() for x in file]
return api_key, country_codes
def prepare_feature(feature):
# Removes any character from the unsafe characters list and surrounds the whole item in quotes
| 64 | 64 | 49 | 23 | 40 | devianpctek/TeleScraper | scraper.py | Python | prepare_feature | prepare_feature | 34 | 38 | 34 | 35 | 3b388edc1fae2eae504ef91fff5ad9fb5f4111b2 | bigcode/the-stack | train |
8ed34cb02a288e326be79274 | train | function | def get_tags(tags_list):
# Takes a list of tags, prepares each tag and joins them into a string by the pipe character
return prepare_feature("|".join(tags_list))
| def get_tags(tags_list):
# Takes a list of tags, prepares each tag and joins them into a string by the pipe character
| return prepare_feature("|".join(tags_list))
| ())
if request.status_code == 429:
print("Temp-Banned due to excess requests, please wait and continue later")
sys.exit()
return request.json()
def get_tags(tags_list):
# Takes a list of tags, prepares each tag and joins them into a string by the pipe character
| 64 | 64 | 38 | 28 | 36 | devianpctek/TeleScraper | scraper.py | Python | get_tags | get_tags | 53 | 55 | 53 | 54 | e123a58f7c806f9ed8f50f6c214f20f24c9fad07 | bigcode/the-stack | train |
80e193169a99090cae6fde0d | train | function | def get_pages(country_code, next_page_token='&'):
country_data = []
# Because the API uses page tokens (which are literally just the same function of numbers everywhere) it is much
# more inconvenient to iterate over pages, but that is what is done here.
while next_page_token is not None:
# ... | def get_pages(country_code, next_page_token='&'):
| country_data = []
# Because the API uses page tokens (which are literally just the same function of numbers everywhere) it is much
# more inconvenient to iterate over pages, but that is what is done here.
while next_page_token is not None:
# A page of data i.e. a list of videos and all neede... | video_id] + features + [prepare_feature(x) for x in [trending_date, tags, view_count, likes, dislikes,
comment_count, thumbnail_link, comments_disabled,
ratings_disabled, descrip... | 70 | 70 | 236 | 12 | 57 | devianpctek/TeleScraper | scraper.py | Python | get_pages | get_pages | 119 | 137 | 119 | 119 | 26c71af041f01b325893f30af9cfda86f0c40ba1 | bigcode/the-stack | train |
c6b457cb566eb8128abe96dc | train | function | def set_reminder_time(update,context):
text = update.message.text
regex = r"^\s*([0-1]?[0-9]|2[0-3]):[0-5][0-9]\s*$"
if context.user_data["tz"] is None:
reply_text = "Hey, I have realised you have yet to set your time-zone. " \
"I cannot properly send you reminders without it :... | def set_reminder_time(update,context):
| text = update.message.text
regex = r"^\s*([0-1]?[0-9]|2[0-3]):[0-5][0-9]\s*$"
if context.user_data["tz"] is None:
reply_text = "Hey, I have realised you have yet to set your time-zone. " \
"I cannot properly send you reminders without it :( " \
"Would you l... | '
'time do you normally intend to work out? (eg. enter 19:00 '
'if you plan to workout at 7pm)'
.format(", ".join(context.user_data["schedule"])),
reply_markup=ReplyKeyboardRemove())
... | 73 | 73 | 245 | 9 | 63 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | set_reminder_time | set_reminder_time | 63 | 84 | 63 | 63 | c8565ea3f4b36607e82deed705ca9e9b3aece745 | bigcode/the-stack | train |
2ab1f3bc55ea95f099ce8c16 | train | function | def save_exercise(update, context):
tz = context.user_data["tz"]
current_exercise = Exercise(tz)
if "exercise" in context.user_data :
if context.user_data["exercise"][-1] != current_exercise: # prevent multiple tracking of exercise in the same day
context.user_data["exercise"].append(cur... | def save_exercise(update, context):
| tz = context.user_data["tz"]
current_exercise = Exercise(tz)
if "exercise" in context.user_data :
if context.user_data["exercise"][-1] != current_exercise: # prevent multiple tracking of exercise in the same day
context.user_data["exercise"].append(current_exercise)
else:
co... | (excuse)
else:
context.user_data["excuse"] = [excuse]
update.message.reply_text(text="That's alright, try not to miss your schedule the next time",
reply_markup=Markups.main_markup)
return States.CHOOSING
def save_exercise(update, context):
| 64 | 64 | 122 | 8 | 55 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | save_exercise | save_exercise | 165 | 176 | 165 | 165 | 1c3c11161ce2b26f980ec0b3a5c45f940312c223 | bigcode/the-stack | train |
d1533dcb44bcc0cbdb603cc8 | train | function | def show_data(update, context):
update.message.reply_text("This is what you already told me:\n"
"{}".format(facts_to_str(context.user_data)), reply_markup=Markups.main_markup)
return States.CHOOSING
| def show_data(update, context):
| update.message.reply_text("This is what you already told me:\n"
"{}".format(facts_to_str(context.user_data)), reply_markup=Markups.main_markup)
return States.CHOOSING
| elif key == "excuse":
facts.append("Here are the reasons in which you missed out on exercising : ")
for excuse in user_data["excuse"]:
facts.append(excuse.datetime + " - " + excuse.text)
return "\n".join(facts)
def show_data(update, context):
| 64 | 64 | 51 | 7 | 57 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | show_data | show_data | 224 | 227 | 224 | 224 | 847532106cdf5adf7f560622c9cfd26b180b1e99 | bigcode/the-stack | train |
90b9fa006c3632a472c97372 | train | function | def start(update, context):
user = update.message.from_user
name = user.first_name
reply_text = "Hi " + name + "! "
if context.user_data:
reply_text = "What would you like to do now?"
else:
reply_text += "I am a personal fitness trainer bot, it is nice to meet you!" \
... | def start(update, context):
| user = update.message.from_user
name = user.first_name
reply_text = "Hi " + name + "! "
if context.user_data:
reply_text = "What would you like to do now?"
else:
reply_text += "I am a personal fitness trainer bot, it is nice to meet you!" \
"I am here to help yo... | context.user_data["exercise"].append(current_exercise)
else:
context.user_data["exercise"] = [current_exercise]
update.message.reply_text("Good job in completing your workout for today!", reply_markup=Markups.main_markup)
return States.CHOOSING
def start(update, context):
| 64 | 64 | 183 | 6 | 57 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | start | start | 179 | 195 | 179 | 179 | 0ab2bc67cd8eb80d03c345af18f65e31e11a071b | bigcode/the-stack | train |
9cac92ef3d8efbc84da9e7e0 | train | function | def save_schedule(update, context):
text = update.message.text
if "Yup, that's all!" != text:
if context.user_data and "schedule" in context.user_data \
and text not in context.user_data["schedule"]:
current_schedule = context.user_data["schedule"]
current_schedul... | def save_schedule(update, context):
| text = update.message.text
if "Yup, that's all!" != text:
if context.user_data and "schedule" in context.user_data \
and text not in context.user_data["schedule"]:
current_schedule = context.user_data["schedule"]
current_schedule.append(text)
context.u... | , please type your new schedule"
del context.user_data["schedule"]
else:
reply_text = "Ok, please enter your preferred schedule "
update.message.reply_text(reply_text, reply_markup=Markups.schedule_markup)
return States.CHOOSING_SCHEDULE
def save_schedule(update, context):
| 64 | 64 | 215 | 7 | 56 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | save_schedule | save_schedule | 39 | 60 | 39 | 39 | f7647920a86adfd5d04b26aeeca2a0cbc8fd8289 | bigcode/the-stack | train |
59fe7fd1009faebde1686403 | train | function | def done(update, context):
if 'choice' in context.user_data:
del context.user_data['choice']
update.message.reply_text("I learned these facts about you:\n"
"{}"
"\nPlease type /start to use me again!".format(facts_to_str(context.user_data)))
... | def done(update, context):
| if 'choice' in context.user_data:
del context.user_data['choice']
update.message.reply_text("I learned these facts about you:\n"
"{}"
"\nPlease type /start to use me again!".format(facts_to_str(context.user_data)))
return ConversationHandl... | "\n".join(facts)
def show_data(update, context):
update.message.reply_text("This is what you already told me:\n"
"{}".format(facts_to_str(context.user_data)), reply_markup=Markups.main_markup)
return States.CHOOSING
def done(update, context):
| 64 | 64 | 69 | 6 | 57 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | done | done | 230 | 237 | 230 | 230 | 0fc464d3652f1510a972fff2bf39744d4e0eb79b | bigcode/the-stack | train |
bebf64b0993f95122abc60b3 | train | function | def callback_reminder(context: CallbackContext):
send_reminder()
| def callback_reminder(context: CallbackContext):
| send_reminder()
| '
'(With 1 being "Meh, the food looked good and colourful" to 5 being "I am '
'so hungry I would enjoy eating hostel food right now"', reply_markup=Markups.scale_markup)
return States.TRACK_SNACK
def callback_reminder(context: CallbackContext):
| 64 | 64 | 14 | 9 | 54 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | callback_reminder | callback_reminder | 137 | 138 | 137 | 137 | 51a0537e313b3e6b76d765011b0562571e8f314e | bigcode/the-stack | train |
321dadcdc06e0c0e153178a0 | train | function | def track_snacking(update,context):
update.message.reply_text("Try to be as descriptive as you can, best if you know the exact quantity "
"the meal. Eg. 2 slices of wholemeal bread with peanut butter")
return States.TRACK_SNACK
| def track_snacking(update,context):
| update.message.reply_text("Try to be as descriptive as you can, best if you know the exact quantity "
"the meal. Eg. 2 slices of wholemeal bread with peanut butter")
return States.TRACK_SNACK
| "] = [current_weight]
update.message.reply_text('Alright, I have updated your current weight of :'
' {}kg'.format(context.user_data["weight"][-1].value), reply_markup=Markups.main_markup)
return States.CHOOSING
def track_snacking(update,context):
| 64 | 64 | 57 | 8 | 55 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | track_snacking | track_snacking | 108 | 111 | 108 | 108 | b46d2b4862abbc545ac1075170d7761d2de58fbe | bigcode/the-stack | train |
d2fdf00d6233dfe357d8285e | train | function | def track_exercise(update, context):
update.message.reply_text(text="Hey, have you done your exercise that you planned for today?",
reply_markup=Markups.reminder_markup)
return States.REMINDER
| def track_exercise(update, context):
| update.message.reply_text(text="Hey, have you done your exercise that you planned for today?",
reply_markup=Markups.reminder_markup)
return States.REMINDER
| looked good and colourful" to 5 being "I am '
'so hungry I would enjoy eating hostel food right now"', reply_markup=Markups.scale_markup)
return States.TRACK_SNACK
def callback_reminder(context: CallbackContext):
send_reminder()
def track_exercise(update, context):
| 64 | 64 | 45 | 8 | 56 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | track_exercise | track_exercise | 140 | 143 | 140 | 140 | fa0c676514682214bd98b95174015b7f05e3d822 | bigcode/the-stack | train |
ec426d0bda43ee69dffbc6bd | train | function | def track_weight(update, context):
update.message.reply_text("Enter your weight in kg, for example: 54.5")
return States.TRACK_WEIGHT
| def track_weight(update, context):
| update.message.reply_text("Enter your weight in kg, for example: 54.5")
return States.TRACK_WEIGHT
| _markup)
return States.CHOOSING
else:
reply_text = "Opps, please write the time like '13:00' if you intend to work out at 1pm"
update.message.reply_text(reply_text)
return States.GET_TIMEZONE
def track_weight(update, context):
| 64 | 64 | 34 | 7 | 56 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | track_weight | track_weight | 87 | 89 | 87 | 87 | a02555a9e3579a0acbe41294df2081c30233272a | bigcode/the-stack | train |
91a558171d11e8317420937c | train | function | def set_schedule(update, context):
if context.user_data and "schedule" in context.user_data:
reply_text = "You are now updating your schedule, please type your new schedule"
del context.user_data["schedule"]
else:
reply_text = "Ok, please enter your preferred schedule "
update.messag... | def set_schedule(update, context):
| if context.user_data and "schedule" in context.user_data:
reply_text = "You are now updating your schedule, please type your new schedule"
del context.user_data["schedule"]
else:
reply_text = "Ok, please enter your preferred schedule "
update.message.reply_text(reply_text, reply_mark... | (lng=message.location.longitude, lat=message.location.latitude))
context.user_data["tz"] = tz
reply_text = "Got it, thanks!"
update.message.reply_text(reply_text, reply_markup=Markups.main_markup)
return States.CHOOSING
def set_schedule(update, context):
| 64 | 64 | 89 | 7 | 56 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | set_schedule | set_schedule | 29 | 36 | 29 | 29 | 2e91cd1f07c33b06b78e47f89f8d8eea04c62ed0 | bigcode/the-stack | train |
effd7ea5f0a6ada23b9522e6 | train | function | def save_snack(update,context):
text = update.message.text # could be either hunger_level or description
tz = context.user_data["tz"]
if "snack" in context.user_data:
last_snack = context.user_data["snack"][-1]
if last_snack.hunger_level is None:
last_snack.hunger_level = text
... | def save_snack(update,context):
| text = update.message.text # could be either hunger_level or description
tz = context.user_data["tz"]
if "snack" in context.user_data:
last_snack = context.user_data["snack"][-1]
if last_snack.hunger_level is None:
last_snack.hunger_level = text
context.user_data["sna... | Markups.main_markup)
return States.CHOOSING
def track_snacking(update,context):
update.message.reply_text("Try to be as descriptive as you can, best if you know the exact quantity "
"the meal. Eg. 2 slices of wholemeal bread with peanut butter")
return States.TRACK_SNACK
def ... | 78 | 78 | 263 | 8 | 69 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | save_snack | save_snack | 114 | 134 | 114 | 114 | 63a2101cbe7aa4e505b3666749e16f762c850b04 | bigcode/the-stack | train |
01f16de97b36c90cdb1f317d | train | function | def facts_to_str(user_data):
facts = list()
for key, value in user_data.items():
if key == "tz":
if user_data["tz"] is None:
facts.append("You have yet to set your timezone :(")
else:
facts.append("Your timezone is " + str(user_data['tz']))
... | def facts_to_str(user_data):
| facts = list()
for key, value in user_data.items():
if key == "tz":
if user_data["tz"] is None:
facts.append("You have yet to set your timezone :(")
else:
facts.append("Your timezone is " + str(user_data['tz']))
elif key == "weight":
... | ["tz"] = None # Tz is set to none unless user gives gives location
update.message.reply_text(reply_text, reply_markup=Markups.location_markup)
return States.GET_TIMEZONE
update.message.reply_text(reply_text,reply_markup=Markups.main_markup)
return States.CHOOSING
def facts_to_str(user_data):
| 73 | 73 | 244 | 7 | 65 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | facts_to_str | facts_to_str | 198 | 221 | 198 | 198 | c5772d7b414ea6d8719ec923450b5c220a7bef47 | bigcode/the-stack | train |
87bb9ca297d0e7d254ad46b5 | train | function | def get_excuse(update, context):
text = update.message.text
if text == Markups.reminder_keyboard[-1][0]:
update.message.reply_text(text="Oh no :( What happened?")
return States.REMINDER
else:
if "tz" in context.user_data:
excuse = Excuse(text, tz=context.user_data["tz"])
... | def get_excuse(update, context):
| text = update.message.text
if text == Markups.reminder_keyboard[-1][0]:
update.message.reply_text(text="Oh no :( What happened?")
return States.REMINDER
else:
if "tz" in context.user_data:
excuse = Excuse(text, tz=context.user_data["tz"])
else:
excuse ... | inder(context: CallbackContext):
send_reminder()
def track_exercise(update, context):
update.message.reply_text(text="Hey, have you done your exercise that you planned for today?",
reply_markup=Markups.reminder_markup)
return States.REMINDER
def get_excuse(update, context):
| 64 | 64 | 162 | 8 | 55 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | get_excuse | get_excuse | 146 | 162 | 146 | 146 | 5c1a3c52013e9a1182a08c151137690d7cb1b238 | bigcode/the-stack | train |
cf30cf53dadd3bc975fa731b | train | function | def set_time_zone(update, context):
if update.edited_message:
message = update.edited_message
else:
message = update.message
tf = TimezoneFinder()
tz = timezone(tf.timezone_at(lng=message.location.longitude, lat=message.location.latitude))
context.user_data["tz"] = tz
reply_text... | def set_time_zone(update, context):
| if update.edited_message:
message = update.edited_message
else:
message = update.message
tf = TimezoneFinder()
tz = timezone(tf.timezone_at(lng=message.location.longitude, lat=message.location.latitude))
context.user_data["tz"] = tz
reply_text = "Got it, thanks!"
update.mess... | ercise import Exercise
from sample.Snack import Snack
from sample.Weight import Weight
from pytz import timezone
from sample import States
from sample import Markups
from telegram.ext import ConversationHandler, CallbackContext
from sample.Reminder import send_reminder
import re
def set_time_zone(update, context):
| 64 | 64 | 104 | 8 | 55 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | set_time_zone | set_time_zone | 15 | 26 | 15 | 15 | 010fe5e7831e514eb3d6259a1de071abfdcba2e9 | bigcode/the-stack | train |
5197db17de2ef97665e6288d | train | function | def save_weight(update, context):
text = update.message.text.strip()
print(text)
if text[-2:].lower() == "kg":
text = text[:-2]
tz = context.user_data["tz"]
current_weight = Weight(text, tz=tz)
if "weight" in context.user_data:
context.user_data["weight"].append(current_weight)
... | def save_weight(update, context):
| text = update.message.text.strip()
print(text)
if text[-2:].lower() == "kg":
text = text[:-2]
tz = context.user_data["tz"]
current_weight = Weight(text, tz=tz)
if "weight" in context.user_data:
context.user_data["weight"].append(current_weight)
else:
context.user_data... | to work out at 1pm"
update.message.reply_text(reply_text)
return States.GET_TIMEZONE
def track_weight(update, context):
update.message.reply_text("Enter your weight in kg, for example: 54.5")
return States.TRACK_WEIGHT
def save_weight(update, context):
| 64 | 64 | 144 | 7 | 56 | kishore03109/PersonalTrainerBot | sample/Handlers.py | Python | save_weight | save_weight | 92 | 105 | 92 | 92 | 2d423c514f73f074dbf04a179b2ff5b27b2977e8 | bigcode/the-stack | train |
b53810e48975a7a914da9aae | train | function | def onCreate (tag, keys):
c = keys.get('c')
if not c: return
backlinkController(c)
| def onCreate (tag, keys):
| c = keys.get('c')
if not c: return
backlinkController(c)
| -frame',onCreate)
# can't use before-create-leo-frame because Qt dock's not ready
g.plugin_signon(__name__)
return ok
#@+node:ekr.20090616105756.3941: *3* onCreate
def onCreate (tag, keys):
| 64 | 64 | 28 | 8 | 55 | leonidborisenko/leo-editor | leo/plugins/backlink.py | Python | onCreate | onCreate | 951 | 956 | 951 | 952 | e1c80e68e628945c81f915c9ad73ed0096797368 | bigcode/the-stack | train |
cc758a4e55b86d578d194cf0 | train | function | def init ():
'''Return True if the plugin has loaded successfully.'''
ok = g.app.gui.guiName() != 'nullGui'
if ok:
g.registerHandler('after-create-leo-frame',onCreate)
# can't use before-create-leo-frame because Qt dock's not ready
g.plugin_signon(__name__)
return ok
| def init ():
| '''Return True if the plugin has loaded successfully.'''
ok = g.app.gui.guiName() != 'nullGui'
if ok:
g.registerHandler('after-create-leo-frame',onCreate)
# can't use before-create-leo-frame because Qt dock's not ready
g.plugin_signon(__name__)
return ok
| ,to,type_)
self.dests = dests
#@-others
#@+node:ekr.20140920145803.17995: ** top-level
#@+node:ekr.20090616105756.3940: *3* init
def init ():
| 64 | 64 | 76 | 4 | 59 | leonidborisenko/leo-editor | leo/plugins/backlink.py | Python | init | init | 942 | 949 | 942 | 942 | 7f167080236027ae450e154122c2cc0c014b347f | bigcode/the-stack | train |
457ecbbbce539031b077734c | train | class | class backlinkController:
"""Display and edit links in leo trees"""
#@+others
#@+node:ekr.20090616105756.3943: *3* __init__ & reloadSettings (backlinkController)
def __init__ (self,c):
'''Ctor for backlinkController class.'''
self.c = c
self.c.backlinkController = self
se... | class backlinkController:
| """Display and edit links in leo trees"""
#@+others
#@+node:ekr.20090616105756.3943: *3* __init__ & reloadSettings (backlinkController)
def __init__ (self,c):
'''Ctor for backlinkController class.'''
self.c = c
self.c.backlinkController = self
self.initIvars()
sel... | # - store attributes for link start/whole-link/end (name, weight)
#
# - restore dropped links (cut / paste or undo)?
# UI class signatures, main class signature
#
# UI classes must have (i.e. owner will call):
# - __init__(owner)
# - showMessage(txt, color=['black'|'red'])
# - enableDelete(bool) (also unch... | 256 | 256 | 5,905 | 4 | 251 | leonidborisenko/leo-editor | leo/plugins/backlink.py | Python | backlinkController | backlinkController | 87 | 730 | 87 | 87 | 31b4acdb64d1d6e54c82a412d23977778f160a62 | bigcode/the-stack | train |
37d01cf4913d5c9a3c3e9a47 | train | class | class ResourceState(object):
def __init__(self, args, instance_info):
self.args = args
self.instance_info = instance_info
self.state = None
self.volume_id = None
self.old_volume_id = None
self.snapshot_id = None
self.attached_device = None
def survey(sel... | class ResourceState(object):
| def __init__(self, args, instance_info):
self.args = args
self.instance_info = instance_info
self.state = None
self.volume_id = None
self.old_volume_id = None
self.snapshot_id = None
self.attached_device = None
def survey(self):
logger.debug('Loo... | ', metavar='COUNT', type=positive_int, default=None,
help='Number of provisioned I/O operations to assign to newly created '
'volumes. Make sure to choose an appropriate volume type to '
'match.')
argp.add_argument(
'--move-to-current-az', action='store_true', default=False... | 256 | 256 | 918 | 5 | 250 | Cobliteam/ebs_snatcher | ebs_snatcher/main.py | Python | ResourceState | ResourceState | 95 | 218 | 95 | 95 | 84f352c83b7464cad4362974385b435401feda64 | bigcode/the-stack | train |
74a8c6f7bb5d6b3be51638f5 | train | function | def positive_int(s):
n = int(s)
if n <= 0:
raise ValueError('Value must be positive: {}'.format(n))
return n
| def positive_int(s):
| n = int(s)
if n <= 0:
raise ValueError('Value must be positive: {}'.format(n))
return n
| there is a volume available in a different AZ than the "
"current one, instead of skipping it and looking for snapshots "
"by tag, try to move it to the current AZ, by cloning it and "
"deleting the original.")
return argp.parse_args()
def positive_int(s):
| 64 | 64 | 36 | 5 | 59 | Cobliteam/ebs_snatcher | ebs_snatcher/main.py | Python | positive_int | positive_int | 73 | 78 | 73 | 73 | 4c5077c87f06700407933a3905f27eff8e6819d4 | bigcode/the-stack | train |
0c5feb65f22348c719de5ba0 | train | function | def key_tag_pair(s):
if isinstance(s, bytes):
s = str(s, 'utf-8')
elif not isinstance(s, str):
raise TypeError('Input must be a string')
try:
key, value = s.split('=', 1)
except ValueError:
raise ValueError('Missing tag value: {}'.format(s))
return key, value
| def key_tag_pair(s):
| if isinstance(s, bytes):
s = str(s, 'utf-8')
elif not isinstance(s, str):
raise TypeError('Input must be a string')
try:
key, value = s.split('=', 1)
except ValueError:
raise ValueError('Missing tag value: {}'.format(s))
return key, value
| current AZ, by cloning it and "
"deleting the original.")
return argp.parse_args()
def positive_int(s):
n = int(s)
if n <= 0:
raise ValueError('Value must be positive: {}'.format(n))
return n
def key_tag_pair(s):
| 64 | 64 | 82 | 6 | 57 | Cobliteam/ebs_snatcher | ebs_snatcher/main.py | Python | key_tag_pair | key_tag_pair | 81 | 92 | 81 | 81 | 83ff0b0b0dc3850b4e3ed07ba5b20c3781bf8626 | bigcode/the-stack | train |
8f553413bbc24b1d4f357281 | train | function | def main():
logging.basicConfig(level=logging.DEBUG)
args = get_args()
instance_info = ebs.get_instance_info(args.instance_id)
resource_state = ResourceState(args, instance_info)
resource_state.survey()
resource_state.converge()
print(json.dumps(resource_state.to_json()))
return 0
| def main():
| logging.basicConfig(level=logging.DEBUG)
args = get_args()
instance_info = ebs.get_instance_info(args.instance_id)
resource_state = ResourceState(args, instance_info)
resource_state.survey()
resource_state.converge()
print(json.dumps(resource_state.to_json()))
return 0
| if self.old_volume_id:
ebs.delete_volume(volume_id=self.old_volume_id)
def to_json(self):
return {'volume_id': self.volume_id,
'attached_device': self.attached_device,
'result': self.state,
'src_snapshot_id': self.snapshot_id}
def main():
| 64 | 64 | 68 | 3 | 61 | Cobliteam/ebs_snatcher | ebs_snatcher/main.py | Python | main | main | 221 | 233 | 221 | 221 | f5eec96f44b3a20ed571524e33d9c13a77699ba3 | bigcode/the-stack | train |
f8520363a03b6228d4bba128 | train | function | def get_args(): # pragma: no cover
argp = argparse.ArgumentParser(
'ebs-snatcher',
description='Automatically provision AWS EBS volumes from snapshots')
argp.add_argument(
'--instance-id', metavar='ID', required=True,
help='Instance ID to attach volumes to')
argp.add_argumen... | def get_args(): # pragma: no cover
| argp = argparse.ArgumentParser(
'ebs-snatcher',
description='Automatically provision AWS EBS volumes from snapshots')
argp.add_argument(
'--instance-id', metavar='ID', required=True,
help='Instance ID to attach volumes to')
argp.add_argument(
'--volume-id-tag', metava... | from __future__ import unicode_literals
from builtins import str, bytes
import argparse
import json
import logging
import random
from . import ebs
logger = logging.getLogger('ebs-snatcher.main')
def get_args(): # pragma: no cover
| 57 | 191 | 639 | 11 | 46 | Cobliteam/ebs_snatcher | ebs_snatcher/main.py | Python | get_args | get_args | 15 | 70 | 15 | 15 | 8700c2fa353def68928ffad66a57587a3438c622 | bigcode/the-stack | train |
57c9aff630390643e747e1ea | train | function | def simple_fixed_prediction_classifier_extra_fields(export_path,
eval_export_path):
"""Exports a simple fixed prediction classifier that parses extra fields."""
estimator = tf.estimator.Estimator(
model_fn=fixed_prediction_classifier.model_fn)
estimator.t... | def simple_fixed_prediction_classifier_extra_fields(export_path,
eval_export_path):
| """Exports a simple fixed prediction classifier that parses extra fields."""
estimator = tf.estimator.Estimator(
model_fn=fixed_prediction_classifier.model_fn)
estimator.train(input_fn=fixed_prediction_classifier.train_input_fn, steps=1)
serving_input_receiver_fn = (
tf.estimator.export.build_pars... | _int" features.
"""
from __future__ import absolute_import
from __future__ import division
# Standard __future__ imports
from __future__ import print_function
# Standard Imports
import tensorflow as tf
from tensorflow_model_analysis.eval_saved_model import export
from tensorflow_model_analysis.eval_saved_model.exampl... | 97 | 97 | 325 | 15 | 81 | yupbank/model-analysis | tensorflow_model_analysis/eval_saved_model/example_trainers/fixed_prediction_classifier_extra_fields.py | Python | simple_fixed_prediction_classifier_extra_fields | simple_fixed_prediction_classifier_extra_fields | 35 | 68 | 35 | 36 | 586412e7157461649dad4d5f9b3d10ff6bc23dfe | bigcode/the-stack | train |
a6db8bacc6fa260a0e96a0ab | train | class | class ToTensor:
def __init__(self):
self.transform = transforms.ToTensor()
def __call__(self, x):
return self.transform(x)
| class ToTensor:
| def __init__(self):
self.transform = transforms.ToTensor()
def __call__(self, x):
return self.transform(x)
| import torch
from torchvision import transforms
class ToTensor:
| 12 | 64 | 34 | 4 | 7 | Bhuvan-21/SyferText | src/syfervision/transforms/image_modelling.py | Python | ToTensor | ToTensor | 5 | 10 | 5 | 5 | b43aac273cf1511b851fd810eb31b4d71cded44a | bigcode/the-stack | train |
8821af5c5bd0f739641318c7 | train | class | class Resize:
def __init__(self, size):
self.transform = transforms.Resize(size)
def __call__(self, x):
return self.transform(x)
| class Resize:
| def __init__(self, size):
self.transform = transforms.Resize(size)
def __call__(self, x):
return self.transform(x)
| import torch
from torchvision import transforms
class ToTensor:
def __init__(self):
self.transform = transforms.ToTensor()
def __call__(self, x):
return self.transform(x)
class Resize:
| 45 | 64 | 35 | 3 | 42 | Bhuvan-21/SyferText | src/syfervision/transforms/image_modelling.py | Python | Resize | Resize | 13 | 18 | 13 | 13 | 6e2c07d495333eb7a37738754fe48625d9cd6eba | bigcode/the-stack | train |
5fa35c609a62c3666adb73fb | train | class | class WysiHtmlTextArea(forms.widgets.Textarea):
template = '' # TODO: make a template..
def render(self, name, value, attrs=None):
baseVal = super(WysiHtmlTextArea, self).render(name, value, attrs)
# return render_to_string(template, {'textarea': baseVal}) #TODO: implement this instead on the... | class WysiHtmlTextArea(forms.widgets.Textarea):
| template = '' # TODO: make a template..
def render(self, name, value, attrs=None):
baseVal = super(WysiHtmlTextArea, self).render(name, value, attrs)
# return render_to_string(template, {'textarea': baseVal}) #TODO: implement this instead on the above
return u'<div cradmin_legacy_wysi... | from __future__ import unicode_literals
from django import forms
class WysiHtmlTextArea(forms.widgets.Textarea):
| 24 | 64 | 99 | 11 | 12 | appressoas/cradmin_legacy | cradmin_legacy/wysihtml5/widgets.py | Python | WysiHtmlTextArea | WysiHtmlTextArea | 5 | 12 | 5 | 5 | 79871ba39fdaa07d79e4aea29377b85f45d23aa6 | bigcode/the-stack | train |
3cce59627de6280a586ba2e5 | train | class | @Group.register
class FullRankGroup(Group):
"""Full Rank approximation to the posterior where Multivariate Gaussian family
is fitted to minimize KL divergence from True posterior. In contrast to
MeanField approach correlations between variables are taken in account. The
main drawback of the method is co... | @Group.register
class FullRankGroup(Group):
| """Full Rank approximation to the posterior where Multivariate Gaussian family
is fitted to minimize KL divergence from True posterior. In contrast to
MeanField approach correlations between variables are taken in account. The
main drawback of the method is computational cost.
"""
__param_spec__... | ()
update_start_vals(start_, self.model.test_point, self.model)
start = start_
if self.batched:
start = start[self.group[0].name][0]
else:
start = self.bij.map(start)
rho = np.zeros((self.ddim,))
if self.batched:
start = np.tile... | 256 | 256 | 905 | 10 | 246 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | FullRankGroup | FullRankGroup | 114 | 224 | 114 | 115 | 93f21069d6360044e0c1c1bec4c95c8ee0ef8b26 | bigcode/the-stack | train |
9c8d113265d8e97ae936fd20 | train | class | class FullRank(SingleGroupApproximation):
__doc__ = """**Single Group Full Rank Approximation**
""" + str(FullRankGroup.__doc__)
_group_class = FullRankGroup
| class FullRank(SingleGroupApproximation):
| __doc__ = """**Single Group Full Rank Approximation**
""" + str(FullRankGroup.__doc__)
_group_class = FullRankGroup
| 0].__dir__())
return list(sorted(d))
class MeanField(SingleGroupApproximation):
__doc__ = """**Single Group Mean Field Approximation**
""" + str(MeanFieldGroup.__doc__)
_group_class = MeanFieldGroup
class FullRank(SingleGroupApproximation):
| 64 | 64 | 43 | 9 | 54 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | FullRank | FullRank | 569 | 573 | 569 | 569 | 5fbeb9a893aa6d024205670cdf9da2e3f62b7e1c | bigcode/the-stack | train |
bfb06caa537140a9ac56f766 | train | class | class NormalizingFlow(SingleGroupApproximation):
__doc__ = """**Single Group Normalizing Flow Approximation**
""" + str(NormalizingFlowGroup.__doc__)
_group_class = NormalizingFlowGroup
def __init__(self, flow=NormalizingFlowGroup.default_flow, *args, **kwargs):
kwargs['flow'] = flow
s... | class NormalizingFlow(SingleGroupApproximation):
| __doc__ = """**Single Group Normalizing Flow Approximation**
""" + str(NormalizingFlowGroup.__doc__)
_group_class = NormalizingFlowGroup
def __init__(self, flow=NormalizingFlowGroup.default_flow, *args, **kwargs):
kwargs['flow'] = flow
super().__init__(*args, **kwargs)
| trace contained in the empirical approximation
"""
node = self.to_flat_input(node)
def sample(post):
return theano.clone(node, {self.input: post})
nodes, _ = theano.scan(sample, self.histogram)
return nodes
class NormalizingFlow(SingleGroupApproximation):
| 64 | 64 | 87 | 10 | 53 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | NormalizingFlow | NormalizingFlow | 608 | 616 | 608 | 608 | a27c3ae30b2328ae2f493edf2fa3998372688c58 | bigcode/the-stack | train |
cb4303782f8d0d3e64d3f2fb | train | class | class SingleGroupApproximation(Approximation):
"""Base class for Single Group Approximation"""
_group_class = None
def __init__(self, *args, **kwargs):
local_rv = kwargs.get('local_rv')
groups = [self._group_class(None, *args, **kwargs)]
if local_rv is not None:
groups.e... | class SingleGroupApproximation(Approximation):
| """Base class for Single Group Approximation"""
_group_class = None
def __init__(self, *args, **kwargs):
local_rv = kwargs.get('local_rv')
groups = [self._group_class(None, *args, **kwargs)]
if local_rv is not None:
groups.extend([Group([v], params=p, local=True, model=k... | Returns
-------
trace: class:`pymc3.backends.base.MultiTrace`
Samples drawn from variational posterior.
"""
return approx.sample(draws=draws, include_transformed=include_transformed)
# single group shortcuts exported to user
class SingleGroupApproximation(Approximation):
| 64 | 64 | 176 | 9 | 54 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | SingleGroupApproximation | SingleGroupApproximation | 541 | 559 | 541 | 541 | 140e640cd969e908354a819619c82d885c184a85 | bigcode/the-stack | train |
af7195ad8645f407be56fba4 | train | class | @Group.register
class EmpiricalGroup(Group):
"""Builds Approximation instance from a given trace,
it has the same interface as variational approximation
"""
supports_batched = False
has_logq = False
__param_spec__ = dict(histogram=('s', 'd'))
short_name = 'empirical'
@change_flags(compu... | @Group.register
class EmpiricalGroup(Group):
| """Builds Approximation instance from a given trace,
it has the same interface as variational approximation
"""
supports_batched = False
has_logq = False
__param_spec__ = dict(histogram=('s', 'd'))
short_name = 'empirical'
@change_flags(compute_test_value='off')
def __init_group__(s... |
def symbolic_logq_not_scaled(self):
z = self.symbolic_random
if self.batched:
def logq(z_b, mu_b, L_b):
return pm.MvNormal.dist(mu=mu_b, chol=L_b).logp(z_b)
# it's gonna be so slow
# scan is computed over batch and then summed up
# out... | 256 | 256 | 948 | 10 | 245 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | EmpiricalGroup | EmpiricalGroup | 227 | 343 | 227 | 228 | da266b92dc016fe32805290b2ff727aa54c35276 | bigcode/the-stack | train |
1a1e5eb822ad08e062addb85 | train | class | class Empirical(SingleGroupApproximation):
__doc__ = """**Single Group Full Rank Approximation**
""" + str(EmpiricalGroup.__doc__)
_group_class = EmpiricalGroup
def __init__(self, trace=None, size=None, **kwargs):
if kwargs.get('local_rv', None) is not None:
raise opvi.LocalGroupEr... | class Empirical(SingleGroupApproximation):
| __doc__ = """**Single Group Full Rank Approximation**
""" + str(EmpiricalGroup.__doc__)
_group_class = EmpiricalGroup
def __init__(self, trace=None, size=None, **kwargs):
if kwargs.get('local_rv', None) is not None:
raise opvi.LocalGroupError('Empirical approximation does not suppo... | .__doc__)
_group_class = MeanFieldGroup
class FullRank(SingleGroupApproximation):
__doc__ = """**Single Group Full Rank Approximation**
""" + str(FullRankGroup.__doc__)
_group_class = FullRankGroup
class Empirical(SingleGroupApproximation):
| 64 | 64 | 216 | 9 | 54 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | Empirical | Empirical | 576 | 605 | 576 | 576 | aaca1cdb4039dc65a60b4d029df2a81223ee599a | bigcode/the-stack | train |
0d3b05b2632a78957f590f54 | train | class | class MeanField(SingleGroupApproximation):
__doc__ = """**Single Group Mean Field Approximation**
""" + str(MeanFieldGroup.__doc__)
_group_class = MeanFieldGroup
| class MeanField(SingleGroupApproximation):
| __doc__ = """**Single Group Mean Field Approximation**
""" + str(MeanFieldGroup.__doc__)
_group_class = MeanFieldGroup
| '))
def __getattr__(self, item):
return getattr(self.groups[0], item)
def __dir__(self):
d = set(super().__dir__())
d.update(self.groups[0].__dir__())
return list(sorted(d))
class MeanField(SingleGroupApproximation):
| 64 | 64 | 43 | 9 | 55 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | MeanField | MeanField | 562 | 566 | 562 | 562 | 9cb1cc433ed0803eac8224537adabf9d33d97b72 | bigcode/the-stack | train |
cdcaad9a27cadcac6d0e0ea3 | train | class | @Group.register
class MeanFieldGroup(Group):
R"""Mean Field approximation to the posterior where spherical Gaussian family
is fitted to minimize KL divergence from True posterior. It is assumed
that latent space variables are uncorrelated that is the main drawback
of the method
"""
__param_spec_... | @Group.register
class MeanFieldGroup(Group):
| R"""Mean Field approximation to the posterior where spherical Gaussian family
is fitted to minimize KL divergence from True posterior. It is assumed
that latent space variables are uncorrelated that is the main drawback
of the method
"""
__param_spec__ = dict(mu=('d', ), rho=('d', ))
short_n... | the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import theano
from theano import tensor as tt
import pymc3 as pm
from pymc3.distributions.dist_math import rho2sigma
from . import opvi
from pymc3.variational.opvi import Group, Approximation, node_p... | 162 | 162 | 542 | 10 | 152 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | MeanFieldGroup | MeanFieldGroup | 38 | 111 | 38 | 39 | 1a667c82796901e335e4d153be9764da4ebb1f7f | bigcode/the-stack | train |
6f3f9ff89215eb9646c4791c | train | class | class NormalizingFlowGroup(Group):
R"""Normalizing flow is a series of invertible transformations on initial distribution.
.. math::
z_K &= f_K \circ \dots \circ f_2 \circ f_1(z_0) \\
& z_0 \sim \mathcal{N}(0, 1)
In that case we can compute tractable density for the flow.
.. math::
... | class NormalizingFlowGroup(Group):
| R"""Normalizing flow is a series of invertible transformations on initial distribution.
.. math::
z_K &= f_K \circ \dots \circ f_2 \circ f_1(z_0) \\
& z_0 \sim \mathcal{N}(0, 1)
In that case we can compute tractable density for the flow.
.. math::
\ln q_K(z_K) = \ln q_0(z_0)... | self.histogram[self.randidx(size)])
else:
if deterministic:
return tt.repeat(
self.mean.dimshuffle('x', 0),
size if size is not None else 1, -1)
else:
return self.histogram[self.randidx(size)]
@property
def... | 256 | 256 | 1,546 | 7 | 249 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | NormalizingFlowGroup | NormalizingFlowGroup | 346 | 517 | 346 | 346 | 6be751352eade2fd0f297eac5308e453437987b8 | bigcode/the-stack | train |
d2452976a8cc08e46da67366 | train | function | def sample_approx(approx, draws=100, include_transformed=True):
"""Draw samples from variational posterior.
Parameters
----------
approx: :class:`Approximation`
Approximation to sample from
draws: `int`
Number of random samples.
include_transformed: `bool`
If True, trans... | def sample_approx(approx, draws=100, include_transformed=True):
| """Draw samples from variational posterior.
Parameters
----------
approx: :class:`Approximation`
Approximation to sample from
draws: `int`
Number of random samples.
include_transformed: `bool`
If True, transformed variables are also sampled. Default is True.
Returns... | :
return next(iter(self.user_params[0].values())).shape[0]
@classmethod
def get_param_spec_for(cls, flow, **kwargs):
return flows.Formula(flow).get_param_spec_for(**kwargs)
def sample_approx(approx, draws=100, include_transformed=True):
| 64 | 64 | 127 | 16 | 48 | tomicapretto/pymc3 | pymc3/variational/approximations.py | Python | sample_approx | sample_approx | 520 | 537 | 520 | 520 | d4e508767e738309a259708a6f00cdfc8a066a02 | bigcode/the-stack | train |
b5b441c99996ef2f865123a8 | train | class | class PGGwContext(context.NeutronContext):
@property
def plugin(self):
'''
Over-riding function in NeutronContext Class to return 'plumgrid'
as the neutron plugin.
'''
return 'plumgrid'
@property
def network_manager(self):
'''
Over-riding functio... | class PGGwContext(context.NeutronContext):
@property
| def plugin(self):
'''
Over-riding function in NeutronContext Class to return 'plumgrid'
as the neutron plugin.
'''
return 'plumgrid'
@property
def network_manager(self):
'''
Over-riding function in NeutronContext Class to return 'neutron'
as t... | '''
ctxt = {
'opsvm_ip': '127.0.0.1',
'director_ips': [],
}
for rid in relation_ids('plumgrid'):
for unit in related_units(rid):
rdata = relation_get(rid=rid, unit=unit)
ctxt['director_ips'
].append(str(get_host_ip(rdata['private-address'])))... | 129 | 129 | 433 | 14 | 114 | plumgrid/upstream-charm-plumgrid-gateway | hooks/pg_gw_context.py | Python | PGGwContext | PGGwContext | 38 | 97 | 38 | 40 | ba4b4c3e1343cd09f1e1c324507fc0f044fb4174 | bigcode/the-stack | train |
c209d74a37ffaeea931f02e2 | train | function | def _pg_dir_context():
'''
Inspects relation with PLUMgrid director.
'''
ctxt = {
'opsvm_ip': '127.0.0.1',
'director_ips': [],
}
for rid in relation_ids('plumgrid'):
for unit in related_units(rid):
rdata = relation_get(rid=rid, unit=unit)
ctxt['dir... | def _pg_dir_context():
| '''
Inspects relation with PLUMgrid director.
'''
ctxt = {
'opsvm_ip': '127.0.0.1',
'director_ips': [],
}
for rid in relation_ids('plumgrid'):
for unit in related_units(rid):
rdata = relation_get(rid=rid, unit=unit)
ctxt['director_ips'
... | .
from charmhelpers.contrib.openstack import context
from charmhelpers.contrib.openstack.utils import get_host_ip
from charmhelpers.core.hookenv import (
relation_ids,
related_units,
relation_get,
)
from socket import (
gethostname,
getfqdn
)
def _pg_dir_context():
| 64 | 64 | 134 | 6 | 58 | plumgrid/upstream-charm-plumgrid-gateway | hooks/pg_gw_context.py | Python | _pg_dir_context | _pg_dir_context | 19 | 35 | 19 | 19 | 91cf5d8d4e946d629983881f4b24c9b9a4760119 | bigcode/the-stack | train |
72b88e90f152b051dd36d936 | train | function | @contextmanager
def training(module: nn.Module):
"""
A context manager for training the module.
Args:
module: The module to switch to training in the context.
Returns:
A generator for the context of the module.
"""
training = module.training
try:
module.train()
... | @contextmanager
def training(module: nn.Module):
| """
A context manager for training the module.
Args:
module: The module to switch to training in the context.
Returns:
A generator for the context of the module.
"""
training = module.training
try:
module.train()
yield module
finally:
# Switch b... | .
Returns:
A generator for the context of the module.
"""
training = module.training
try:
module.eval()
yield module
finally:
# Switch batch to training if needed
if training:
module.train()
@contextmanager
def training(module: nn.Module):
| 64 | 64 | 91 | 11 | 53 | Chainso/HLRL | hlrl/torch/utils/contexts/training.py | Python | training | training | 26 | 45 | 26 | 27 | ff365ff4c86e61edcaeb696107fb4e06d1e6aa86 | bigcode/the-stack | train |
e53068d94775a4dc83408d15 | train | function | @contextmanager
def evaluate(module: nn.Module):
"""
A context manager for evaluating the module.
Args:
module: The module to switch to evaluating in the context.
Returns:
A generator for the context of the module.
"""
training = module.training
try:
module.eval()
... | @contextmanager
def evaluate(module: nn.Module):
| """
A context manager for evaluating the module.
Args:
module: The module to switch to evaluating in the context.
Returns:
A generator for the context of the module.
"""
training = module.training
try:
module.eval()
yield module
finally:
# Switc... | from contextlib import contextmanager
import torch.nn as nn
@contextmanager
def evaluate(module: nn.Module):
| 24 | 64 | 90 | 11 | 12 | Chainso/HLRL | hlrl/torch/utils/contexts/training.py | Python | evaluate | evaluate | 5 | 24 | 5 | 6 | 0477760eda6d64575a608920cbcd195789bdb59d | bigcode/the-stack | train |
600cdf569f4bbb627e88c58e | train | function | def resolve_refs(spec, store=None, handlers=None):
"""
Resolve JSON references like {"$ref": <some URI>} in a spec.
Optionally takes a store, which is a mapping from reference URLs to a
dereferenced objects. Prepopulating the store can avoid network calls.
"""
spec = deepcopy(spec)
store = s... | def resolve_refs(spec, store=None, handlers=None):
| """
Resolve JSON references like {"$ref": <some URI>} in a spec.
Optionally takes a store, which is a mapping from reference URLs to a
dereferenced objects. Prepopulating the store can avoid network calls.
"""
spec = deepcopy(spec)
store = store or {}
handlers = handlers or default_handl... | .exceptions import RefResolutionError, ValidationError # noqa
from jsonschema.validators import extend
from openapi_spec_validator.handlers import UrlHandler
from .utils import deep_get
default_handlers = {
'http': UrlHandler('http'),
'https': UrlHandler('https'),
'file': UrlHandler('file'),
}
def resol... | 79 | 79 | 266 | 11 | 68 | aminalaee/connexion | connexion/json_schema.py | Python | resolve_refs | resolve_refs | 19 | 51 | 19 | 19 | 5718371f326da61a62c324f5b80ad7e33c8c9c50 | bigcode/the-stack | train |
1ace672697085d20d1125092 | train | function | def validate_writeOnly(validator, wo, instance, schema):
yield ValidationError("Property is write-only")
| def validate_writeOnly(validator, wo, instance, schema):
| yield ValidationError("Property is write-only")
| subschema.get('x-writeOnly') is True:
continue
yield ValidationError("%r is a required property" % prop)
def validate_readOnly(validator, ro, instance, schema):
yield ValidationError("Property is read-only")
def validate_writeOnly(validator, wo, instance, schema):
| 64 | 64 | 23 | 13 | 51 | aminalaee/connexion | connexion/json_schema.py | Python | validate_writeOnly | validate_writeOnly | 95 | 96 | 95 | 95 | 1d0a7b24d260b907d3eec59770a9320f1918bcfa | bigcode/the-stack | train |
67d0fb130e22a19d4bebe067 | train | function | def validate_required(validator, required, instance, schema):
if not validator.is_type(instance, "object"):
return
for prop in required:
if prop not in instance:
properties = schema.get('properties')
if properties is not None:
subschema = properties.get(p... | def validate_required(validator, required, instance, schema):
| if not validator.is_type(instance, "object"):
return
for prop in required:
if prop not in instance:
properties = schema.get('properties')
if properties is not None:
subschema = properties.get(prop)
if subschema is not None:
... | if instance is None and (schema.get('x-nullable') is True or schema.get('nullable')):
return
if instance not in enums:
yield ValidationError(f"{instance!r} is not one of {enums!r}")
def validate_required(validator, required, instance, schema):
| 63 | 64 | 158 | 12 | 51 | aminalaee/connexion | connexion/json_schema.py | Python | validate_required | validate_required | 72 | 88 | 72 | 72 | f1b4b985cc970b69f419e7f8c2347e53263b533b | bigcode/the-stack | train |
8807b551f159c9dfc4ec418d | train | function | def validate_readOnly(validator, ro, instance, schema):
yield ValidationError("Property is read-only")
| def validate_readOnly(validator, ro, instance, schema):
| yield ValidationError("Property is read-only")
| chema.get('writeOnly'):
continue
if 'x-writeOnly' in validator.VALIDATORS and subschema.get('x-writeOnly') is True:
continue
yield ValidationError("%r is a required property" % prop)
def validate_readOnly(validator, ro, instance, schema):
| 64 | 64 | 23 | 13 | 51 | aminalaee/connexion | connexion/json_schema.py | Python | validate_readOnly | validate_readOnly | 91 | 92 | 91 | 91 | 262df1f3b979a50861de7d61f023d0a115cef503 | bigcode/the-stack | train |
6c06b1e4281f68d4154a127f | train | function | def validate_type(validator, types, instance, schema):
if instance is None and (schema.get('x-nullable') is True or schema.get('nullable')):
return
types = _utils.ensure_list(types)
if not any(validator.is_type(instance, type) for type in types):
yield ValidationError(_utils.types_msg(inst... | def validate_type(validator, types, instance, schema):
| if instance is None and (schema.get('x-nullable') is True or schema.get('nullable')):
return
types = _utils.ensure_list(types)
if not any(validator.is_type(instance, type) for type in types):
yield ValidationError(_utils.types_msg(instance, types))
| _resolve(v)
elif isinstance(node, (list, tuple)):
for i, _ in enumerate(node):
node[i] = _do_resolve(node[i])
return node
res = _do_resolve(spec)
return res
def validate_type(validator, types, instance, schema):
| 64 | 64 | 75 | 12 | 51 | aminalaee/connexion | connexion/json_schema.py | Python | validate_type | validate_type | 54 | 61 | 54 | 54 | 78b0a92c95ab85dea1bc33489f18cbdaa3e56a3d | bigcode/the-stack | train |
0e7017eac6c3cdd995e946d0 | train | function | def validate_enum(validator, enums, instance, schema):
if instance is None and (schema.get('x-nullable') is True or schema.get('nullable')):
return
if instance not in enums:
yield ValidationError(f"{instance!r} is not one of {enums!r}")
| def validate_enum(validator, enums, instance, schema):
| if instance is None and (schema.get('x-nullable') is True or schema.get('nullable')):
return
if instance not in enums:
yield ValidationError(f"{instance!r} is not one of {enums!r}")
| -nullable') is True or schema.get('nullable')):
return
types = _utils.ensure_list(types)
if not any(validator.is_type(instance, type) for type in types):
yield ValidationError(_utils.types_msg(instance, types))
def validate_enum(validator, enums, instance, schema):
| 64 | 64 | 64 | 12 | 52 | aminalaee/connexion | connexion/json_schema.py | Python | validate_enum | validate_enum | 64 | 69 | 64 | 64 | 0e2056ebf57ba767c7a9afb1a66584f96d99bd2a | bigcode/the-stack | train |
6ad84402171cb47167f5560a | train | function | @flask_app.route('/')
def hello():
return 'Hello World!'
| @flask_app.route('/')
def hello():
| return 'Hello World!'
| # -*- coding: utf-8 -*-
import asyncio
import os
from flask import Flask
flask_app = Flask(__name__)
@flask_app.route('/')
def hello():
| 36 | 64 | 15 | 9 | 27 | TonyPythoneer/seria-bot-py | web.py | Python | hello | hello | 10 | 12 | 10 | 11 | 6ec898db1a00d866d63d8e8867ca15eba53d414f | bigcode/the-stack | train |
1e22963d507ff7ae92abb026 | train | function | async def main():
port = int(os.environ.get('PORT', 5000))
future_tasks = [
asyncio.ensure_future(flask_app.run(host='0.0.0.0', port=port)),
]
return await asyncio.gather(*future_tasks)
| async def main():
| port = int(os.environ.get('PORT', 5000))
future_tasks = [
asyncio.ensure_future(flask_app.run(host='0.0.0.0', port=port)),
]
return await asyncio.gather(*future_tasks)
| # -*- coding: utf-8 -*-
import asyncio
import os
from flask import Flask
flask_app = Flask(__name__)
@flask_app.route('/')
def hello():
return 'Hello World!'
async def main():
| 46 | 64 | 57 | 4 | 42 | TonyPythoneer/seria-bot-py | web.py | Python | main | main | 15 | 21 | 15 | 15 | bd25ebb60e130d264a0435fff6c43798b99fdab9 | bigcode/the-stack | train |
52512eb3e957efa485b1c2fd | train | function | def reconstruct(last, now):
if now == (1<<K)-1:
return ""
for n in range(K):
if now & (1<<n):
continue
if_used = restore(n, now+(1<<n)) + overlap[last][n]
if restore(last, now) == if_used:
return k_list[n][:len(k_list[n])-overlap[last][n]] + ... | def reconstruct(last, now):
| if now == (1<<K)-1:
return ""
for n in range(K):
if now & (1<<n):
continue
if_used = restore(n, now+(1<<n)) + overlap[last][n]
if restore(last, now) == if_used:
return k_list[n][:len(k_list[n])-overlap[last][n]] + reconstruct(n, now+(1<<n))
... | if (last & (1 << n)) == 0: # ???
candidate = overlap_list[last][n] + restore(n, used+(1<<n))
result = max(result, candidate)
cache[last][used] = result
return result
def reconstruct(last, now):
| 64 | 64 | 104 | 6 | 57 | cutz-j/AlgorithmStudy | algospot/lec9_DP/[cutz]restore.py | Python | reconstruct | reconstruct | 48 | 60 | 48 | 48 | bd73395f8c922e53240393e62ed8d77669f3a28d | bigcode/the-stack | train |
b111e0f6560fc2c6938e9957 | train | function | def pp(k_list):
for i in range(len(k_list)):
removed = False
for j in range(len(k_list)):
if i != j and k_list[i] in k_list[j]:
k_list.pop(i)
removed = True
break
if removed == True:
continue
return k_list
| def pp(k_list):
| for i in range(len(k_list)):
removed = False
for j in range(len(k_list)):
if i != j and k_list[i] in k_list[j]:
k_list.pop(i)
removed = True
break
if removed == True:
continue
return k_list
| import sys
sys.setrecursionlimit(32688)
MAX = 15
cache = [[-1]*((1<<MAX)+1+1) for _ in range(MAX+1)]
def pp(k_list):
| 45 | 64 | 71 | 5 | 40 | cutz-j/AlgorithmStudy | algospot/lec9_DP/[cutz]restore.py | Python | pp | pp | 7 | 18 | 7 | 7 | ba5c1a6149751e94d5ebded688c717d3079de85d | bigcode/the-stack | train |
74de7cac5131fa2622ec4c5a | train | function | def restore(last, used):
# 완전탐색
# basis
if used == (1<<K)-1:
return 0
# memoization
result = cache[last][used]
if result != -1:
return result # dp
result = 0
for n in range(K):
if (last & (1 << n)) == 0: # ???
candidate = overlap_list[las... | def restore(last, used):
# 완전탐색
# basis
| if used == (1<<K)-1:
return 0
# memoization
result = cache[last][used]
if result != -1:
return result # dp
result = 0
for n in range(K):
if (last & (1 << n)) == 0: # ???
candidate = overlap_list[last][n] + restore(n, used+(1<<n))
resu... | (len(k_i), len(k_j))
for l in range(length, 0, -1):
if k_i[len(k_i)-l:] == k_j[:l]:
return l
return 0
def restore(last, used):
# 완전탐색
# basis
| 64 | 64 | 131 | 18 | 45 | cutz-j/AlgorithmStudy | algospot/lec9_DP/[cutz]restore.py | Python | restore | restore | 27 | 46 | 27 | 29 | a62565218743bf32a771fbd8e1245678827ff4d3 | bigcode/the-stack | train |
8db5bb4e374cd2cf28a09211 | train | function | def overlap(k_i, k_j):
length = min(len(k_i), len(k_j))
for l in range(length, 0, -1):
if k_i[len(k_i)-l:] == k_j[:l]:
return l
return 0
| def overlap(k_i, k_j):
| length = min(len(k_i), len(k_j))
for l in range(length, 0, -1):
if k_i[len(k_i)-l:] == k_j[:l]:
return l
return 0
| removed = False
for j in range(len(k_list)):
if i != j and k_list[i] in k_list[j]:
k_list.pop(i)
removed = True
break
if removed == True:
continue
return k_list
def overlap(k_i, k_j):
| 64 | 64 | 58 | 8 | 55 | cutz-j/AlgorithmStudy | algospot/lec9_DP/[cutz]restore.py | Python | overlap | overlap | 20 | 25 | 20 | 20 | b42df0dffb034ea84896533b9eeae54c4348a19d | bigcode/the-stack | train |
e6c87c515f670f6150296748 | train | class | class CycleGANModel(BaseModel):
"""
This class implements the CycleGAN model, for learning image-to-image translation without paired data.
The model training requires '--dataset_mode unaligned' dataset.
By default, it uses a '--netG resnet_9blocks' ResNet generator,
a '--netD basic' discriminator (... | class CycleGANModel(BaseModel):
| """
This class implements the CycleGAN model, for learning image-to-image translation without paired data.
The model training requires '--dataset_mode unaligned' dataset.
By default, it uses a '--netG resnet_9blocks' ResNet generator,
a '--netD basic' discriminator (PatchGAN introduced by pix2pix),... | import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
class CycleGANModel(BaseModel):
| 34 | 256 | 2,563 | 7 | 26 | YuzuHotaru/CycleGAN | models/cycle_gan_model.py | Python | CycleGANModel | CycleGANModel | 8 | 194 | 8 | 8 | 7da906d4b327e6bf7222e8205855d976a7e0f2ac | bigcode/the-stack | train |
d026a0f0c87f1e846ef1d695 | train | class | class SpotifyDBus():
def __init__(self, ui=None):
self.connect_to_spotify()
self.set_properties()
self.ui = ui
if self.ui:
self.win = LyricifyUI()
self.win.connect('delete-event', self.on_exit)
self.lyricify()
GLib.MainLoop().run() # W... | class SpotifyDBus():
| def __init__(self, ui=None):
self.connect_to_spotify()
self.set_properties()
self.ui = ui
if self.ui:
self.win = LyricifyUI()
self.win.connect('delete-event', self.on_exit)
self.lyricify()
GLib.MainLoop().run() # Wait for events ie. a s... | import sys
import argparse
import dbus
from subprocess import call
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from lyricify.lyrics import create_song_url, get_album_image, get_lyrics
from lyricify.gui import LyricifyUI
class SpotifyDBus():
| 68 | 153 | 512 | 5 | 62 | sharadsw/lyricify | lyricify/controller.py | Python | SpotifyDBus | SpotifyDBus | 12 | 84 | 12 | 13 | b4cfc46b570caecfca5d653047376ea7a1488edb | bigcode/the-stack | train |
b3049c9e61121dcbc9dee48b | train | function | def main():
parser = argparse.ArgumentParser(description="Get lyrics for Spotify songs")
parser.add_argument("-ui", action="store_true",
help="Open a GTK ui for lyrics")
args = parser.parse_args()
try:
SpotifyDBus(ui=args.ui)
except KeyboardInterrupt:
pass
| def main():
| parser = argparse.ArgumentParser(description="Get lyrics for Spotify songs")
parser.add_argument("-ui", action="store_true",
help="Open a GTK ui for lyrics")
args = parser.parse_args()
try:
SpotifyDBus(ui=args.ui)
except KeyboardInterrupt:
pass
| lyrics/album art for the song, sorry!")
sys.exit()
if self.ui:
self.win.update_view(self.artist, self.song, song_lyrics)
else:
call("clear")
print("{} - {}\n\n{}".format(self.artist, self.song, song_lyrics))
def main():
| 64 | 64 | 65 | 3 | 61 | sharadsw/lyricify | lyricify/controller.py | Python | main | main | 87 | 96 | 87 | 87 | 28636f137b0065e13f344c2116a75f3d0bbc5c7f | bigcode/the-stack | train |
603a324e2f1ef50e8a5f3d48 | train | class | @dataclass(frozen=True)
class Announcement:
origin_info: bytes32
message: bytes
def name(self) -> bytes32:
return std_hash(bytes(self.origin_info + self.message))
| @dataclass(frozen=True)
class Announcement:
| origin_info: bytes32
message: bytes
def name(self) -> bytes32:
return std_hash(bytes(self.origin_info + self.message))
| from dataclasses import dataclass
from avocado.types.blockchain_format.sized_bytes import bytes32
from avocado.util.hash import std_hash
@dataclass(frozen=True)
class Announcement:
| 37 | 64 | 42 | 9 | 27 | avocado-fork-workaround/avocado-blockchain | avocado/types/announcement.py | Python | Announcement | Announcement | 7 | 13 | 7 | 8 | ce2539c896e6a373032608bf4977922458c24646 | bigcode/the-stack | train |
c89640a84164b8a596e7a36c | train | class | class TestUnfoldOp(AutoScanTest):
def __init__(self, *args, **kwargs):
AutoScanTest.__init__(self, *args, **kwargs)
host_places = [
Place(TargetType.Host, PrecisionType.FP32, DataLayoutType.NCHW)
]
self.enable_testing_on_place(places=host_places, thread=[1, 4])
def ... | class TestUnfoldOp(AutoScanTest):
| def __init__(self, *args, **kwargs):
AutoScanTest.__init__(self, *args, **kwargs)
host_places = [
Place(TargetType.Host, PrecisionType.FP32, DataLayoutType.NCHW)
]
self.enable_testing_on_place(places=host_places, thread=[1, 4])
def is_program_valid(self,
... | 2 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | 229 | 229 | 764 | 10 | 218 | 714627034/Paddle-Lite | lite/tests/unittest_py/op/test_unfold_op.py | Python | TestUnfoldOp | TestUnfoldOp | 30 | 113 | 30 | 30 | d2faa1e1288dec4c3d553cc7e1d6788c5cc2379d | bigcode/the-stack | train |
331ca258e81080e6f388cc4c | train | function | def pil_loader(img_str):
buff = io.BytesIO(img_str)
with Image.open(buff) as img:
img = img.convert('RGB')
return np.array(img)
| def pil_loader(img_str):
| buff = io.BytesIO(img_str)
with Image.open(buff) as img:
img = img.convert('RGB')
return np.array(img)
| division
import os
import pdb
import io
import torch
import pandas as pd
from skimage import transform
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
def pil_loader(img_str):
| 64 | 64 | 38 | 6 | 57 | NIRVANALAN/PyTorch_Classification | utils/cardiac_datasets.py | Python | pil_loader | pil_loader | 16 | 20 | 16 | 16 | 2eeb936df12bca06e1e38038eeac341144cd4158 | bigcode/the-stack | train |
68a22141a9a911317e668f43 | train | class | class CardiacDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, datalist, root_dir='', transform=None):
"""
Args:
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sampl... | class CardiacDataset(Dataset):
| """Face Landmarks dataset."""
def __init__(self, datalist, root_dir='', transform=None):
"""
Args:
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.roo... | Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
def pil_loader(img_str):
buff = io.BytesIO(img_str)
with Image.open(buff) as img:
img = img.convert('RGB')
return np.array(img)
class CardiacDataset(Dataset):
| 64 | 64 | 193 | 7 | 57 | NIRVANALAN/PyTorch_Classification | utils/cardiac_datasets.py | Python | CardiacDataset | CardiacDataset | 22 | 51 | 22 | 22 | a2bfe202fc243e574fd93abf00a00c24e2434ba8 | bigcode/the-stack | train |
34090da3e968a1ff7fb55ea7 | train | function | @click.command()
@click.option('--zip', 'zip', flag_value=True, default=False)
@click.option('--text', 'text', flag_value=True, default=False,
help='Copy a TXT or other tab-separated file')
@click.option('--csv', 'csv', flag_value=True, default=False,
help='Copy a CSV or other delimiter separated file')
@click.... | @click.command()
@click.option('--zip', 'zip', flag_value=True, default=False)
@click.option('--text', 'text', flag_value=True, default=False,
help='Copy a TXT or other tab-separated file')
@click.option('--csv', 'csv', flag_value=True, default=False,
help='Copy a CSV or other delimiter separated file')
@click.... | ''' Main interface to Postgres uploading functions '''
file = filename[0]
try:
zipped_file = filename[1]
except IndexError:
zipped_file = None
if zip:
if zipped_file:
# Grab the specific file in the archive
try:
zipped_fi... | @click.command()
@click.option('--zip', 'zip', flag_value=True, default=False)
@click.option('--text', 'text', flag_value=True, default=False,
help='Copy a TXT or other tab-separated file')
@click.option('--csv', 'csv', flag_value=True, default=False,
help='Copy a CSV or other delimiter separated file')
@click.... | 300 | 158 | 528 | 300 | 0 | vincentlaucsb/sqlify | pgreaper/cli/copy.py | Python | copy | copy | 7 | 61 | 7 | 24 | cb1654e68fe6f9fc3d640e1fdbc7edbfe170d3a5 | bigcode/the-stack | train |
9519add9ce2fe60c883bc679 | train | function | def copy_delim(file, zip, zipped_file, delim, header, skiplines,
dbname, user, host, password):
# Use is not None because zipped_file = 0 is a legit non-null option
if zip and (zipped_file is None):
raise ValueError('Please specify which file in the ZIP archive to upload.')
# Load the file
... | def copy_delim(file, zip, zipped_file, delim, header, skiplines,
dbname, user, host, password):
# Use is not None because zipped_file = 0 is a legit non-null option
| if zip and (zipped_file is None):
raise ValueError('Please specify which file in the ZIP archive to upload.')
# Load the file
pgreaper.copy_csv(file, delimiter=delim, header=header, skiplines=skiplines,
dbname=dbname, user=user, host=host, password=password)
# Print report
... | , skiplines,
dbname, user, host, password)
def copy_delim(file, zip, zipped_file, delim, header, skiplines,
dbname, user, host, password):
# Use is not None because zipped_file = 0 is a legit non-null option
| 63 | 64 | 135 | 48 | 15 | vincentlaucsb/sqlify | pgreaper/cli/copy.py | Python | copy_delim | copy_delim | 63 | 74 | 63 | 65 | c32f51a2d81218ae5424433689dab37b487ea602 | bigcode/the-stack | train |
540748dd3488ac0f287a3d8b | train | class | class CoreConfig(AppConfig):
name = 'app.core'
label = 'core'
verbose_name = "Aplicación Principal" | class CoreConfig(AppConfig):
| name = 'app.core'
label = 'core'
verbose_name = "Aplicación Principal" | from django.apps import AppConfig
class CoreConfig(AppConfig):
| 13 | 64 | 28 | 6 | 6 | Jereromanoo/agencia | app/core/apps.py | Python | CoreConfig | CoreConfig | 3 | 6 | 3 | 3 | 6d1a1d16cc3a46cc557acad51f8fc544955cfa6e | bigcode/the-stack | train |
ff1c530fb040154832ead58a | train | function | def get_config(path: str, logger: Logger=None) -> Optional[ConfigTree]:
"""
Function to read Configuration from a HOCON file
Args:
path (str): Path of Hocon File
Returns:
ConfigTree containing the configuration
"""
try:
if logger:
logger.info(f"Reading Confi... | def get_config(path: str, logger: Logger=None) -> Optional[ConfigTree]:
| """
Function to read Configuration from a HOCON file
Args:
path (str): Path of Hocon File
Returns:
ConfigTree containing the configuration
"""
try:
if logger:
logger.info(f"Reading Configuration from {path}")
conf = ConfigFactory.parse_file(path)
... | from pyhocon import ConfigFactory, ConfigTree
import argparse
from pysparkutils.dependencies.logger import get_logger
from logging import Logger
from typing import Optional
def get_config(path: str, logger: Logger=None) -> Optional[ConfigTree]:
| 52 | 64 | 122 | 18 | 33 | NarendraBabuOggu/PySparkUtils | pysparkutils/dependencies/hocon_config_parser.py | Python | get_config | get_config | 7 | 26 | 7 | 7 | 18e1d1de1c32e38a06e26cf9f5d81ce1aa33e619 | bigcode/the-stack | train |
dc2342f461a05f2d02a01195 | train | class | class PosEmbedRel(nn.Module):
""" Relative Position Embedding
As per: https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2
Originally from: `Attention Augmented Convolutional Networks` - https://arxiv.org/abs/1904.09925
"""
def __init__(self, block_size, win_size, dim_head, scal... | class PosEmbedRel(nn.Module):
| """ Relative Position Embedding
As per: https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2
Originally from: `Attention Augmented Convolutional Networks` - https://arxiv.org/abs/1904.09925
"""
def __init__(self, block_size, win_size, dim_head, scale):
"""
Args:
... | = win_size - W
flat_x = x.reshape([-1, H, W * rel_size])[:, :, W - 1: -1]
out = flat_x.reshape([-1, H, 1, W, 2 * (win_size - 1)])[:, :, :, :, full_rank_gap : win_size + full_rank_gap]
# tile and permute
return out.expand(-1, -1, win_size, -1, -1).permute(permute_mask)
class PosEmbedRel(nn.Mod... | 114 | 114 | 381 | 7 | 107 | leondgarse/pytorch-image-models | timm/models/layers/halo_attn.py | Python | PosEmbedRel | PosEmbedRel | 60 | 93 | 60 | 60 | 1799d4df542b15ea92fc73178b2c06330cede98a | bigcode/the-stack | train |
3061eba93cb0f987de20fbcc | train | function | def rel_logits_1d(q, rel_k, permute_mask: List[int]):
""" Compute relative logits along one dimension
As per: https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2
Originally from: `Attention Augmented Convolutional Networks` - https://arxiv.org/abs/1904.09925
Args:
q: (batc... | def rel_logits_1d(q, rel_k, permute_mask: List[int]):
| """ Compute relative logits along one dimension
As per: https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2
Originally from: `Attention Augmented Convolutional Networks` - https://arxiv.org/abs/1904.09925
Args:
q: (batch * heads, height, width, dim)
rel_k: (2 * win... | is a WIP, there is no official ref impl and some details in paper weren't clear to me.
The attention mechanism works but it's slow as implemented.
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import List
import torch
from torch import nn
import torch.nn.functional as F
from .helpers import make... | 108 | 108 | 361 | 18 | 89 | leondgarse/pytorch-image-models | timm/models/layers/halo_attn.py | Python | rel_logits_1d | rel_logits_1d | 30 | 57 | 30 | 30 | 47424bdde6718dcf5ada3313c120ba2fceba909c | bigcode/the-stack | train |
9d8ec52262624a32bf7d4815 | train | class | class HaloAttn(nn.Module):
""" Halo Attention
Paper: `Scaling Local Self-Attention for Parameter Efficient Visual Backbones`
- https://arxiv.org/abs/2103.12731
The internal dimensions of the attention module are controlled by the interaction of several arguments.
* the output dimension of th... | class HaloAttn(nn.Module):
| """ Halo Attention
Paper: `Scaling Local Self-Attention for Parameter Efficient Visual Backbones`
- https://arxiv.org/abs/2103.12731
The internal dimensions of the attention module are controlled by the interaction of several arguments.
* the output dimension of the module is specified by di... | scale (float): scale factor (for init)
"""
super().__init__()
self.block_size = block_size
self.dim_head = dim_head
self.height_rel = nn.Parameter(torch.randn(win_size * 2 - 1, dim_head) * scale)
self.width_rel = nn.Parameter(torch.randn(win_size * 2 - 1, dim_... | 256 | 256 | 1,673 | 7 | 248 | leondgarse/pytorch-image-models | timm/models/layers/halo_attn.py | Python | HaloAttn | HaloAttn | 96 | 209 | 96 | 96 | 6a86e891a801c5518c8dacc66c0b32491e217976 | bigcode/the-stack | train |
8ba2714d007c9eef8800cf7b | train | function | def test_get_master_fingerprint(client: Client, speculos_globals: SpeculosGlobals):
assert client.get_master_fingerprint() == speculos_globals.master_key_fingerprint.to_bytes(4, byteorder="big")
| def test_get_master_fingerprint(client: Client, speculos_globals: SpeculosGlobals):
| assert client.get_master_fingerprint() == speculos_globals.master_key_fingerprint.to_bytes(4, byteorder="big")
| from ledger_bitcoin import Client
from .conftest import SpeculosGlobals
def test_get_master_fingerprint(client: Client, speculos_globals: SpeculosGlobals):
| 35 | 64 | 44 | 18 | 16 | backpacker69/app-bitcoin-new | bitcoin_client/tests/test_get_master_fingerprint_legacyapp.py | Python | test_get_master_fingerprint | test_get_master_fingerprint | 5 | 6 | 5 | 5 | a29baef5594c8ae74286ec8a0d49d563215a78c1 | bigcode/the-stack | train |
b6cc9a560f946b6c2fb060fd | train | function | def initialize_bert_based_model(config, d_out, is_featurizer=False):
from models.bert.bert import BertClassifier, BertFeaturizer
from models.bert.distilbert import DistilBertClassifier, DistilBertFeaturizer
if config.get('model') == 'bert-base-uncased':
if is_featurizer:
model = BertFea... | def initialize_bert_based_model(config, d_out, is_featurizer=False):
| from models.bert.bert import BertClassifier, BertFeaturizer
from models.bert.distilbert import DistilBertClassifier, DistilBertFeaturizer
if config.get('model') == 'bert-base-uncased':
if is_featurizer:
model = BertFeaturizer.from_pretrained(config.get('model'), **config.get('model_kwar... | _y'):
# Sometimes model is a tuple of (featurizer, classifier)
if isinstance(model, tuple):
for submodel in model:
submodel.needs_y = False
else:
model.needs_y = False
return model
def initialize_bert_based_model(config, d_out, is_featurizer=False):
| 72 | 72 | 240 | 17 | 54 | itsjohnward/wilds | wilds/examples/models/initializer.py | Python | initialize_bert_based_model | initialize_bert_based_model | 114 | 136 | 114 | 114 | 9493e7b9a62e86ca1a557477273f833cfd2c2781 | bigcode/the-stack | train |
e45ba4bc72fc211c6b77eda3 | train | function | def initialize_fasterrcnn_model(config, d_out):
from models.detection.fasterrcnn import fasterrcnn_resnet50_fpn
# load a model pre-trained pre-trained on COCO
model = fasterrcnn_resnet50_fpn(
pretrained=config.get('model_kwargs')["pretrained_model"],
pretrained_backbone=config.get('model_k... | def initialize_fasterrcnn_model(config, d_out):
| from models.detection.fasterrcnn import fasterrcnn_resnet50_fpn
# load a model pre-trained pre-trained on COCO
model = fasterrcnn_resnet50_fpn(
pretrained=config.get('model_kwargs')["pretrained_model"],
pretrained_backbone=config.get('model_kwargs')["pretrained_backbone"],
num_class... | _features
else: # want to initialize a classifier for a particular num_classes
last_layer = nn.Linear(d_features, d_out)
model.d_out = d_out
setattr(model, last_layer_name, last_layer)
return model
def initialize_fasterrcnn_model(config, d_out):
| 64 | 64 | 123 | 12 | 51 | itsjohnward/wilds | wilds/examples/models/initializer.py | Python | initialize_fasterrcnn_model | initialize_fasterrcnn_model | 168 | 181 | 168 | 169 | 6316e5ee1b5cfce2e3ad922f079ff532b655da7e | bigcode/the-stack | train |
fb085b04d2bbcec91e6d4f9c | train | function | def initialize_torchvision_model(name, d_out, **kwargs):
import torchvision
# get constructor and last layer names
if name == 'wideresnet50':
constructor_name = 'wide_resnet50_2'
last_layer_name = 'fc'
elif name == 'densenet121':
constructor_name = name
last_layer_name =... | def initialize_torchvision_model(name, d_out, **kwargs):
| import torchvision
# get constructor and last layer names
if name == 'wideresnet50':
constructor_name = 'wide_resnet50_2'
last_layer_name = 'fc'
elif name == 'densenet121':
constructor_name = name
last_layer_name = 'classifier'
elif name in ('resnet50', 'resnet34', '... | '), **config.get('model_kwargs'))
else:
model = DistilBertClassifier.from_pretrained(
config.get('model'),
num_labels=d_out,
**config.get('model_kwargs'))
else:
raise ValueError(f'Model: {config.get("model")} not recognized.')
return mo... | 81 | 81 | 270 | 14 | 66 | itsjohnward/wilds | wilds/examples/models/initializer.py | Python | initialize_torchvision_model | initialize_torchvision_model | 138 | 165 | 138 | 138 | 9a368df21c8626fb76386f7538729dc60bf2f5bc | bigcode/the-stack | train |
5e58b7a620fcb8a59e4c8a7c | train | function | def initialize_model(config, d_out, is_featurizer=False):
"""
Initializes models according to the config
Args:
- config (dictionary): config dictionary
- d_out (int): the dimensionality of the model output
- is_featurizer (bool): whether to return a model or a (featur... | def initialize_model(config, d_out, is_featurizer=False):
| """
Initializes models according to the config
Args:
- config (dictionary): config dictionary
- d_out (int): the dimensionality of the model output
- is_featurizer (bool): whether to return a model or a (featurizer, classifier) pair that constitutes a model.
O... | import torch
import torch.nn as nn
from .layers import Identity
def initialize_model(config, d_out, is_featurizer=False):
| 29 | 256 | 1,097 | 14 | 14 | itsjohnward/wilds | wilds/examples/models/initializer.py | Python | initialize_model | initialize_model | 6 | 111 | 6 | 6 | d8ae7a2396e24af97479266f33ba8621fdc3f59a | bigcode/the-stack | train |
e9d54bff3e02591c62a66592 | train | class | class TestServiceParser(unittest.TestCase):
def setUp(self):
self.xmldoc = file(XRD_FILE).read()
self.yadis_url = 'http://unittest.url/'
def _getServices(self, flt=None):
return list(services.applyFilter(self.yadis_url, self.xmldoc, flt))
def testParse(self):
"""Make sure t... | class TestServiceParser(unittest.TestCase):
| def setUp(self):
self.xmldoc = file(XRD_FILE).read()
self.yadis_url = 'http://unittest.url/'
def _getServices(self, flt=None):
return list(services.applyFilter(self.yadis_url, self.xmldoc, flt))
def testParse(self):
"""Make sure that parsing succeeds at all"""
servi... | file__, os.path.join("data", "test1-xrd.xml"))
NOXRDS_FILE = sibpath(__file__, os.path.join("data", "not-xrds.xml"))
NOXRD_FILE = sibpath(__file__, os.path.join("data", "no-xrd.xml"))
# None of the namespaces or service URIs below are official (or even
# sanctioned by the owners of that piece of URL-space)
LID_2_0 = ... | 235 | 235 | 786 | 8 | 227 | google-code-export/django-hotclub | libs/external_libs/python-yadis-1.1.0/yadis/test/test_etxrd.py | Python | TestServiceParser | TestServiceParser | 35 | 127 | 35 | 35 | d9abca55bd718c327a015472834fc6d5820fa00c | bigcode/the-stack | train |
e547ebb976b153960909bab1 | train | function | def simpleOpenIDTransformer(endpoint):
"""Function to extract information from an OpenID service element"""
if 'http://openid.net/signon/1.0' not in endpoint.type_uris:
return None
delegates = list(endpoint.service_element.findall(
'{http://openid.net/xmlns/1.0}Delegate'))
assert len(de... | def simpleOpenIDTransformer(endpoint):
| """Function to extract information from an OpenID service element"""
if 'http://openid.net/signon/1.0' not in endpoint.type_uris:
return None
delegates = list(endpoint.service_element.findall(
'{http://openid.net/xmlns/1.0}Delegate'))
assert len(delegates) == 1
delegate = delegates[... | or even
# sanctioned by the owners of that piece of URL-space)
LID_2_0 = "http://lid.netmesh.org/sso/2.0b5"
TYPEKEY_1_0 = "http://typekey.com/services/1.0"
def simpleOpenIDTransformer(endpoint):
| 64 | 64 | 97 | 7 | 57 | google-code-export/django-hotclub | libs/external_libs/python-yadis-1.1.0/yadis/test/test_etxrd.py | Python | simpleOpenIDTransformer | simpleOpenIDTransformer | 24 | 33 | 24 | 24 | 902096717e04b8a05364cfbd1f85366a29d8c285 | bigcode/the-stack | train |
082c99d5700ec93272322fa0 | train | class | class TestCanonicalID(unittest.TestCase):
canonicalIDtests = [
("@ootao*test1", "delegated-20060809.xrds",
"@!5BAD.2AA.3C72.AF46!0000.0000.3B9A.CA01"),
("@ootao*test1", "delegated-20060809-r1.xrds",
"@!5BAD.2AA.3C72.AF46!0000.0000.3B9A.CA01"),
("@ootao*test1", "delegated-2... | class TestCanonicalID(unittest.TestCase):
| canonicalIDtests = [
("@ootao*test1", "delegated-20060809.xrds",
"@!5BAD.2AA.3C72.AF46!0000.0000.3B9A.CA01"),
("@ootao*test1", "delegated-20060809-r1.xrds",
"@!5BAD.2AA.3C72.AF46!0000.0000.3B9A.CA01"),
("@ootao*test1", "delegated-20060809-r2.xrds",
"@!5BAD.2AA.3C72... | self.xmldoc = file(NOXRDS_FILE).read()
self.failUnlessRaises(
etxrd.XRDSError,
services.applyFilter, self.yadis_url, self.xmldoc, None)
def testEmpty(self):
"""Make sure that we get an exception when an XRDS element is
not present"""
self.xmldoc = ''
... | 196 | 196 | 656 | 8 | 188 | google-code-export/django-hotclub | libs/external_libs/python-yadis-1.1.0/yadis/test/test_etxrd.py | Python | TestCanonicalID | TestCanonicalID | 130 | 173 | 130 | 131 | 85eeb8fa3e599e1be69b8a6eef125cc511ac023a | bigcode/the-stack | train |
2139fbd7ce2339f7f4d6d18d | train | function | def sibpath(one, other, make_absolute=True):
if os.path.isabs(other):
return other
p = os.path.join(os.path.dirname(one), other)
if make_absolute:
p = os.path.abspath(p)
return p
| def sibpath(one, other, make_absolute=True):
| if os.path.isabs(other):
return other
p = os.path.join(os.path.dirname(one), other)
if make_absolute:
p = os.path.abspath(p)
return p
| import unittest
from yadis import services, etxrd, xri
import os.path
def sibpath(one, other, make_absolute=True):
| 31 | 64 | 53 | 11 | 19 | google-code-export/django-hotclub | libs/external_libs/python-yadis-1.1.0/yadis/test/test_etxrd.py | Python | sibpath | sibpath | 5 | 11 | 5 | 5 | dd51c01e5d818c67f9748c053337a8331ed07397 | bigcode/the-stack | train |
545a5571a768428578543893 | train | class | class VerveResponseSentimentAnalytics(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, status_code=None, message=None, list=None, data=None, records=None):
"""
VerveResponseSentimentAnalytics... | class VerveResponseSentimentAnalytics(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, status_code=None, message=None, list=None, data=None, records=None):
"""
VerveResponseSentimentAnalytics - a model defined in Swagger
:param d... | # coding: utf-8
"""
iEngage 2.0 API
This API enables Intelligent Engagement for your Business. iEngage is a platform that combines process, augmented intelligence and rewards to help you intelligently engage customers.
OpenAPI spec version: 2.0
Generated by: https://github.com/swagger-api/swagge... | 216 | 256 | 1,114 | 9 | 206 | iEngage/python-sdk | iengage_client/models/verve_response_sentiment_analytics.py | Python | VerveResponseSentimentAnalytics | VerveResponseSentimentAnalytics | 30 | 229 | 30 | 30 | 3fb0acb17f33f25f4c3b1abe75ef29122453bcdc | bigcode/the-stack | train |
c9b110bd6f190113ce4cf583 | train | function | def get_path(file_path=''):
from flask import request, make_response, jsonify, send_file, Response
print(file_path)
as_records = request.args.get('records')
as_json = request.args.get('json')
as_attachment = request.args.get('download')
is_recursive = request.args.get('recursive')
show_hidd... | def get_path(file_path=''):
| from flask import request, make_response, jsonify, send_file, Response
print(file_path)
as_records = request.args.get('records')
as_json = request.args.get('json')
as_attachment = request.args.get('download')
is_recursive = request.args.get('recursive')
show_hidden = request.args.get('hidde... | import json
import mimetypes
import os
import re
import stat
from datetime import datetime
from . import config
def get_type(mode):
if stat.S_ISDIR(mode) or stat.S_ISLNK(mode):
type = 'dir'
else:
type = 'file'
return type
def get_path(file_path=''):
| 74 | 92 | 309 | 7 | 66 | mcx/ml_logger | scratch/old/vis_server_gevent_deprecated/file_handlers.py | Python | get_path | get_path | 17 | 51 | 17 | 17 | 7fdb218c4020aa08f7aa3d8fe3d448c0d73989eb | bigcode/the-stack | train |
cd01d1473662d5b6a19a4d8c | train | function | def post(p=''):
from flask import request, make_response, jsonify, send_file, Response
path = os.path.join(config.Args.logdir, p)
info = {}
if os.path.isdir(path):
files = request.files.getlist('files[]')
for file in files:
try:
filename = secure_filename(file... | def post(p=''):
| from flask import request, make_response, jsonify, send_file, Response
path = os.path.join(config.Args.logdir, p)
info = {}
if os.path.isdir(path):
files = request.files.getlist('files[]')
for file in files:
try:
filename = secure_filename(file.filename)
... | = make_response(df.to_json(orient="records"), 200)
else:
res = send_file(path)
if as_attachment:
res.headers.add('Content-Disposition', 'attachment')
else:
res = make_response('Not found', 404)
return res
def post(p=''):
| 64 | 64 | 182 | 5 | 58 | mcx/ml_logger | scratch/old/vis_server_gevent_deprecated/file_handlers.py | Python | post | post | 54 | 75 | 54 | 54 | b6e7645174f7314a5f49222153348ac9d73dc9f4 | bigcode/the-stack | train |
e33809289696e175da525f36 | train | function | def list_directory(root, current_directory, recursive=False, show_hidden=False):
total = {'size': 0, 'dir': 0, 'file': 0}
real_path = os.path.join(root, current_directory)
for filename in os.listdir(real_path):
if not show_hidden and filename.startswith('.'):
continue
filepath = ... | def list_directory(root, current_directory, recursive=False, show_hidden=False):
| total = {'size': 0, 'dir': 0, 'file': 0}
real_path = os.path.join(root, current_directory)
for filename in os.listdir(real_path):
if not show_hidden and filename.startswith('.'):
continue
filepath = os.path.join(root, current_directory, filename)
stat_res = os.stat(filepa... | info['status'] = 'error'
info['msg'] = 'Invalid Operation'
res = make_response(json.JSONEncoder().encode(info), 200)
res.headers.add('Content-type', 'application/json')
return res
def list_directory(root, current_directory, recursive=False, show_hidden=False):
| 64 | 64 | 200 | 15 | 48 | mcx/ml_logger | scratch/old/vis_server_gevent_deprecated/file_handlers.py | Python | list_directory | list_directory | 78 | 99 | 78 | 78 | c487f2da8c69cb212983b4dfe8b7107bebf79d10 | bigcode/the-stack | train |
58dc6a782ac927c3b1e8b3a7 | train | function | def get_type(mode):
if stat.S_ISDIR(mode) or stat.S_ISLNK(mode):
type = 'dir'
else:
type = 'file'
return type
| def get_type(mode):
| if stat.S_ISDIR(mode) or stat.S_ISLNK(mode):
type = 'dir'
else:
type = 'file'
return type
| import json
import mimetypes
import os
import re
import stat
from datetime import datetime
from . import config
def get_type(mode):
| 32 | 64 | 40 | 5 | 26 | mcx/ml_logger | scratch/old/vis_server_gevent_deprecated/file_handlers.py | Python | get_type | get_type | 9 | 14 | 9 | 9 | 233285755be03b318feef9f076cb39301ce77ec5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.