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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a0fa39d2816d987440670816 | train | function | def save_data_csv(rows: List[CsvFaceModel], file_path: str):
"""
Save to a CSV file.
It will tansfor CsvFaceModel.encoding(np.ndarray) to base64
"""
def encode_row(row: CsvFaceModel):
dic = row.dict()
dic['base64_encoding'] = \
base64.b64encode(dic['encoding'].tobytes())... | def save_data_csv(rows: List[CsvFaceModel], file_path: str):
| """
Save to a CSV file.
It will tansfor CsvFaceModel.encoding(np.ndarray) to base64
"""
def encode_row(row: CsvFaceModel):
dic = row.dict()
dic['base64_encoding'] = \
base64.b64encode(dic['encoding'].tobytes()).decode("utf-8")
dic.pop('encoding')
return ... | antic import BaseModel
class CsvFaceModel(BaseModel):
name: str
src_url: str = ''
comment: str = ''
encoding: np.ndarray
class Config:
arbitrary_types_allowed = True
def save_data_csv(rows: List[CsvFaceModel], file_path: str):
| 64 | 64 | 163 | 17 | 46 | KuroiCc/myjlab2021-2nd-final-work | star_face_similarity/utils.py | Python | save_data_csv | save_data_csv | 23 | 42 | 23 | 23 | 01ab2858e7b72822d26e0068d60bb9807158e9b4 | bigcode/the-stack | train |
e293526c2a0602ab9de3c4bc | train | function | def crawling_image(name: str, image_url: str, path: str = 'images'):
res = requests.get(image_url)
if not os.path.exists(path):
os.makedirs(os.path.abspath(path))
extension = image_url.rsplit('.')[-1]
with open(f'{path}/{name}.{extension}', 'wb') as f:
f.write(res.content)
return os... | def crawling_image(name: str, image_url: str, path: str = 'images'):
| res = requests.get(image_url)
if not os.path.exists(path):
os.makedirs(os.path.abspath(path))
extension = image_url.rsplit('.')[-1]
with open(f'{path}/{name}.{extension}', 'wb') as f:
f.write(res.content)
return os.path.abspath(f'{path}/{name}.{extension}')
| return CsvFaceModel(**row)
with open(file_path, newline='') as f:
csv_reader = csv.DictReader(f)
data = list(map(decode_row, csv_reader))
return data
def crawling_image(name: str, image_url: str, path: str = 'images'):
| 64 | 64 | 90 | 19 | 44 | KuroiCc/myjlab2021-2nd-final-work | star_face_similarity/utils.py | Python | crawling_image | crawling_image | 63 | 71 | 63 | 63 | 8d60990d63e21f06078f8c85059472a4db073211 | bigcode/the-stack | train |
2f430b3d4d1a592f1e30d80a | train | function | def load_data_csv(file_path):
"""
Load CSV save by func `save_data_csv`
"""
def decode_row(row: dict):
row['encoding'] = \
np.frombuffer(base64.b64decode(row['base64_encoding']), dtype="float64")
row.pop('base64_encoding')
return CsvFaceModel(**row)
with open(fi... | def load_data_csv(file_path):
| """
Load CSV save by func `save_data_csv`
"""
def decode_row(row: dict):
row['encoding'] = \
np.frombuffer(base64.b64decode(row['base64_encoding']), dtype="float64")
row.pop('base64_encoding')
return CsvFaceModel(**row)
with open(file_path, newline='') as f:
... | ', newline='') as f:
csv_writer = csv.DictWriter(
f, fieldnames=['name', 'src_url', 'comment', 'base64_encoding']
)
csv_writer.writeheader()
csv_writer.writerows(list(map(encode_row, rows)))
def load_data_csv(file_path):
| 63 | 64 | 110 | 7 | 56 | KuroiCc/myjlab2021-2nd-final-work | star_face_similarity/utils.py | Python | load_data_csv | load_data_csv | 45 | 60 | 45 | 45 | 36ee0a999f9da0774131853d93af83e9a1338b54 | bigcode/the-stack | train |
b3f999d84e20caa1ac586c24 | train | function | def rotateImage(img: Image.Image, orientation):
"""
The source of this code is as follows. Some changes have been made compared to the source.
source:https://max999blog.com/python-rotate-image-by-exif-orientation/
画像ファイルをOrientationの値に応じて回転させる
"""
img_rotate = img
# orientationの値に応じて画像を回転させ... | def rotateImage(img: Image.Image, orientation):
| """
The source of this code is as follows. Some changes have been made compared to the source.
source:https://max999blog.com/python-rotate-image-by-exif-orientation/
画像ファイルをOrientationの値に応じて回転させる
"""
img_rotate = img
# orientationの値に応じて画像を回転させる
if orientation == 1:
pass
elif... | )
def find_all_file(path: str):
file_list = []
files = os.listdir(path)
for file in files:
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
inner_file_list = find_all_file(file_path)
file_list = file_list + inner_file_list
elif os.path.isfi... | 98 | 98 | 329 | 10 | 87 | KuroiCc/myjlab2021-2nd-final-work | star_face_similarity/utils.py | Python | rotateImage | rotateImage | 89 | 124 | 89 | 89 | 6379beb76289b8ecd6583ad35cf7dabe7b426707 | bigcode/the-stack | train |
34657c65e319a9eb69f96646 | train | function | def _get_cmap(m_names):
"""Get a color map mapping a method name to color."""
cmap = {}
cm_type = cm.get_cmap('Accent')
for idx, colr in enumerate(cm_type(np.linspace(0, 1, len(m_names)))):
cmap[m_names[idx]] = colr
return cmap
| def _get_cmap(m_names):
| """Get a color map mapping a method name to color."""
cmap = {}
cm_type = cm.get_cmap('Accent')
for idx, colr in enumerate(cm_type(np.linspace(0, 1, len(m_names)))):
cmap[m_names[idx]] = colr
return cmap
| """
for method, choices in (choice_timelines.items()):
percent = np.mean(choices, axis=0)
ax.plot(range(len(percent)), percent, label=method)
ax.set_xlabel('t')
ax.set_ylabel('Percent')
ax.legend()
def _get_cmap(m_names):
| 64 | 64 | 73 | 8 | 56 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | _get_cmap | _get_cmap | 261 | 267 | 261 | 261 | 96f8b604d11059ef2878b4753b1d3fff4c943262 | bigcode/the-stack | train |
5795e617951f95cdb94c473f | train | function | def _plot_choice_trend(choice_timelines, ax):
"""Plot the percent of runs that picked context over time.
(choice must be binary)
Args:
choice_timeline: dict method -> ndarray of choices.
ax: pyplot ax object.
"""
for method, choices in (choice_timelines.items()):
percent = np... | def _plot_choice_trend(choice_timelines, ax):
| """Plot the percent of runs that picked context over time.
(choice must be binary)
Args:
choice_timeline: dict method -> ndarray of choices.
ax: pyplot ax object.
"""
for method, choices in (choice_timelines.items()):
percent = np.mean(choices, axis=0)
ax.plot(range(l... | to_add = to_add.replace('0', '')
to_add = to_add.capitalize()
tick_names.append(to_add)
ax.set_xticklabels(tick_names)
ax.set_ylabel('Proportion')
if add_legend:
ax.legend()
def _plot_choice_trend(choice_timelines, ax):
| 64 | 64 | 111 | 12 | 52 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | _plot_choice_trend | _plot_choice_trend | 247 | 259 | 247 | 247 | 02d7bf331640d78dcd8409d669711c0a8cf03db6 | bigcode/the-stack | train |
68ccd98ff31bc6aabb0782ed | train | function | def _write_or_show(show_figure, write_path):
"""Write figure or show figure or both."""
if write_path is not None:
plt.savefig(write_path, dpi=100)
if show_figure:
plt.show()
| def _write_or_show(show_figure, write_path):
| """Write figure or show figure or both."""
if write_path is not None:
plt.savefig(write_path, dpi=100)
if show_figure:
plt.show()
| cmap = {}
cm_type = cm.get_cmap('Accent')
for idx, colr in enumerate(cm_type(np.linspace(0, 1, len(m_names)))):
cmap[m_names[idx]] = colr
return cmap
def _write_or_show(show_figure, write_path):
| 64 | 64 | 50 | 12 | 51 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | _write_or_show | _write_or_show | 269 | 274 | 269 | 269 | d0cfdf56f8b2fe0cdab4b58acb59624cfb7905d5 | bigcode/the-stack | train |
b0b522c7244a3db57969c16e | train | function | def plot_summary(f_infos, results, show_figure=False, write_path=None):
"""Plot a bunch of information all at once."""
cmap = _get_cmap(list(results[0].keys()))
cant_regret = np.any([f_info.max_val is None for f_info in f_infos])
if len(f_infos) > 7 or len(results[0]) > 7:
# If there are too man... | def plot_summary(f_infos, results, show_figure=False, write_path=None):
| """Plot a bunch of information all at once."""
cmap = _get_cmap(list(results[0].keys()))
cant_regret = np.any([f_info.max_val is None for f_info in f_infos])
if len(f_infos) > 7 or len(results[0]) > 7:
# If there are too many function then just plot total regret.
fig, ax = plt.subplots(n... | """
Functions for plotting various quantities.
"""
from __future__ import division
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from scipy.stats import sem
from gp.gp_util import gp_regression
from OCBO.util.post_util im... | 118 | 205 | 684 | 17 | 100 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | plot_summary | plot_summary | 18 | 70 | 18 | 18 | 12dd8396f583db389c8c4e98de63a4e6d151073b | bigcode/the-stack | train |
a976803de45094d8355f16dc | train | function | def _plot_perf(regrets, ax, cmap, ylab='Simple Regret',
add_legend=True, ordering=None, ts=None, log_plot=False):
"""Plot the total simple regrets.
Args:
regrets: dict method -> ndarray, each row is a run's regret.
ax: pyplot ax object.
cmap: dict function name -> color.
... | def _plot_perf(regrets, ax, cmap, ylab='Simple Regret',
add_legend=True, ordering=None, ts=None, log_plot=False):
| """Plot the total simple regrets.
Args:
regrets: dict method -> ndarray, each row is a run's regret.
ax: pyplot ax object.
cmap: dict function name -> color.
add_legend: Whether to add a legend.
"""
if ordering is None:
ordering = regrets.keys()
if log_plot:
... | _vals = gp.eval(surf_pts)[0].reshape(dim1_pts.shape)
# Plot the surface and the data points.
if ax is None:
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(dim1_pts, dim2_pts, surf_vals, cmap=cm.coolwarm)
ax.scatter(x_data[:,0], x_data[:,1], y_data, s=50)
def _plot_perf(regrets, ax, ... | 122 | 122 | 407 | 34 | 88 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | _plot_perf | _plot_perf | 165 | 205 | 165 | 166 | 45a620610205930f46c5f176a4c323b797427ae7 | bigcode/the-stack | train |
9b91387424bb850fd5a30694 | train | function | def plot_total(f_infos, results, show_figure=False, write_path=None, ax=None,
add_legend=True, cmap=None, use_tex=False, ordering=None,
risk_neutral=False, log_plot=False, psuedo_regret=False):
"""Plot total regret.
Args:
f_infos: List of Namespace for function info used.
... | def plot_total(f_infos, results, show_figure=False, write_path=None, ax=None,
add_legend=True, cmap=None, use_tex=False, ordering=None,
risk_neutral=False, log_plot=False, psuedo_regret=False):
| """Plot total regret.
Args:
f_infos: List of Namespace for function info used.
results: Dict method -> List of results.
show_figure: Whether to show the figure.
write_path: Path to write the figure at.
ax: pyplot ax object to use for plotting.
add_legend: Whether ... | get_best_for_function(f_info.name, results)
if cant_regret:
_plot_perf(f_best, axs[plot_idx], cmap, ylab='Performance')
else:
f_regrets = best_vals_to_regrets([f_info], f_best)
_plot_perf(f_regrets, axs[plot_idx], cmap)
axs[plot_idx].set_title(f_info.name)
... | 153 | 153 | 513 | 52 | 101 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | plot_total | plot_total | 72 | 115 | 72 | 74 | 9d9548df87217d665455df55ed1cf6f633345075 | bigcode/the-stack | train |
c8642d0eb509f05839d3f907 | train | function | def _plot_proportions(f_names, proportions, ax, cmap, add_legend=True,
ordering=None):
"""Plot histogram of proportions for functions.
Args:
f_names: Name of the functions.
proportions: dict method -> ndarray, each row is a run's proportion.
ax: pyplot ax object.
... | def _plot_proportions(f_names, proportions, ax, cmap, add_legend=True,
ordering=None):
| """Plot histogram of proportions for functions.
Args:
f_names: Name of the functions.
proportions: dict method -> ndarray, each row is a run's proportion.
ax: pyplot ax object.
cmap: dict function name -> color.
add_legend: Whether to add a legend.
"""
if ordering... | linewidth=2)
ax.fill_between(plot_ts, avg - err, avg + err, color=cmap[method],
alpha=0.4)
ax.set_xlabel('t')
ax.set_ylabel(ylab)
if add_legend:
leg = ax.legend()
for legobj in leg.legendHandles:
legobj.set_linewidth(5.0)
def _plot_... | 104 | 104 | 347 | 24 | 80 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | _plot_proportions | _plot_proportions | 207 | 245 | 207 | 208 | 610cfe6749385e508e1cf24049da5ae3cdb87b6a | bigcode/the-stack | train |
36ddf09a7a3fae7d2353aec7 | train | function | def plot_props(f_infos, results, show_figure=False, write_path=None, ax=None,
add_legend=True, ordering=None, cmap=None):
"""Given results, plot proportions of how often each function as called.
Args:
f_infos: List of Namespace for function info used.
results: Dict method -> List ... | def plot_props(f_infos, results, show_figure=False, write_path=None, ax=None,
add_legend=True, ordering=None, cmap=None):
| """Given results, plot proportions of how often each function as called.
Args:
f_infos: List of Namespace for function info used.
results: Dict method -> List of results.
show_figure: Whether to show the figure.
write_path: Path to write the figure at.
ax: pyplot ax objec... | , cmap, ylab=ylab, add_legend=add_legend,
ordering=ordering, log_plot=log_plot)
_write_or_show(show_figure, write_path)
def plot_props(f_infos, results, show_figure=False, write_path=None, ax=None,
add_legend=True, ordering=None, cmap=None):
| 72 | 72 | 241 | 32 | 40 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | plot_props | plot_props | 117 | 139 | 117 | 118 | 7250ee4cb0c019e2b6ad73c859577691fee616cd | bigcode/the-stack | train |
008597d88cb6b8c1c6aeab4f | train | function | def visualize_mean_surface(domain, x_data, y_data, ax=None,
gp_engine='dragonfly', gp_options=None):
"""Given two-D data, fit a GP to it and make a 3D plot.
Args:
domain: List of lists representing x domain.
x_data: The x data as an ndarray.
y_data: The y data ... | def visualize_mean_surface(domain, x_data, y_data, ax=None,
gp_engine='dragonfly', gp_options=None):
| """Given two-D data, fit a GP to it and make a 3D plot.
Args:
domain: List of lists representing x domain.
x_data: The x data as an ndarray.
y_data: The y data as an ndarray.
ax: The axis object, makes a new one if None.
"""
# Get the surface points for the plot.
dim1... | (results, f_names)
if ax is None:
plt.figure(figsize=(18, 12))
ax = plt.subplot(111)
_plot_proportions(f_names, proportions, ax, cmap, add_legend=add_legend,
ordering=ordering)
_write_or_show(show_figure, write_path)
def visualize_mean_surface(domain, x_data, y_data, ax... | 95 | 95 | 317 | 26 | 69 | zhaofeng-shu33/OCBO | OCBO/util/plotting_util.py | Python | visualize_mean_surface | visualize_mean_surface | 141 | 163 | 141 | 142 | 94f0fa27f64b29e99872f27b26720d85d9ad89a7 | bigcode/the-stack | train |
44e28312e44f242f49d52dc7 | train | function | def Estudiante(id, tipo):
global mutex_estudiante, estudiantes_reunidos, num_estudiantes
time.sleep(random.random())
#Región crítica de estudiante
mutex_estudiante.acquire()
print(13*" "+"El estudiante %s número %d ha llegado a la reunión" %(tipo, id))
estudiantes_reunidos = estudiantes_reunidos... | def Estudiante(id, tipo):
| global mutex_estudiante, estudiantes_reunidos, num_estudiantes
time.sleep(random.random())
#Región crítica de estudiante
mutex_estudiante.acquire()
print(13*" "+"El estudiante %s número %d ha llegado a la reunión" %(tipo, id))
estudiantes_reunidos = estudiantes_reunidos + 1
if(estudiantes_re... | Región crítica de visitante
mutex_visitante.acquire()
visitantes_formados.append(id)
print(" El jefe de grupo está formado para ver al profesor en la posición" )
mutex_visitante.release()
profesor_libre.release()
#Definición del estudiante
def Estudiante(id, tipo):
| 64 | 64 | 133 | 7 | 56 | jorgelmp/sistop-2022-1 | proyectos/1/ManzanaresJorge-SalazarJesus/solicitud.py | Python | Estudiante | Estudiante | 59 | 70 | 59 | 59 | e79db31b3d6f7878ad6adf2c67b3d02e6d0e104c | bigcode/the-stack | train |
62e573f44340dd1f7f6f07f2 | train | function | def imprimeFila():
fila = ""
for i in visitantes_formados:
if(i==-1):
fila += " jefe de grupo,"
else:
fila += " visitante " + str(i) + ","
return fila[0:-1]
| def imprimeFila():
| fila = ""
for i in visitantes_formados:
if(i==-1):
fila += " jefe de grupo,"
else:
fila += " visitante " + str(i) + ","
return fila[0:-1]
| de visitante
mutex_visitante.acquire()
visitantes_formados.append(id)
print(13*" "+"El visitante %d está formado para ver al profesor" %id)
mutex_visitante.release()
profesor_libre.release()
#Método para imprimir la fila de visitantes formados
def imprimeFila():
| 64 | 64 | 54 | 4 | 59 | jorgelmp/sistop-2022-1 | proyectos/1/ManzanaresJorge-SalazarJesus/solicitud.py | Python | imprimeFila | imprimeFila | 85 | 92 | 85 | 85 | de7e3728d3302344b691376fb98a94645ca68c16 | bigcode/the-stack | train |
411df324843960f5e05321f4 | train | function | def JefeGrupo(id):
print(" El jefe de grupo ha iniciado la reunión y está esperando a sus compañeros")
print("")
jefe_esperando.acquire()
print(" El jefe de grupo está ecribiendo los argumentos")
time.sleep(2)
print(" El jefe de grupo ha escrito todos los argumentos y va a ir a ver al prof... | def JefeGrupo(id):
| print(" El jefe de grupo ha iniciado la reunión y está esperando a sus compañeros")
print("")
jefe_esperando.acquire()
print(" El jefe de grupo está ecribiendo los argumentos")
time.sleep(2)
print(" El jefe de grupo ha escrito todos los argumentos y va a ir a ver al profesor")
#Región ... | dar más tiempo para la entrega")
else:
print(" El profesor ha determinado que la fecha de entrega no se mueve")
else:
print(" El profesor ha terminado de atender al visitante")
mutex_visitante.release()
#Definición del jefe de grupo
def JefeGrupo(id):
| 64 | 64 | 130 | 6 | 57 | jorgelmp/sistop-2022-1 | proyectos/1/ManzanaresJorge-SalazarJesus/solicitud.py | Python | JefeGrupo | JefeGrupo | 42 | 54 | 42 | 42 | a3a844b69aa562704924b7cc9d1f7e59bba307c7 | bigcode/the-stack | train |
9947079b46af81bfc04b15ac | train | function | def Visitante(id):
global mutex_visitante, visitantes_formados, profesor_libre
time.sleep(5*random.random())
#Región crítica de visitante
mutex_visitante.acquire()
visitantes_formados.append(id)
print(13*" "+"El visitante %d está formado para ver al profesor" %id)
mutex_visitante.release()
... | def Visitante(id):
| global mutex_visitante, visitantes_formados, profesor_libre
time.sleep(5*random.random())
#Región crítica de visitante
mutex_visitante.acquire()
visitantes_formados.append(id)
print(13*" "+"El visitante %d está formado para ver al profesor" %id)
mutex_visitante.release()
profesor_libre.r... | if(estudiantes_reunidos == num_estudiantes):
print(13*" "+"Los %d estudiantes están reunidos, es hora de deliberar" %(num_estudiantes))
print("")
jefe_esperando.release()
mutex_estudiante.release()
#Definición del visitante
def Visitante(id):
| 64 | 64 | 81 | 5 | 58 | jorgelmp/sistop-2022-1 | proyectos/1/ManzanaresJorge-SalazarJesus/solicitud.py | Python | Visitante | Visitante | 74 | 82 | 74 | 74 | 8d004103a088662cbd737556aedb48b20a0e405c | bigcode/the-stack | train |
adaece2b4ccd7e754b72a52b | train | function | def Profesor():
global severidad_profesor, num_estudiantes, num_jovenes, num_visitantes
print(" El profesor se encuentra en su oficina listo para recibir visitas")
print("")
while(num_visitantes > 0):
profesor_libre.acquire()
print(" El profesor informa que la lista de visitantes for... | def Profesor():
| global severidad_profesor, num_estudiantes, num_jovenes, num_visitantes
print(" El profesor se encuentra en su oficina listo para recibir visitas")
print("")
while(num_visitantes > 0):
profesor_libre.acquire()
print(" El profesor informa que la lista de visitantes formados es:", impr... | idos = 0
error = 1
visitantes_formados = []
#Semáforos utilizados
mutex_estudiante = threading.Semaphore(1)
mutex_visitante = threading.Semaphore(1)
profesor_libre = threading.Semaphore(0)
jefe_esperando = threading.Semaphore(0)
#Definición del profesor
def Profesor():
| 77 | 77 | 259 | 3 | 73 | jorgelmp/sistop-2022-1 | proyectos/1/ManzanaresJorge-SalazarJesus/solicitud.py | Python | Profesor | Profesor | 19 | 38 | 19 | 19 | 0a2ca16d2fc086390af4898284a5af964d75eaec | bigcode/the-stack | train |
9d38b821ec5326e9fa32e894 | train | class | class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
group = db.relationship(Group)
def __repr__(self):
return "<User %r>" % self.username
| class User(db.Model):
| id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
group = db.relationship(Group)
def __repr__(self):
return "<User %r>" % self.username
| .db"
db = SQLAlchemy(app)
class Group(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
def __repr__(self):
return "<User %r>" % self.username
class User(db.Model):
| 64 | 64 | 58 | 5 | 58 | ea-evdokimov/SmartDict | env/lib/python3.6/site-packages/tests/example.py | Python | User | User | 18 | 24 | 18 | 18 | 9b26f44e5019b8896e360a5a3bb589fa568583f0 | bigcode/the-stack | train |
fa74c2e487928627532e3888 | train | class | class Group(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
def __repr__(self):
return "<User %r>" % self.username
| class Group(db.Model):
| id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
def __repr__(self):
return "<User %r>" % self.username
| =missing-docstring,too-few-public-methods,invalid-name
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"
db = SQLAlchemy(app)
class Group(db.Model):
| 64 | 64 | 51 | 5 | 59 | ea-evdokimov/SmartDict | env/lib/python3.6/site-packages/tests/example.py | Python | Group | Group | 10 | 15 | 10 | 10 | 12e5e6a31232d58a3de3f25f5c0990a6a3bbd8b3 | bigcode/the-stack | train |
83ab4fb9b347162e911f7c90 | train | class | class Migration(migrations.Migration):
dependencies = [
('workflows', '0002_auto_20210421_0926'),
]
operations = [
migrations.RenameField(
model_name='workflow',
old_name='dependsOnWorkflow',
new_name='triggerWorkflow',
),
migrations.Rena... | class Migration(migrations.Migration):
| dependencies = [
('workflows', '0002_auto_20210421_0926'),
]
operations = [
migrations.RenameField(
model_name='workflow',
old_name='dependsOnWorkflow',
new_name='triggerWorkflow',
),
migrations.RenameField(
model_name='workflo... | # Generated by Django 3.1.8 on 2021-04-26 19:19
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 96 | 7 | 28 | rberrelleza/cuelake | api/workflows/migrations/0003_auto_20210426_1919.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | ecafc636eb6795340f81e8e7ea37552181371d17 | bigcode/the-stack | train |
747c89e1d103d470224ad495 | train | function | def eval_cityscapes_on_kitti(detector='faster_rcnn_cityscapes', num_classes=8):
model = init_detector(model_configs[detector]['config_file'],
model_configs[detector]['checkpoint'], device='cuda:0')
# hook_fc_share = Hook(model.roi_head.bbox_head.shared_fcs._modules['1'])
# hook_cls... | def eval_cityscapes_on_kitti(detector='faster_rcnn_cityscapes', num_classes=8):
| model = init_detector(model_configs[detector]['config_file'],
model_configs[detector]['checkpoint'], device='cuda:0')
# hook_fc_share = Hook(model.roi_head.bbox_head.shared_fcs._modules['1'])
# hook_cls = Hook(model.roi_head.bbox_head.fc_cls)
fcs = []
logits = []
softm... | as np
import torch.nn as nn
# os.environ['CUDA_VISIBLE_DEVICES'] = '1'
from kitti import model_configs
from util import ProgressBar, Hook
from mmdet.apis import init_detector, inference_detector, show_result_pyplot
from kitti_extract import iou
data_dir = '/home/kengo/Documents/GitHub/mmdetection-intermediate/data... | 243 | 243 | 811 | 24 | 219 | A1chemyStars/mmdetection-intermediate | demo/cityscapes_kitti_extract.py | Python | eval_cityscapes_on_kitti | eval_cityscapes_on_kitti | 33 | 118 | 33 | 33 | f382222d923fbe77db80bb2bb6af9a14f9fd3ecc | bigcode/the-stack | train |
9b4e4be6df0400a517d901d9 | train | function | def vis_bbox(img, bbox, thick=1):
"""Visualizes a bounding box."""
(x0, y0, w, h) = bbox
x1, y1 = int(x0 + w), int(y0 + h)
x0, y0 = int(x0), int(y0)
cv2.rectangle(img, (x0, y0), (x1, y1), _GREEN, thickness=thick)
return img
| def vis_bbox(img, bbox, thick=1):
| """Visualizes a bounding box."""
(x0, y0, w, h) = bbox
x1, y1 = int(x0 + w), int(y0 + h)
x0, y0 = int(x0), int(y0)
cv2.rectangle(img, (x0, y0), (x1, y1), _GREEN, thickness=thick)
return img
| txt_tl = x0, y0 - int(0.3 * txt_h)
cv2.putText(img, txt, txt_tl, font, font_scale, _GRAY, lineType=cv2.LINE_AA)
return img
def vis_bbox(img, bbox, thick=1):
| 64 | 64 | 100 | 11 | 52 | intel/Detectron | detectron/utils/vis.py | Python | vis_bbox | vis_bbox | 131 | 137 | 131 | 131 | 3f0f9025de22ce678b1bce4126eaccc3f9bb1f74 | bigcode/the-stack | train |
cd2a468b7101c1504c51352c | train | function | def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
"""Visualizes a single binary mask."""
img = img.astype(np.float32)
idx = np.nonzero(mask)
img[idx[0], idx[1], :] *= 1.0 - alpha
img[idx[0], idx[1], :] += alpha * col
if show_border:
_, contours, _ = cv2.findCo... | def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
| """Visualizes a single binary mask."""
img = img.astype(np.float32)
idx = np.nonzero(mask)
img[idx[0], idx[1], :] *= 1.0 - alpha
img[idx[0], idx[1], :] += alpha * col
if show_border:
_, contours, _ = cv2.findContours(
mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
... | _index] if dataset is not None else \
'id{:d}'.format(class_index)
return class_text + ' {:0.2f}'.format(score).lstrip('0')
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
| 64 | 64 | 154 | 25 | 39 | intel/Detectron | detectron/utils/vis.py | Python | vis_mask | vis_mask | 97 | 111 | 97 | 97 | d608da03c7cb056060ccd108e4ea85537ba00bd0 | bigcode/the-stack | train |
371e39402ca597ed27c7d783 | train | function | def vis_one_image(
im, im_name, output_dir, boxes, segms=None, keypoints=None, thresh=0.9,
kp_thresh=2, dpi=200, box_alpha=0.0, dataset=None, show_class=False,
ext='pdf', out_when_no_box=False):
"""Visual debugging of detections."""
if not os.path.exists(output_dir):
os.makedirs(... | def vis_one_image(
im, im_name, output_dir, boxes, segms=None, keypoints=None, thresh=0.9,
kp_thresh=2, dpi=200, box_alpha=0.0, dataset=None, show_class=False,
ext='pdf', out_when_no_box=False):
| """Visual debugging of detections."""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if isinstance(boxes, list):
boxes, segms, keypoints, classes = convert_from_cls_format(
boxes, segms, keypoints)
if (boxes is None or boxes.shape[0] == 0 or max(boxes[:, 4]) < t... | _box:
im = vis_bbox(
im, (bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]))
# show class (off by default)
if show_class:
class_str = get_class_string(classes[i], score, dataset)
im = vis_class(im, (bbox[0], bbox[1] - 2), class_str)
# s... | 256 | 256 | 1,487 | 65 | 190 | intel/Detectron | detectron/utils/vis.py | Python | vis_one_image | vis_one_image | 251 | 392 | 251 | 254 | 0fe25362637eab383ba3431150f5ed6e9b1967e8 | bigcode/the-stack | train |
ce17978b8c612485909a54e0 | train | function | def get_class_string(class_index, score, dataset):
class_text = dataset.classes[class_index] if dataset is not None else \
'id{:d}'.format(class_index)
return class_text + ' {:0.2f}'.format(score).lstrip('0')
| def get_class_string(class_index, score, dataset):
| class_text = dataset.classes[class_index] if dataset is not None else \
'id{:d}'.format(class_index)
return class_text + ' {:0.2f}'.format(score).lstrip('0')
| klist]
else:
keyps = None
classes = []
for j, cls_box in enumerate(cls_boxes):
classes += [(j % 81)] * len(cls_box)
return boxes, segms, keyps, classes
def get_class_string(class_index, score, dataset):
| 64 | 64 | 57 | 11 | 52 | intel/Detectron | detectron/utils/vis.py | Python | get_class_string | get_class_string | 91 | 94 | 91 | 91 | d82da5ff6eec4ab5b27f7da69e3c7d3d87d73a3c | bigcode/the-stack | train |
b7dffbb5da151a38b9fb5d37 | train | function | def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7):
"""Visualizes keypoints (adapted from vis_one_image).
kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
"""
dataset_keypoints, _ = keypoint_utils.get_keypoints()
kp_lines = kp_connections(dataset_keypoints)
# Convert from pl... | def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7):
| """Visualizes keypoints (adapted from vis_one_image).
kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
"""
dataset_keypoints, _ = keypoint_utils.get_keypoints()
kp_lines = kp_connections(dataset_keypoints)
# Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
... | )
# Place text background.
back_tl = x0, y0 - int(1.3 * txt_h)
back_br = x0 + txt_w, y0
cv2.rectangle(img, back_tl, back_br, _GREEN, -1)
# Show text.
txt_tl = x0, y0 - int(0.3 * txt_h)
cv2.putText(img, txt, txt_tl, font, font_scale, _GRAY, lineType=cv2.LINE_AA)
return img
def vis_bbox(... | 237 | 237 | 791 | 20 | 216 | intel/Detectron | detectron/utils/vis.py | Python | vis_keypoints | vis_keypoints | 140 | 198 | 140 | 140 | 959359bb879140f541dbba300b3dda4f6e9010dc | bigcode/the-stack | train |
fa73387961fb1ff058af7c6b | train | function | def vis_one_image_opencv(
im, boxes, segms=None, keypoints=None, thresh=0.9, kp_thresh=2,
show_box=False, dataset=None, show_class=False):
"""Constructs a numpy array with the detections visualized."""
if isinstance(boxes, list):
boxes, segms, keypoints, classes = convert_from_cls_forma... | def vis_one_image_opencv(
im, boxes, segms=None, keypoints=None, thresh=0.9, kp_thresh=2,
show_box=False, dataset=None, show_class=False):
| """Constructs a numpy array with the detections visualized."""
if isinstance(boxes, list):
boxes, segms, keypoints, classes = convert_from_cls_format(
boxes, segms, keypoints)
if boxes is None or boxes.shape[0] == 0 or max(boxes[:, 4]) < thresh:
return im
if segms is not N... | ], thickness=-1, lineType=cv2.LINE_AA)
if kps[2, i2] > kp_thresh:
cv2.circle(
kp_mask, p2,
radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)
# Blend the keypoints.
return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)
def vis_one_image_open... | 134 | 134 | 447 | 43 | 91 | intel/Detectron | detectron/utils/vis.py | Python | vis_one_image_opencv | vis_one_image_opencv | 201 | 248 | 201 | 203 | 7a1f311fde7155d94357ee7eecf4f1560d79c33e | bigcode/the-stack | train |
95e7ef5a2274e08d37f190f2 | train | function | def vis_class(img, pos, class_str, font_scale=0.35):
"""Visualizes the class."""
x0, y0 = int(pos[0]), int(pos[1])
# Compute text size.
txt = class_str
font = cv2.FONT_HERSHEY_SIMPLEX
((txt_w, txt_h), _) = cv2.getTextSize(txt, font, font_scale, 1)
# Place text background.
back_tl = x0, y... | def vis_class(img, pos, class_str, font_scale=0.35):
| """Visualizes the class."""
x0, y0 = int(pos[0]), int(pos[1])
# Compute text size.
txt = class_str
font = cv2.FONT_HERSHEY_SIMPLEX
((txt_w, txt_h), _) = cv2.getTextSize(txt, font, font_scale, 1)
# Place text background.
back_tl = x0, y0 - int(1.3 * txt_h)
back_br = x0 + txt_w, y0
... | 2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA)
return img.astype(np.uint8)
def vis_class(img, pos, class_str, font_scale=0.35):
| 64 | 64 | 206 | 17 | 47 | intel/Detectron | detectron/utils/vis.py | Python | vis_class | vis_class | 114 | 128 | 114 | 114 | 1cb95fc5ea8625473aa76badea05396add95b3be | bigcode/the-stack | train |
fdf2a78ca8fe54fe432a129a | train | function | def convert_from_cls_format(cls_boxes, cls_segms, cls_keyps):
"""Convert from the class boxes/segms/keyps format generated by the testing
code.
"""
box_list = [b for b in cls_boxes if len(b) > 0]
if len(box_list) > 0:
boxes = np.concatenate(box_list)
else:
boxes = None
if cls... | def convert_from_cls_format(cls_boxes, cls_segms, cls_keyps):
| """Convert from the class boxes/segms/keyps format generated by the testing
code.
"""
box_list = [b for b in cls_boxes if len(b) > 0]
if len(box_list) > 0:
boxes = np.concatenate(box_list)
else:
boxes = None
if cls_segms is not None:
segms = [s for slist in cls_segms ... | left_ankle')],
[keypoints.index('right_shoulder'), keypoints.index('left_shoulder')],
[keypoints.index('right_hip'), keypoints.index('left_hip')],
]
return kp_lines
def convert_from_cls_format(cls_boxes, cls_segms, cls_keyps):
| 64 | 64 | 199 | 16 | 47 | intel/Detectron | detectron/utils/vis.py | Python | convert_from_cls_format | convert_from_cls_format | 68 | 88 | 68 | 68 | 20fb3e48cda648b9db79ab58c34366b9cfdcb9ee | bigcode/the-stack | train |
c399e433530fa929dab5eb81 | train | function | def kp_connections(keypoints):
"""def kp connections"""
kp_lines = [
[keypoints.index('left_eye'), keypoints.index('right_eye')],
[keypoints.index('left_eye'), keypoints.index('nose')],
[keypoints.index('right_eye'), keypoints.index('nose')],
[keypoints.index('right_eye'), keypoi... | def kp_connections(keypoints):
| """def kp connections"""
kp_lines = [
[keypoints.index('left_eye'), keypoints.index('right_eye')],
[keypoints.index('left_eye'), keypoints.index('nose')],
[keypoints.index('right_eye'), keypoints.index('nose')],
[keypoints.index('right_eye'), keypoints.index('right_ear')],
... | point_utils
# Matplotlib requires certain adjustments in some environments
# Must happen before importing matplotlib
envu.set_up_matplotlib()
plt.rcParams['pdf.fonttype'] = 42 # For editing in Adobe Illustrator
_GRAY = (218, 227, 218)
_GREEN = (18, 127, 15)
_WHITE = (255, 255, 255)
def kp_connections(keypoints):
| 85 | 85 | 286 | 6 | 79 | intel/Detectron | detectron/utils/vis.py | Python | kp_connections | kp_connections | 46 | 65 | 46 | 46 | ead5d7a26c35849a47ef894c32ba7390f2854af2 | bigcode/the-stack | train |
0974626155ebb5f56ae5721d | train | class | class Mux21Shape(ogl.PolygonShape):
""" This shape is used exclusively to contruct the MUX 2-1 Gate main shape.
The shape is initially based within an 80x80 square, centered """
def __init__(self):
ogl.PolygonShape.__init__(self)
points = [ (-25, 40),
(25, 40),
... | class Mux21Shape(ogl.PolygonShape):
| """ This shape is used exclusively to contruct the MUX 2-1 Gate main shape.
The shape is initially based within an 80x80 square, centered """
def __init__(self):
ogl.PolygonShape.__init__(self)
points = [ (-25, 40),
(25, 40),
(30, 35),
... | import wx.lib.ogl as ogl
from myhdl import Signal, always
from MyHDLSim.combinational import Mux21
from MyHDLSim.Wrappers.GenericGateWrapper import GenericGateWrapper
class Mux21Shape(ogl.PolygonShape):
| 56 | 64 | 159 | 11 | 44 | mattsnowboard/msu-myhdlsim | MyHDLSim/Wrappers/Mux21Wrapper.py | Python | Mux21Shape | Mux21Shape | 6 | 24 | 6 | 6 | 2aa0ae1aaa3663a5d5dc22aa768a43a3af131f50 | bigcode/the-stack | train |
4f52a08cf198ec1380ed4940 | train | class | class Mux21Wrapper(GenericGateWrapper):
""" This class wraps a MyHDLSim.combinational.MUX21 function for drawing """
def __init__(self, drawManager, x, y, out, select, a, b):
GenericGateWrapper.__init__(self, drawManager, x, y, [a,b], Mux21Shape(), out, [select])
self._CreateInstance(Mux21,... | class Mux21Wrapper(GenericGateWrapper):
| """ This class wraps a MyHDLSim.combinational.MUX21 function for drawing """
def __init__(self, drawManager, x, y, out, select, a, b):
GenericGateWrapper.__init__(self, drawManager, x, y, [a,b], Mux21Shape(), out, [select])
self._CreateInstance(Mux21, out, select, a, b)
GenericGate... | (-25, -40),
(-30, -35),
(-30, 35) ]
self.Create(points)
self.CalculatePolygonCentre
self.AddText("MUX 2-1")
self.SetRegionName("MUX 2-1")
class Mux21Wrapper(GenericGateWrapper):
| 64 | 64 | 112 | 9 | 55 | mattsnowboard/msu-myhdlsim | MyHDLSim/Wrappers/Mux21Wrapper.py | Python | Mux21Wrapper | Mux21Wrapper | 26 | 33 | 26 | 26 | 3298f705d2c69cc94e6b4303a2d4362ef8904fad | bigcode/the-stack | train |
08b91d8e38c6aae699f62d35 | train | function | @deprecated.deprecated(reason="Use `ElasticsearchWrapper.get_instance` instead")
def create_es_wrapper() -> ElasticsearchWrapper:
"""
Creates a instance of ElasticsearchWrapper.
This function is used in fastapi for resolve component dependencies.
See <https://fastapi.tiangolo.com/tutorial/dependen... | @deprecated.deprecated(reason="Use `ElasticsearchWrapper.get_instance` instead")
def create_es_wrapper() -> ElasticsearchWrapper:
| """
Creates a instance of ElasticsearchWrapper.
This function is used in fastapi for resolve component dependencies.
See <https://fastapi.tiangolo.com/tutorial/dependencies/>
Returns
-------
"""
global _instance
if _instance is None:
_instance = ElasticsearchWrapper.... | ": {aggregation_name: aggregation}}
)
return es_helpers.parse_aggregations(results["aggregations"]).get(
aggregation_name
)
_instance = None # The singleton instance
@deprecated.deprecated(reason="Use `ElasticsearchWrapper.get_instance` instead")
def create_es_wrapper() -> Elasti... | 64 | 64 | 97 | 25 | 38 | leireropl/rubrix | src/rubrix/server/elasticseach/client_wrapper.py | Python | create_es_wrapper | create_es_wrapper | 571 | 589 | 571 | 572 | 0d2e8d18a7f1cd89e40caf771ff636831836ef85 | bigcode/the-stack | train |
9b0fba5ed15f3155944cc2e0 | train | class | class GenericSearchError(Exception):
def __init__(self, origin_error: Exception):
self.origin_error = origin_error
| class GenericSearchError(Exception):
| def __init__(self, origin_error: Exception):
self.origin_error = origin_error
| .errors import InvalidTextSearchError
try:
import ujson as json
except ModuleNotFoundError:
import json
from rubrix.server.apis.v0.settings.server import settings
class ClosedIndexError(Exception):
pass
class IndexNotFoundError(Exception):
pass
class GenericSearchError(Exception):
| 64 | 64 | 26 | 6 | 57 | leireropl/rubrix | src/rubrix/server/elasticseach/client_wrapper.py | Python | GenericSearchError | GenericSearchError | 42 | 44 | 42 | 42 | b73b5a2a4dbaca7b1264c60cc5407d579e5f2f87 | bigcode/the-stack | train |
1661b18bfe85e07e87acf9fa | train | class | class IndexNotFoundError(Exception):
pass
| class IndexNotFoundError(Exception):
| pass
| .logging import LoggingMixin
from rubrix.server.errors import InvalidTextSearchError
try:
import ujson as json
except ModuleNotFoundError:
import json
from rubrix.server.apis.v0.settings.server import settings
class ClosedIndexError(Exception):
pass
class IndexNotFoundError(Exception):
| 64 | 64 | 10 | 7 | 56 | leireropl/rubrix | src/rubrix/server/elasticseach/client_wrapper.py | Python | IndexNotFoundError | IndexNotFoundError | 38 | 39 | 38 | 38 | 6ce29f3070174a373bac44f7d570ea276e82d721 | bigcode/the-stack | train |
b82d98997806afe80764dc9c | train | class | class ClosedIndexError(Exception):
pass
| class ClosedIndexError(Exception):
| pass
| .helpers import scan as es_scan
from rubrix.logging import LoggingMixin
from rubrix.server.errors import InvalidTextSearchError
try:
import ujson as json
except ModuleNotFoundError:
import json
from rubrix.server.apis.v0.settings.server import settings
class ClosedIndexError(Exception):
| 64 | 64 | 9 | 6 | 57 | leireropl/rubrix | src/rubrix/server/elasticseach/client_wrapper.py | Python | ClosedIndexError | ClosedIndexError | 34 | 35 | 34 | 34 | 07363ee5330f5bfd9a03ac5a701972fc6174b7e9 | bigcode/the-stack | train |
2d18100554b5596ea2e8157c | train | class | class ElasticsearchWrapper(LoggingMixin):
"""A simple elasticsearch client wrapper for atomize some repetitive operations"""
_INSTANCE = None
@classmethod
def get_instance(cls) -> "ElasticsearchWrapper":
"""
Creates an instance of ElasticsearchWrapper.
This function is used in... | class ElasticsearchWrapper(LoggingMixin):
| """A simple elasticsearch client wrapper for atomize some repetitive operations"""
_INSTANCE = None
@classmethod
def get_instance(cls) -> "ElasticsearchWrapper":
"""
Creates an instance of ElasticsearchWrapper.
This function is used in fastapi for resolve component dependencie... | may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Li... | 256 | 256 | 3,030 | 7 | 248 | leireropl/rubrix | src/rubrix/server/elasticseach/client_wrapper.py | Python | ElasticsearchWrapper | ElasticsearchWrapper | 47 | 565 | 47 | 47 | 72b474a8a0eee195c8a10ed7e730e99b21aa30b8 | bigcode/the-stack | train |
608d4533514e133298be5ccd | train | class | class ConfigReader():
def read_config(self, filename: str) -> dict:
config_dict = { 'error': "no config file found" }
try:
with open(filename, "r") as json_file:
try:
config_dict = json.load(json_file)
except Exception as e:
... | class ConfigReader():
| def read_config(self, filename: str) -> dict:
config_dict = { 'error': "no config file found" }
try:
with open(filename, "r") as json_file:
try:
config_dict = json.load(json_file)
except Exception as e:
print("json e... | import json
#import glob
class ConfigReader():
| 10 | 64 | 173 | 4 | 5 | 1nd2rd3st/python-qt5-hello-world | configreader/configreader.py | Python | ConfigReader | ConfigReader | 4 | 26 | 4 | 5 | 38a42188d9b88d4d42c02a60bc0b019469be6602 | bigcode/the-stack | train |
2847807ed3c12aad63470961 | train | function | def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
"""Convert a list of bounding boxes from the format used by albumentations to a format, specified
in `target_format`.
Args:
bboxes (List[tuple]): List of albumentation bounding box `(x_min, y_min, x_max... | def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
| """Convert a list of bounding boxes from the format used by albumentations to a format, specified
in `target_format`.
Args:
bboxes (List[tuple]): List of albumentation bounding box `(x_min, y_min, x_max, y_max)`.
target_format (str): required format of the output bounding box. Should be 'co... | the format used by albumentations
"""
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox in bboxes]
def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
| 64 | 64 | 191 | 24 | 40 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | convert_bboxes_from_albumentations | convert_bboxes_from_albumentations | 307 | 322 | 307 | 307 | f17858e1cd58662caf38b4d6c848585c6603ba75 | bigcode/the-stack | train |
a3eaf564fc0b9d7b51a9e8c7 | train | function | def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False):
"""Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.
Args:
bbox (tuple): An albumentation bounding box `(x_min, y_min, x_max, y_max)`.
target_forma... | def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False):
| """Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.
Args:
bbox (tuple): An albumentation bounding box `(x_min, y_min, x_max, y_max)`.
target_format (str): required format of the output bounding box. Should be 'coco', 'pascal_voc' or 'yolo'... | 1)):
raise ValueError("In YOLO format all labels must be float and in range (0, 1]")
x, y, width, height = denormalize_bbox(bbox, rows, cols)
x_min = x - width / 2
x_max = x_min + width
y_min = y - height / 2
y_max = y_min + height
else:
(x_min, y_min, ... | 187 | 187 | 624 | 23 | 163 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | convert_bbox_from_albumentations | convert_bbox_from_albumentations | 256 | 298 | 256 | 256 | e5944628deea42a37880b9aee064eb21fe822158 | bigcode/the-stack | train |
11cfcfbb5d5dfc5488272fab | train | function | def calculate_bbox_area(bbox, rows, cols):
"""Calculate the area of a bounding box in pixels.
Args:
bbox (tuple): A bounding box `(x_min, y_min, x_max, y_max)`.
rows (int): Image height.
cols (int): Image width.
Return:
int: Area of a bounding box in pixels.
"""
bb... | def calculate_bbox_area(bbox, rows, cols):
| """Calculate the area of a bounding box in pixels.
Args:
bbox (tuple): A bounding box `(x_min, y_min, x_max, y_max)`.
rows (int): Image height.
cols (int): Image width.
Return:
int: Area of a bounding box in pixels.
"""
bbox = denormalize_bbox(bbox, rows, cols)
... | Image width.
Returns:
List[tuple]: Denormalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
"""
return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
def calculate_bbox_area(bbox, rows, cols):
| 64 | 64 | 133 | 11 | 53 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | calculate_bbox_area | calculate_bbox_area | 143 | 158 | 143 | 143 | f7691104ff43c8ab9e838a30981ba1e24e9038d2 | bigcode/the-stack | train |
5f8e93e0449074332bffb0fb | train | function | def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
"""Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`(x_min, y_min, x... | def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
| """Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`(x_min, y_min, x_max, y_max)` e.g. `(0.15, 0.27, 0.67, 0.5)`.
Args:
bbox (tuple): A bounding b... | threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0].
min_area (float): Minimal area threshold.
Returns:
List[tuple]: Filtered bounding boxes `[(x_min, y_min, x_max, y_max)]`.
"""
img_height, img_width = original_shape[:2]
transformed_img_height, t... | 239 | 239 | 799 | 23 | 215 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | convert_bbox_to_albumentations | convert_bbox_to_albumentations | 196 | 253 | 196 | 196 | 957d2a1e70d8807c9617cf980db2b59d322b65ad | bigcode/the-stack | train |
c93d9eedbe3f5d19e2b764f8 | train | class | class BboxProcessor(DataProcessor):
@property
def default_data_name(self):
return "bboxes"
def ensure_data_valid(self, data):
for data_name in self.data_fields:
data_exists = data_name in data and len(data[data_name])
if data_exists and len(data[data_name][0]) < 5:
... | class BboxProcessor(DataProcessor):
@property
| def default_data_name(self):
return "bboxes"
def ensure_data_valid(self, data):
for data_name in self.data_fields:
data_exists = data_name in data and len(data[data_name])
if data_exists and len(data[data_name][0]) < 5:
if self.params.label_fields is None... | denormalize_bbox",
"normalize_bboxes",
"denormalize_bboxes",
"calculate_bbox_area",
"filter_bboxes_by_visibility",
"convert_bbox_to_albumentations",
"convert_bbox_from_albumentations",
"convert_bboxes_to_albumentations",
"convert_bboxes_from_albumentations",
"BboxProcessor",
]
class ... | 93 | 93 | 312 | 11 | 82 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | BboxProcessor | BboxProcessor | 21 | 52 | 21 | 22 | c7c8d7f346f34fff29b89350e2b9511af612a142 | bigcode/the-stack | train |
0c34d6cf0bf0b316c19bd1ab | train | function | def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
"""Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
"""
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox... | def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
| """Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
"""
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox in bboxes]
| x_max - x_min
height = y_max - y_min
bbox = normalize_bbox((x, y, width, height) + tail, rows, cols)
return bbox
def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
| 64 | 64 | 81 | 24 | 39 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | convert_bboxes_to_albumentations | convert_bboxes_to_albumentations | 301 | 304 | 301 | 301 | 8d974fe945bdf2519533aea879b7d27bc9a49951 | bigcode/the-stack | train |
974f4e314a4f000a9b6ebb7e | train | function | def union_of_bboxes(height, width, bboxes, erosion_rate=0.0):
"""Calculate union of bounding boxes.
Args:
height (float): Height of image or space.
width (float): Width of image or space.
bboxes (List[tuple]): List like bounding boxes. Format is `[(x_min, y_min, x_max, y_max)]`.
... | def union_of_bboxes(height, width, bboxes, erosion_rate=0.0):
| """Calculate union of bounding boxes.
Args:
height (float): Height of image or space.
width (float): Width of image or space.
bboxes (List[tuple]): List like bounding boxes. Format is `[(x_min, y_min, x_max, y_max)]`.
erosion_rate (float): How much each bounding box can be shrin... | _area(bbox, rows, cols)
if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visibility:
continue
else:
bbox = tuple(np.clip(bbox[:4], 0, 1.0))
if calculate_bbox_area(bbox, rows, cols) <= min_area:
continue
resulting_boxes.appe... | 103 | 103 | 346 | 19 | 83 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | union_of_bboxes | union_of_bboxes | 379 | 402 | 379 | 379 | ba5b45310f5f96fcafe810de15f97634438db55f | bigcode/the-stack | train |
e3d92925a0098a9ae37ef8ba | train | function | def denormalize_bboxes(bboxes, rows, cols):
"""Denormalize a list of bounding boxes.
Args:
bboxes (List[tuple]): Normalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
rows (int): Image height.
cols (int): Image width.
Returns:
List[tuple]: Denormalized bounding boxes ... | def denormalize_bboxes(bboxes, rows, cols):
| """Denormalize a list of bounding boxes.
Args:
bboxes (List[tuple]): Normalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
rows (int): Image height.
cols (int): Image width.
Returns:
List[tuple]: Denormalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
"""
... | ): Image width.
Returns:
List[tuple]: Normalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
"""
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
def denormalize_bboxes(bboxes, rows, cols):
| 64 | 64 | 120 | 13 | 51 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | denormalize_bboxes | denormalize_bboxes | 128 | 140 | 128 | 128 | 4a41461bf306682b98f66fa15371212c14bf019a | bigcode/the-stack | train |
a4bd24c7cd93bed1e5fbebb7 | train | function | def normalize_bboxes(bboxes, rows, cols):
"""Normalize a list of bounding boxes.
Args:
bboxes (List[tuple]): Denormalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
rows (int): Image height.
cols (int): Image width.
Returns:
List[tuple]: Normalized bounding boxes `[(x... | def normalize_bboxes(bboxes, rows, cols):
| """Normalize a list of bounding boxes.
Args:
bboxes (List[tuple]): Denormalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
rows (int): Image height.
cols (int): Image width.
Returns:
List[tuple]: Normalized bounding boxes `[(x_min, y_min, x_max, y_max)]`.
"""
... | ")
x_min, x_max = x_min * cols, x_max * cols
y_min, y_max = y_min * rows, y_max * rows
return (x_min, y_min, x_max, y_max) + tail
def normalize_bboxes(bboxes, rows, cols):
| 64 | 64 | 114 | 11 | 52 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | normalize_bboxes | normalize_bboxes | 113 | 125 | 113 | 113 | d0f17b51071b84f7ee125f0f75d7f09dd94bb195 | bigcode/the-stack | train |
972670d9e06f2aef25616b40 | train | function | def filter_bboxes(bboxes, rows, cols, min_area=0.0, min_visibility=0.0):
"""Remove bounding boxes that either lie outside of the visible area by more then min_visibility
or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size.
Args:
bboxes (List[tup... | def filter_bboxes(bboxes, rows, cols, min_area=0.0, min_visibility=0.0):
| """Remove bounding boxes that either lie outside of the visible area by more then min_visibility
or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size.
Args:
bboxes (List[tuple]): List of albumentation bounding box `(x_min, y_min, x_max, y_max)`.
... | if y_max <= y_min:
raise ValueError("y_max is less than or equal to y_min for bbox {bbox}.".format(bbox=bbox))
def check_bboxes(bboxes):
"""Check if bboxes boundaries are in range 0, 1 and minimums are lesser then maximums"""
for bbox in bboxes:
check_bbox(bbox)
def filter_bboxes(bboxes, rows... | 103 | 103 | 344 | 25 | 78 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | filter_bboxes | filter_bboxes | 348 | 376 | 348 | 348 | 0dd613a442919bcaccbf257620d7d0b30c6d8986 | bigcode/the-stack | train |
668f0eed4461789d392f27e5 | train | function | def denormalize_bbox(bbox, rows, cols):
"""Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
Args:
bbox (tuple): Normalized bounding box `(x_... | def denormalize_bbox(bbox, rows, cols):
| """Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
Args:
bbox (tuple): Normalized bounding box `(x_min, y_min, x_max, y_max)`.
rows... | 0:
raise ValueError("Argument cols must be positive integer")
x_min, x_max = x_min / cols, x_max / cols
y_min, y_max = y_min / rows, y_max / rows
return (x_min, y_min, x_max, y_max) + tail
def denormalize_bbox(bbox, rows, cols):
| 79 | 79 | 264 | 12 | 66 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | denormalize_bbox | denormalize_bbox | 84 | 110 | 84 | 84 | b4e57ff1027726a64aa8c05e391cc7c9c27c71bb | bigcode/the-stack | train |
8321ac7685978a4030fefa7a | train | function | def filter_bboxes_by_visibility(
original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0.0, min_area=0.0,
):
"""Filter bounding boxes and return only those boxes whose visibility after transformation is above
the threshold and minimal area of bounding box in pixels is more then min_area.
... | def filter_bboxes_by_visibility(
original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0.0, min_area=0.0,
):
| """Filter bounding boxes and return only those boxes whose visibility after transformation is above
the threshold and minimal area of bounding box in pixels is more then min_area.
Args:
original_shape (tuple): Original image shape `(height, width)`.
bboxes (List[tuple]): Original bounding b... | cols (int): Image width.
Return:
int: Area of a bounding box in pixels.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox[:4]
area = (x_max - x_min) * (y_max - y_min)
return area
def filter_bboxes_by_visibility(
original_shape, bboxes, transformed_sha... | 111 | 111 | 373 | 35 | 75 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | filter_bboxes_by_visibility | filter_bboxes_by_visibility | 161 | 193 | 161 | 163 | 3600150f0257fa054c5062466fd1a6852c7292eb | bigcode/the-stack | train |
0bea48a08f65d8d796abd07c | train | function | def normalize_bbox(bbox, rows, cols):
"""Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
Args:
bbox (tuple): Denormalized bounding box `(x_min, y_min, x_max, y_max)`.
rows (int): Image height.
cols (int): Image width.
... | def normalize_bbox(bbox, rows, cols):
| """Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
Args:
bbox (tuple): Denormalized bounding box `(x_min, y_min, x_max, y_max)`.
rows (int): Image height.
cols (int): Image width.
Returns:
tuple: Normalized... | (data, self.params.format, rows, cols, check_validity=True)
def convert_to_albumentations(self, data, rows, cols):
conversion = convert_bboxes_to_albumentations(data, self.params.format, rows, cols, check_validity=True)
return conversion
def normalize_bbox(bbox, rows, cols):
| 71 | 71 | 239 | 10 | 60 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | normalize_bbox | normalize_bbox | 55 | 81 | 55 | 55 | f2949c50b47ca7e05f6af9a165eb1e1fe0b6b30a | bigcode/the-stack | train |
f772465d35b174a77213a969 | train | function | def check_bboxes(bboxes):
"""Check if bboxes boundaries are in range 0, 1 and minimums are lesser then maximums"""
for bbox in bboxes:
check_bbox(bbox)
| def check_bboxes(bboxes):
| """Check if bboxes boundaries are in range 0, 1 and minimums are lesser then maximums"""
for bbox in bboxes:
check_bbox(bbox)
| x_max is less than or equal to x_min for bbox {bbox}.".format(bbox=bbox))
if y_max <= y_min:
raise ValueError("y_max is less than or equal to y_min for bbox {bbox}.".format(bbox=bbox))
def check_bboxes(bboxes):
| 64 | 64 | 44 | 7 | 57 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | check_bboxes | check_bboxes | 342 | 345 | 342 | 342 | b11e49feb35c2cc7fee769f990e46636ddf2a5b3 | bigcode/the-stack | train |
7491d5954ad19cf92dd38972 | train | function | def check_bbox(bbox):
"""Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"""
# Tolerance for floating point operation rounding
tolerance = 0.01
for name, value in zip(["x_min", "y_min", "x_max", "y_max"], bbox[:4]):
if not 0 - tolerance <= value <= 1 + tolerance:
... | def check_bbox(bbox):
| """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"""
# Tolerance for floating point operation rounding
tolerance = 0.01
for name, value in zip(["x_min", "y_min", "x_max", "y_max"], bbox[:4]):
if not 0 - tolerance <= value <= 1 + tolerance:
raise Valu... | width.
check_validity (bool): Check if all boxes are valid boxes.
Returns:
list[tuple]: List of bounding box.
"""
return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
def check_bbox(bbox):
| 68 | 68 | 229 | 6 | 62 | spencerng/albumentations | albumentations/augmentations/bbox_utils.py | Python | check_bbox | check_bbox | 325 | 339 | 325 | 325 | bb562e7393bd962d1c243fbc7c6528e9e8b1bb49 | bigcode/the-stack | train |
78a323dcd82c601b665c9fcb | train | class | class ActionMessageTestCase(unittest.TestCase):
def test_action_message_serialization_and_deserialization(self):
enqueue_mini_castle_for_review_action_label = ActionLabel(
"EnqueueMiniCastleForReview"
)
action_rules = [
ActionRule(
name="Enqueue Mini-... | class ActionMessageTestCase(unittest.TestCase):
| def test_action_message_serialization_and_deserialization(self):
enqueue_mini_castle_for_review_action_label = ActionLabel(
"EnqueueMiniCastleForReview"
)
action_rules = [
ActionRule(
name="Enqueue Mini-Castle for Review",
action_label... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import unittest
from hmalib.common.classification_models import (
BankedContentIDClassificationLabel,
BankIDClassificationLabel,
ClassificationLabel,
)
from hmalib.common.configs.evaluator import ActionLabel, ActionRule
from hmalib.comm... | 97 | 102 | 341 | 9 | 87 | crhird/ThreatExchange | hasher-matcher-actioner/hmalib/common/messages/tests/test_actioner_messages.py | Python | ActionMessageTestCase | ActionMessageTestCase | 14 | 57 | 14 | 14 | 7dee736540dd3b8e8b4723895c296325faa2dc30 | bigcode/the-stack | train |
36740be8b0a9ba1940d73236 | train | class | class ParserFuzzTest(unittest.TestCase):
@given(st.text(min_size=1), settings=settings.Settings(max_examples=10000))
@example('True')
@example(r'"test\t\t\a\\a"')
@example(r' "test\t\t\a\\a" ')
@example('"(1, 2)"')
@example('(1, 2)')
@example('(1, 2)')
@example('(1, 2) ')
@e... | class ParserFuzzTest(unittest.TestCase):
@given(st.text(min_size=1), settings=settings.Settings(max_examples=10000))
@example('True')
@example(r'"test\t\t\a\\a"')
@example(r' "test\t\t\a\\a" ')
@example('"(1, 2)"')
@example('(1, 2)')
@example('(1, 2)')
@example('(1, 2) ')
@e... | def testDefaultParseValueFuzz(self, value):
try:
result = parser.DefaultParseValue(value)
except TypeError:
# It's OK to get a TypeError if the string has the null character.
if u'\x00' in value:
return
raise
except MemoryError:
if len(value) > 100:
# This is ... | class ParserFuzzTest(unittest.TestCase):
@given(st.text(min_size=1), settings=settings.Settings(max_examples=10000))
@example('True')
@example(r'"test\t\t\a\\a"')
@example(r' "test\t\t\a\\a" ')
@example('"(1, 2)"')
@example('(1, 2)')
@example('(1, 2)')
@example('(1, 2) ')
@e... | 277 | 188 | 627 | 277 | 0 | hexnor/SurfFree----Web-Proxy----Django | vsurfree/lib/python2.7/site-packages/fire/parser_fuzz_test.py | Python | ParserFuzzTest | ParserFuzzTest | 30 | 93 | 30 | 53 | 3c1c535f9dafa0ede3639a19b9491fd0ccd3d28e | bigcode/the-stack | train |
2d8098f408787575158bcf45 | train | function | def update():
global x, xprev, t, n
ret_x = []
ret_xdot = []
for _ in range(timesteps_per_update):
xnext = (2*beta*x + (alpha - beta)*xprev - dV_dx(x) + gamma*np.cos(omega*t)) / (alpha+beta)
n += 1
t += dt
xdot = (xnext - xprev) / (2*dt)
xprev = x
x = xnex... | def update():
| global x, xprev, t, n
ret_x = []
ret_xdot = []
for _ in range(timesteps_per_update):
xnext = (2*beta*x + (alpha - beta)*xprev - dV_dx(x) + gamma*np.cos(omega*t)) / (alpha+beta)
n += 1
t += dt
xdot = (xnext - xprev) / (2*dt)
xprev = x
x = xnext
if n... | xdot = update()
dict_ = dict(x=x, xdot=xdot)
cds0.stream(dict_, rollover=rollover)
if n % timesteps_per_period == 0:
cds1.stream(dict(x=x[-1:], xdot=xdot[-1:]))
def update():
| 64 | 64 | 148 | 3 | 61 | teresafds/bokeh | examples/app/duffing_oscillator.py | Python | update | update | 67 | 81 | 67 | 67 | 5c24cc749656c99a606c08c416af3a9d5133c7e8 | bigcode/the-stack | train |
657eeba1fc84bb327bd56eef | train | function | def stream():
x, xdot = update()
dict_ = dict(x=x, xdot=xdot)
cds0.stream(dict_, rollover=rollover)
if n % timesteps_per_period == 0:
cds1.stream(dict(x=x[-1:], xdot=xdot[-1:]))
| def stream():
| x, xdot = update()
dict_ = dict(x=x, xdot=xdot)
cds0.stream(dict_, rollover=rollover)
if n % timesteps_per_period == 0:
cds1.stream(dict(x=x[-1:], xdot=xdot[-1:]))
| 0], xdot=[0])
cds1.data = dict(x=[], xdot=[])
line.data_source = cds0
circle.data_source = cds1
def slider_callback(_attr, _old, _new):
reset(delta_slider.value, gamma_slider.value, omega_slider.value)
def stream():
| 64 | 64 | 67 | 3 | 61 | teresafds/bokeh | examples/app/duffing_oscillator.py | Python | stream | stream | 60 | 65 | 60 | 60 | 80a0d10a2abed9ca9d022d54c4fdfbfb78366ecf | bigcode/the-stack | train |
784227f6be14413ef45ef56c | train | function | def reset(new_delta, new_gamma, new_omega):
global delta, gamma, omega, dt, t, xprev, x, n, alpha
delta = new_delta
gamma = new_gamma
omega = new_omega
dt = 2*np.pi/omega / timesteps_per_period
alpha = delta / (2*dt)
n = 0
t = 0
xprev = 0
x = 0
cds0.data = dict(x=[0], xdot=[... | def reset(new_delta, new_gamma, new_omega):
| global delta, gamma, omega, dt, t, xprev, x, n, alpha
delta = new_delta
gamma = new_gamma
omega = new_omega
dt = 2*np.pi/omega / timesteps_per_period
alpha = delta / (2*dt)
n = 0
t = 0
xprev = 0
x = 0
cds0.data = dict(x=[0], xdot=[0])
cds1.data = dict(x=[], xdot=[])
... | = delta / (2*dt)
beta = 1 / dt**2
n = 0
t = 0
xprev = 0
x = 0
def dV_dx(x):
return x**3 - x
def reset(new_delta, new_gamma, new_omega):
| 64 | 64 | 145 | 12 | 51 | teresafds/bokeh | examples/app/duffing_oscillator.py | Python | reset | reset | 39 | 55 | 39 | 39 | dafa10d117ad4fe5eb3b8898b27ac94b1fefe0a0 | bigcode/the-stack | train |
8a0046eb19c931aca6d8d03e | train | function | def slider_callback(_attr, _old, _new):
reset(delta_slider.value, gamma_slider.value, omega_slider.value)
| def slider_callback(_attr, _old, _new):
| reset(delta_slider.value, gamma_slider.value, omega_slider.value)
| 0
x = 0
cds0.data = dict(x=[0], xdot=[0])
cds1.data = dict(x=[], xdot=[])
line.data_source = cds0
circle.data_source = cds1
def slider_callback(_attr, _old, _new):
| 64 | 64 | 26 | 12 | 51 | teresafds/bokeh | examples/app/duffing_oscillator.py | Python | slider_callback | slider_callback | 57 | 58 | 57 | 57 | 17641d9afe485160fead1dd883c14c266e50a260 | bigcode/the-stack | train |
cc67bb756ecea9ef085e9404 | train | function | def dV_dx(x):
return x**3 - x
| def dV_dx(x):
| return x**3 - x
| 5000
dt = 2*np.pi / (omega*timesteps_per_period)
alpha = delta / (2*dt)
beta = 1 / dt**2
n = 0
t = 0
xprev = 0
x = 0
def dV_dx(x):
| 64 | 64 | 14 | 6 | 57 | teresafds/bokeh | examples/app/duffing_oscillator.py | Python | dV_dx | dV_dx | 36 | 37 | 36 | 36 | 1f5e0d59cfd5322418a1d80af86847900cc41c0d | bigcode/the-stack | train |
a95e207f698bc33e0c5ebc63 | train | class | class CaseReplacer():
cases = ('camel', 'title', 'upper', 'lower')
def __init__(self, argv):
self.parser = argparse.ArgumentParser('./replace.py case')
self.parser.add_argument('-f', '--field', help='Field to search/replace in', required=False)
self.parser.add_argument('-c', '--case', h... | class CaseReplacer():
| cases = ('camel', 'title', 'upper', 'lower')
def __init__(self, argv):
self.parser = argparse.ArgumentParser('./replace.py case')
self.parser.add_argument('-f', '--field', help='Field to search/replace in', required=False)
self.parser.add_argument('-c', '--case', help='Case to use. Vali... | (iter(args.input.readline, ''), delimiter=',')):
if index == 0:
for col in row: column_names[col] = row.index(col)
else:
if args.field:
row[column_names[args.field]] = row[column_names[args.field]].replace(args.search, args.replace)
... | 99 | 99 | 333 | 5 | 94 | tesera/csv-toolkit | replace.py | Python | CaseReplacer | CaseReplacer | 33 | 59 | 33 | 33 | c4deaedccfa0f648e854442828954c91a0f96b95 | bigcode/the-stack | train |
cf4a1ebd4d158f4ceff817c6 | train | function | def main():
command_parser = argparse.ArgumentParser(
description='Replaces text in CSV files',
usage='''./replace.py <command> [<args>]
The commands are:
text
case
''')
command_parser.add_argument('command', help='Subcommand to run')
command = command_parser.parse_args(sys.argv... | def main():
| command_parser = argparse.ArgumentParser(
description='Replaces text in CSV files',
usage='''./replace.py <command> [<args>]
The commands are:
text
case
''')
command_parser.add_argument('command', help='Subcommand to run')
command = command_parser.parse_args(sys.argv[1:2]).comma... | (col)
else:
if args.field:
row[column_names[args.field]] = getattr(row[column_names[args.field]], args.case)()
else:
row = [getattr(cell, args.case)() for cell in row]
writer.writerow(row)
args.output.flush()
def... | 64 | 64 | 102 | 3 | 61 | tesera/csv-toolkit | replace.py | Python | main | main | 61 | 73 | 61 | 61 | 1c92a67267cdc7bb4b398ae97b08361352c4b5f0 | bigcode/the-stack | train |
5eb62748d1574350e77249eb | train | class | class TextReplacer():
def __init__(self,argv):
self.parser = argparse.ArgumentParser('./replace.py text', description='Replace or reformat fields in csv files')
self.parser.add_argument('-s', '--search', help='search criteria', required=True)
self.parser.add_argument('-r', '--replace', help=... | class TextReplacer():
| def __init__(self,argv):
self.parser = argparse.ArgumentParser('./replace.py text', description='Replace or reformat fields in csv files')
self.parser.add_argument('-s', '--search', help='search criteria', required=True)
self.parser.add_argument('-r', '--replace', help='replace criteria', re... | #!/usr/bin/env python
import argparse
import sys
import csv
class TextReplacer():
| 20 | 91 | 306 | 5 | 14 | tesera/csv-toolkit | replace.py | Python | TextReplacer | TextReplacer | 7 | 30 | 7 | 7 | 93ab2c70213a40339a53ff1c74ad4ccc11d7eaf8 | bigcode/the-stack | train |
9fccf18afb8688a691877032 | train | class | class DistributedPartyCogActivity(DistributedPartyTeamActivity):
notify = directNotify.newCategory('DistributedPartyCogActivity')
players = {}
localPlayer = None
view = None
def __init__(self, cr, arenaModel = 'phase_13/models/parties/cogPieArena_model', texture = None):
DistributedPartyTea... | class DistributedPartyCogActivity(DistributedPartyTeamActivity):
| notify = directNotify.newCategory('DistributedPartyCogActivity')
players = {}
localPlayer = None
view = None
def __init__(self, cr, arenaModel = 'phase_13/models/parties/cogPieArena_model', texture = None):
DistributedPartyTeamActivity.__init__(self, cr, PartyGlobals.ActivityIds.PartyCog, s... | from direct.distributed.ClockDelta import globalClockDelta
from pandac.PandaModules import Point3
from toontown.toonbase import TTLocalizer
import PartyGlobals
from DistributedPartyTeamActivity import DistributedPartyTeamActivity
from PartyCogActivity import PartyCogActivity
class DistributedPartyCogActivity(Distribute... | 67 | 256 | 1,683 | 11 | 55 | LittleNed/toontown-stride | toontown/parties/DistributedPartyCogActivity.py | Python | DistributedPartyCogActivity | DistributedPartyCogActivity | 8 | 193 | 8 | 8 | 43c70ddc76290474e8cdf62d7d47f607baea9e20 | bigcode/the-stack | train |
0edc856947d24504f9bf73c2 | train | class | class InstantSendTest(BitcoinGemTestFramework):
def __init__(self):
super().__init__(9, 5, [], fast_dip3_enforcement=True)
# set sender, receiver, isolated nodes
self.isolated_idx = 1
self.receiver_idx = 2
self.sender_idx = 3
def run_test(self):
self.nodes[0].s... | class InstantSendTest(BitcoinGemTestFramework):
| def __init__(self):
super().__init__(9, 5, [], fast_dip3_enforcement=True)
# set sender, receiver, isolated nodes
self.isolated_idx = 1
self.receiver_idx = 2
self.sender_idx = 3
def run_test(self):
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
s... | #!/usr/bin/env python3
# Copyright (c) 2018 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import BitcoinGemTestFramework
from test... | 104 | 256 | 1,030 | 10 | 94 | Penny-Admixture/bitcoingem | qa/rpc-tests/p2p-instantsend.py | Python | InstantSendTest | InstantSendTest | 15 | 118 | 15 | 15 | 6948cb725d9d19493c543ff4f214045b870ab83a | bigcode/the-stack | train |
03fde94f211bcf2849681cc0 | train | class | class NoticiasAdjuntos(models.Model):
adjuntos = models.ForeignKey(Noticias)
titulo = models.CharField(_(u'Titulo'),max_length=250)
archivo = models.FileField(upload_to=get_file_path)
fileDir = 'subirNoticiasAdjuntos/'
def __unicode__(self):
return self.titulo
class Meta:
verb... | class NoticiasAdjuntos(models.Model):
| adjuntos = models.ForeignKey(Noticias)
titulo = models.CharField(_(u'Titulo'),max_length=250)
archivo = models.FileField(upload_to=get_file_path)
fileDir = 'subirNoticiasAdjuntos/'
def __unicode__(self):
return self.titulo
class Meta:
verbose_name=_(u'Subir adjuntos')
... | 'subirNoticiasAudios/'
def __unicode__(self):
return self.titulo
class Meta:
verbose_name=_(u'Subir audio')
verbose_name_plural=_(u'Subir audios')
ordering = ('-titulo', )
class NoticiasAdjuntos(models.Model):
| 64 | 64 | 108 | 7 | 57 | shiminasai/plataforma_FADCANIC | cambiaahora/noticias/models.py | Python | NoticiasAdjuntos | NoticiasAdjuntos | 66 | 79 | 66 | 66 | 5a153df48f82309b920b99f70145c6357cb2990a | bigcode/the-stack | train |
ec0232531df197cd16784e21 | train | class | class Noticias(models.Model):
titulo = models.CharField(_(u'Titulo'),max_length=450)
slug = models.SlugField(editable=False, max_length=450)
fecha = models.DateField(_(u'Fecha'))
foto = ImageField(_(u'Foto principal'), upload_to=get_file_path, blank=True, null=True)
url = models.URLField(_(u'url del... | class Noticias(models.Model):
| titulo = models.CharField(_(u'Titulo'),max_length=450)
slug = models.SlugField(editable=False, max_length=450)
fecha = models.DateField(_(u'Fecha'))
foto = ImageField(_(u'Foto principal'), upload_to=get_file_path, blank=True, null=True)
url = models.URLField(_(u'url del video como portada'), blank=T... | (1, _(u'Borrador')),
(2, _(u'Aprobado')),
)
CHOICE_IDIOMA = (
(1, _(u'Español')),
(2, _(u'English')),
)
class Categoria(models.Model):
nombre = models.CharField(max_length=250)
... | 85 | 85 | 284 | 5 | 79 | shiminasai/plataforma_FADCANIC | cambiaahora/noticias/models.py | Python | Noticias | Noticias | 25 | 49 | 25 | 25 | b3ea21a66a5237017d59cac8a4fe4b27e5276030 | bigcode/the-stack | train |
9e9ad7faae76d992c44ec005 | train | class | class NoticiasAudios(models.Model):
audios = models.ForeignKey(Noticias)
titulo = models.CharField(_(u'Titulo'),max_length=250)
audio = models.FileField(_(u'Audio'),)
fileDir = 'subirNoticiasAudios/'
def __unicode__(self):
return self.titulo
class Meta:
verbose_name=_(u'Subir ... | class NoticiasAudios(models.Model):
| audios = models.ForeignKey(Noticias)
titulo = models.CharField(_(u'Titulo'),max_length=250)
audio = models.FileField(_(u'Audio'),)
fileDir = 'subirNoticiasAudios/'
def __unicode__(self):
return self.titulo
class Meta:
verbose_name=_(u'Subir audio')
verbose_name_plural=... | super(Noticias, self).save(*args, **kwargs)
def __unicode__(self):
return u'%s' % (self.titulo)
class Meta:
verbose_name= _(u'Noticia')
verbose_name_plural= _(u'Noticias')
class NoticiasAudios(models.Model):
| 64 | 64 | 108 | 7 | 57 | shiminasai/plataforma_FADCANIC | cambiaahora/noticias/models.py | Python | NoticiasAudios | NoticiasAudios | 51 | 64 | 51 | 51 | e20df3eee4a3a3cf5b73adfb90ace350fb6ae99d | bigcode/the-stack | train |
3a8c279973b3222a864b744c | train | class | class Categoria(models.Model):
nombre = models.CharField(max_length=250)
def __unicode__(self):
return self.nombre
| class Categoria(models.Model):
| nombre = models.CharField(max_length=250)
def __unicode__(self):
return self.nombre
| CHOICE_APROBACION = (
(1, _(u'Borrador')),
(2, _(u'Aprobado')),
)
CHOICE_IDIOMA = (
(1, _(u'Español')),
(2, _(u'English')),
)
class Categoria(models.Model):
| 64 | 64 | 28 | 5 | 59 | shiminasai/plataforma_FADCANIC | cambiaahora/noticias/models.py | Python | Categoria | Categoria | 19 | 23 | 19 | 19 | e58ef163e50895744a78977e8d6f6de7d57346b3 | bigcode/the-stack | train |
d82f833224fcc3b5d9f18707 | train | class | class AppDynamicsAgent(BaseWatcher):
def __init__(self, cluster_id: str, load_template):
self.dest_path = os.environ.get('WATCHER_APPDYNAMICS_DEST_PATH')
if not self.dest_path:
raise RuntimeError('AppDyanmics watcher agent initialization failed. Env variable '
... | class AppDynamicsAgent(BaseWatcher):
| def __init__(self, cluster_id: str, load_template):
self.dest_path = os.environ.get('WATCHER_APPDYNAMICS_DEST_PATH')
if not self.dest_path:
raise RuntimeError('AppDyanmics watcher agent initialization failed. Env variable '
'WATCHER_APPDYNAMICS_DEST_PATH m... | """
Appdynamics watcher agent for providing job file templates and variables required to ship logs to
appdynamics controller.
"""
import os
import logging
from kube_log_watcher.agents.base import BaseWatcher
TPL_NAME = 'appdynamics.job.jinja2'
logger = logging.getLogger('kube_log_watcher')
class AppDynamicsAgent(Bas... | 74 | 154 | 515 | 7 | 67 | dryewo/kubernetes-log-watcher | kube_log_watcher/agents/appdynamics.py | Python | AppDynamicsAgent | AppDynamicsAgent | 15 | 85 | 15 | 15 | cf9886767c9d7a80f577ad1a447ff968f32a03ef | bigcode/the-stack | train |
f94b2941e25aa121b5fcda21 | train | class | class Verbosity(IntEnum):
"""regular lvls from `logging` & `machine` for machine-readable output only"""
machine = 100
silent = logging.CRITICAL
minimal = logging.WARNING
user = logging.INFO
debug = logging.DEBUG
unset = logging.NOTSET
| class Verbosity(IntEnum):
| """regular lvls from `logging` & `machine` for machine-readable output only"""
machine = 100
silent = logging.CRITICAL
minimal = logging.WARNING
user = logging.INFO
debug = logging.DEBUG
unset = logging.NOTSET
| import logging
import os
import tempfile
from enum import IntEnum
class Verbosity(IntEnum):
| 21 | 64 | 63 | 6 | 14 | sgued/pynitrokey | pynitrokey/confconsts.py | Python | Verbosity | Verbosity | 7 | 15 | 7 | 7 | 04aa7d099381279dfc988ea8e22fc2ef8e74c053 | bigcode/the-stack | train |
099c83303ab2d680056cf9c8 | train | class | class ArgumentsProcessorExceptionArgumentsAreInvalid(ArgumentsProcessorException):
def __init__(self):
ArgumentsProcessorException.__init__(self, 'supplied_arguments are not valid in reference to expected_arguments') | class ArgumentsProcessorExceptionArgumentsAreInvalid(ArgumentsProcessorException):
| def __init__(self):
ArgumentsProcessorException.__init__(self, 'supplied_arguments are not valid in reference to expected_arguments') | , 'error')
Exception.__init__(self, msg)
class ArgumentsProcessorExceptionArgumentsAreNone(ArgumentsProcessorException):
def __init__(self):
ArgumentsProcessorException.__init__(self, 'Arguments supplied to Arguments Processor may not be None')
class ArgumentsProcessorExceptionArgumentsAreInvalid... | 64 | 64 | 41 | 12 | 52 | excellentingenuity/argumentsprocessor | argumentsprocessor/argumentsprocessorexception.py | Python | ArgumentsProcessorExceptionArgumentsAreInvalid | ArgumentsProcessorExceptionArgumentsAreInvalid | 22 | 24 | 22 | 22 | 6d47b88779651eb150e6d22ccd59fa3136eb7169 | bigcode/the-stack | train |
73be8e9123a733202b692573 | train | class | class ArgumentsProcessorException(Exception):
def __init__(self, msg):
rollbar.init(rollbar_cfg.token, rollbar_cfg.environment) # access_token, environment
rollbar.report_message(msg, 'error')
Exception.__init__(self, msg)
| class ArgumentsProcessorException(Exception):
| def __init__(self, msg):
rollbar.init(rollbar_cfg.token, rollbar_cfg.environment) # access_token, environment
rollbar.report_message(msg, 'error')
Exception.__init__(self, msg)
| #!/usr/bin/env python
__author__ = 'James Johnson'
import rollbar
import argumentsprocessor.rollbar_cfg as rollbar_cfg
class ArgumentsProcessorException(Exception):
| 35 | 64 | 56 | 6 | 28 | excellentingenuity/argumentsprocessor | argumentsprocessor/argumentsprocessorexception.py | Python | ArgumentsProcessorException | ArgumentsProcessorException | 9 | 13 | 9 | 9 | 2652e6a4ffbe5cd594104d4f66880ed6ad36cc1f | bigcode/the-stack | train |
e5dcec89e90e2100a99dc1df | train | class | class ArgumentsProcessorExceptionArgumentsAreNone(ArgumentsProcessorException):
def __init__(self):
ArgumentsProcessorException.__init__(self, 'Arguments supplied to Arguments Processor may not be None')
| class ArgumentsProcessorExceptionArgumentsAreNone(ArgumentsProcessorException):
| def __init__(self):
ArgumentsProcessorException.__init__(self, 'Arguments supplied to Arguments Processor may not be None')
| (Exception):
def __init__(self, msg):
rollbar.init(rollbar_cfg.token, rollbar_cfg.environment) # access_token, environment
rollbar.report_message(msg, 'error')
Exception.__init__(self, msg)
class ArgumentsProcessorExceptionArgumentsAreNone(ArgumentsProcessorException):
| 64 | 64 | 39 | 12 | 52 | excellentingenuity/argumentsprocessor | argumentsprocessor/argumentsprocessorexception.py | Python | ArgumentsProcessorExceptionArgumentsAreNone | ArgumentsProcessorExceptionArgumentsAreNone | 16 | 19 | 16 | 17 | ddaef61a11b2b4cf69b91ae50636ae3ce82b3267 | bigcode/the-stack | train |
ed52751c0e9d997d410b2342 | train | class | class Btn(Tk):
def __init__(self, tex, g_row, g_col):
super().__init__()
self.tex = tex
self.g_row = g_row
self.g_col = g_col
Button(self, text=tex, height=5, width=7, command=lambda: logic.logic1.display_sign_on_btn(tex)).grid(
row=g_row, column=g_col)
| class Btn(Tk):
| def __init__(self, tex, g_row, g_col):
super().__init__()
self.tex = tex
self.g_row = g_row
self.g_col = g_col
Button(self, text=tex, height=5, width=7, command=lambda: logic.logic1.display_sign_on_btn(tex)).grid(
row=g_row, column=g_col)
| import logic
from tkinter import *
class Btn(Tk):
| 12 | 64 | 86 | 5 | 7 | heEXDe/tic-tac-toe | GUI.py | Python | Btn | Btn | 5 | 13 | 5 | 6 | 1346594b82bd52442fa3dd09997c820cd876456f | bigcode/the-stack | train |
fcd4ff186d26057b12e5c716 | train | class | class App(Tk):
def __init__(self, you_play_as, win_or_loose, *args, **kwargs):
super().__init__()
self.title('Tic-tac-toe')
self.resizable(0, 0)
# self.you_play_as = you_play_as
# self.win_or_loose = win_or_loose
self.lst_points = [1, 1, 1, 1, 1, 1, 1, 1, 1]
... | class App(Tk):
| def __init__(self, you_play_as, win_or_loose, *args, **kwargs):
super().__init__()
self.title('Tic-tac-toe')
self.resizable(0, 0)
# self.you_play_as = you_play_as
# self.win_or_loose = win_or_loose
self.lst_points = [1, 1, 1, 1, 1, 1, 1, 1, 1]
self.btn1 = Butt... | import logic
from tkinter import *
class Btn(Tk):
def __init__(self, tex, g_row, g_col):
super().__init__()
self.tex = tex
self.g_row = g_row
self.g_col = g_col
Button(self, text=tex, height=5, width=7, command=lambda: logic.logic1.display_sign_on_btn(tex)).grid(
... | 98 | 212 | 708 | 5 | 93 | heEXDe/tic-tac-toe | GUI.py | Python | App | App | 16 | 59 | 16 | 17 | 62c54dc2d1b00e1205d00ae1508d6e5998bb55a6 | bigcode/the-stack | train |
26e25ada1ae9d1e20e4ba690 | train | class | class TestCallback(OsfTestCase):
@mock.patch('website.oauth.views.osf_oauth_callback')
def test_web_callback(self, osf_callback_mock):
with self.app.app.test_request_context(
'/oauth/connect/googledrive/',
query_string='state=googledrivestate1'):
session.dat... | class TestCallback(OsfTestCase):
@mock.patch('website.oauth.views.osf_oauth_callback')
| def test_web_callback(self, osf_callback_mock):
with self.app.app.test_request_context(
'/oauth/connect/googledrive/',
query_string='state=googledrivestate1'):
session.data = {'oauth_states': {'googledrive': {'state': 'googledrivestate1'}}}
session.sa... | .objects.get(id=region.id)
# Token in waterbutler credentials after it is updated
assert_equal(
external_account.oauth_key,
updated_region.waterbutler_credentials['storage']['token']
)
class TestCallback(OsfTestCase):
@mock.patch('website.oauth.views.osf_oauth_callb... | 67 | 67 | 224 | 23 | 44 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | TestCallback | TestCallback | 1,458 | 1,481 | 1,458 | 1,460 | 3f0019d9170d32956a1e5751610202e4bf58f19a | bigcode/the-stack | train |
e3980e2a494f540c0ed4744a | train | class | class MockOAuth1Provider(ExternalProvider):
_oauth_version = OAUTH1
name = 'Mock OAuth 1.0a Provider'
short_name = 'mock1a'
client_id = 'mock1a_client_id'
client_secret = 'mock1a_client_secret'
auth_url_base = 'http://mock1a.com/auth'
request_token_url = 'http://mock1a.com/request'
cal... | class MockOAuth1Provider(ExternalProvider):
| _oauth_version = OAUTH1
name = 'Mock OAuth 1.0a Provider'
short_name = 'mock1a'
client_id = 'mock1a_client_id'
client_secret = 'mock1a_client_secret'
auth_url_base = 'http://mock1a.com/auth'
request_token_url = 'http://mock1a.com/request'
callback_url = 'http://mock1a.com/callback'
... |
from admin.rdm_custom_storage_location import views as customstoragelocation_update
SILENT_LOGGERS = ['oauthlib', 'requests_oauthlib']
for logger in SILENT_LOGGERS:
logging.getLogger(logger).setLevel(logging.ERROR)
class MockOAuth1Provider(ExternalProvider):
| 64 | 64 | 127 | 9 | 55 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | MockOAuth1Provider | MockOAuth1Provider | 47 | 62 | 47 | 47 | 76dad115004d1d0be24a0c8516802b98ce124f72 | bigcode/the-stack | train |
8cb0c5a9d0a10cdd51a724dd | train | class | class TestExternalProviderOAuth1(OsfTestCase):
# Test functionality of the ExternalProvider class, for OAuth 1.0a
def setUp(self):
super(TestExternalProviderOAuth1, self).setUp()
self.user = UserFactory()
self.provider = MockOAuth1Provider()
@responses.activate
def test_start_f... | class TestExternalProviderOAuth1(OsfTestCase):
# Test functionality of the ExternalProvider class, for OAuth 1.0a
| def setUp(self):
super(TestExternalProviderOAuth1, self).setUp()
self.user = UserFactory()
self.provider = MockOAuth1Provider()
@responses.activate
def test_start_flow(self):
# Request temporary credentials from provider, provide auth redirect
responses.add(
... | # Disconnect an account connected to multiple users from one user
external_account = ExternalAccountFactory(
provider='mock2',
provider_id='mock_provider_id',
provider_name='Mock Provider',
)
self.user.external_accounts.add(external_account)
self.user... | 256 | 256 | 994 | 30 | 226 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | TestExternalProviderOAuth1 | TestExternalProviderOAuth1 | 204 | 341 | 204 | 206 | 85303613753400a64b40f35cf6718d4eed8f79f8 | bigcode/the-stack | train |
28bb13675fd4f8512c7e5ab2 | train | function | def _prepare_mock_500_error():
responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body='{"error": "not found"}',
status=503,
content_type='application/json',
)
)
| def _prepare_mock_500_error():
| responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body='{"error": "not found"}',
status=503,
content_type='application/json',
)
)
| + expires_in,
'expires_in': expires_in,
'refresh_token': 'mock_refresh_token',
'scope': ['all'],
'token_type': 'bearer',
}),
status=200,
content_type='application/json',
)
)
def _prepare_mock_500_error():
| 64 | 64 | 57 | 8 | 56 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | _prepare_mock_500_error | _prepare_mock_500_error | 84 | 93 | 84 | 84 | 3e63e3144cb353bd484cb38b05a95a16ff37f082 | bigcode/the-stack | train |
6c0bde03e6188924d8747836 | train | function | def _prepare_mock_oauth2_handshake_response(expires_in=3600):
responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body=json.dumps({
'access_token': 'mock_access_token',
'expires_at': time.time() + expires_in,
... | def _prepare_mock_oauth2_handshake_response(expires_in=3600):
| responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body=json.dumps({
'access_token': 'mock_access_token',
'expires_at': time.time() + expires_in,
'expires_in': expires_in,
'refre... | = 'http://mock1a.com/request'
callback_url = 'http://mock1a.com/callback'
def handle_callback(self, response):
return {
'provider_id': 'mock_provider_id'
}
def _prepare_mock_oauth2_handshake_response(expires_in=3600):
| 64 | 64 | 118 | 17 | 47 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | _prepare_mock_oauth2_handshake_response | _prepare_mock_oauth2_handshake_response | 65 | 82 | 65 | 66 | 632afdb39efd1fe790d8f74a06805c8846ecc16f | bigcode/the-stack | train |
73b3307832c0b289c0a3680e | train | function | def _prepare_mock_401_error():
responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body='{"error": "user denied access"}',
status=401,
content_type='application/json',
)
)
| def _prepare_mock_401_error():
| responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body='{"error": "user denied access"}',
status=401,
content_type='application/json',
)
)
| _prepare_mock_500_error():
responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body='{"error": "not found"}',
status=503,
content_type='application/json',
)
)
def _prepare_mock_401_error():
| 64 | 64 | 58 | 8 | 56 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | _prepare_mock_401_error | _prepare_mock_401_error | 95 | 104 | 95 | 95 | 4befb350fcbff26d3223ee3e64813b6965433ea1 | bigcode/the-stack | train |
c42f6be6fb9760ac89650430 | train | class | class TestExternalAccount(OsfTestCase):
# Test the ExternalAccount object and associated views.
#
# Functionality not specific to the OAuth version used by the
# ExternalProvider should go here.
def setUp(self):
super(TestExternalAccount, self).setUp()
self.user = AuthUserFactory()
... | class TestExternalAccount(OsfTestCase):
# Test the ExternalAccount object and associated views.
#
# Functionality not specific to the OAuth version used by the
# ExternalProvider should go here.
| def setUp(self):
super(TestExternalAccount, self).setUp()
self.user = AuthUserFactory()
self.provider = MockOAuth2Provider()
def test_disconnect(self):
# Disconnect an external account from a user
external_account = ExternalAccountFactory(
provider='mock2',
... | )
def _prepare_mock_500_error():
responses.add(
responses.Response(
responses.POST,
'https://mock2.com/callback',
body='{"error": "not found"}',
status=503,
content_type='application/json',
)
)
def _prepare_mock_401_error():
r... | 162 | 162 | 541 | 45 | 117 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | TestExternalAccount | TestExternalAccount | 106 | 201 | 106 | 111 | b236a46cc37f78861d9b4fab3a10ed16734b21ac | bigcode/the-stack | train |
52d9db0e12e59e8d5bf372c1 | train | class | class TestExternalProviderOAuth2(OsfTestCase):
# Test functionality of the ExternalProvider class, for OAuth 2.0
def setUp(self):
super(TestExternalProviderOAuth2, self).setUp()
self.user = UserFactory()
self.provider = MockOAuth2Provider()
def test_oauth_version_default(self):
... | class TestExternalProviderOAuth2(OsfTestCase):
# Test functionality of the ExternalProvider class, for OAuth 2.0
| def setUp(self):
super(TestExternalProviderOAuth2, self).setUp()
self.user = UserFactory()
self.provider = MockOAuth2Provider()
def test_oauth_version_default(self):
# OAuth 2.0 is the default version
assert_is(self.provider._oauth_version, OAUTH2)
def test_start_fl... | responses.Response(
responses.POST,
'http://mock1a.com/callback',
body='oauth_token=perm_token'
'&oauth_token_secret=perm_secret'
'&oauth_callback_confirmed=true',
)
)
user = UserFactory()
... | 256 | 256 | 4,212 | 29 | 227 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | TestExternalProviderOAuth2 | TestExternalProviderOAuth2 | 344 | 919 | 344 | 346 | 72b958cc389eb0a29ce5a725c06796a20f1a38e6 | bigcode/the-stack | train |
7e770f11acfa1ad90c688433 | train | class | class TestExternalProviderOAuth2GoogleDrive(OsfTestCase):
# Test functionality of the ExternalProvider class, for OAuth 2.0
def setUp(self):
super(TestExternalProviderOAuth2GoogleDrive, self).setUp()
self.user = UserFactory()
self.provider = MockOAuth2Provider()
self.provider.sh... | class TestExternalProviderOAuth2GoogleDrive(OsfTestCase):
# Test functionality of the ExternalProvider class, for OAuth 2.0
| def setUp(self):
super(TestExternalProviderOAuth2GoogleDrive, self).setUp()
self.user = UserFactory()
self.provider = MockOAuth2Provider()
self.provider.short_name = 'googledrive'
def tearDown(self):
super(TestExternalProviderOAuth2GoogleDrive, self).tearDown()
def ... | ,
body=json.dumps({
'err': 'Should not be hit'
}),
status=500
)
)
ret = self.provider.refresh_oauth_key(force=False)
assert_false(ret)
@responses.activate
def test_force_refresh_with_expired_credentials(sel... | 256 | 256 | 3,847 | 31 | 225 | yuanyuan-deng/RDM-osf.io | tests/test_oauth.py | Python | TestExternalProviderOAuth2GoogleDrive | TestExternalProviderOAuth2GoogleDrive | 921 | 1,455 | 921 | 923 | 8d5f789d0ec50ca1aa517fcced6a749e92c8fbcf | bigcode/the-stack | train |
e5c3a9d127a2f01e44095e2b | train | class | class MyHashSet:
def __init__(self):
self.size = 10000
self.buckets = [[] for _ in range(self.size)]
def add(self, key):
bucket, idx = self._index(key)
if idx >= 0:
return
bucket.append(key)
def remove(self, key):
bucket, idx = self._index(key)
... | class MyHashSet:
| def __init__(self):
self.size = 10000
self.buckets = [[] for _ in range(self.size)]
def add(self, key):
bucket, idx = self._index(key)
if idx >= 0:
return
bucket.append(key)
def remove(self, key):
bucket, idx = self._index(key)
if idx < 0... | class MyHashSet:
| 5 | 64 | 188 | 5 | 0 | zdyxry/LeetCode | hash_table/0705_design_hashset/0705_design_hashset.py | Python | MyHashSet | MyHashSet | 1 | 31 | 1 | 1 | fb72d1df2b67277ca6042327a7b70d8b7b1bd740 | bigcode/the-stack | train |
81b4d8f036a0ab6fb463888c | train | function | def iqr_threshold_method(scores, margin):
q1 = np.percentile(scores, 25, interpolation='midpoint')
q3 = np.percentile(scores, 75, interpolation='midpoint')
iqr = q3-q1
lower_range = q1 - (1.5 * iqr)
upper_range = q3 + (1.5 * iqr)
lower_range = lower_range - margin
upper_range = upper_range +... | def iqr_threshold_method(scores, margin):
| q1 = np.percentile(scores, 25, interpolation='midpoint')
q3 = np.percentile(scores, 75, interpolation='midpoint')
iqr = q3-q1
lower_range = q1 - (1.5 * iqr)
upper_range = q3 + (1.5 * iqr)
lower_range = lower_range - margin
upper_range = upper_range + margin
return lower_range, upper_rang... | only outlier_score is calculated
import matplotlib.pyplot as plt
import numpy as np
import sklearn.datasets as sk_data
import sklearn.neighbors as neighbors
import sys
import statistics
np.set_printoptions(suppress=True, precision=4)
# In[2]:
def iqr_threshold_method(scores, margin):
| 64 | 64 | 108 | 9 | 55 | amit22666/package-outlier | testing methods/testing_based_knn.py | Python | iqr_threshold_method | iqr_threshold_method | 27 | 35 | 27 | 27 | 8b9c869636ce0019e2299fac94c39367ebcb9889 | bigcode/the-stack | train |
995adef555b8002a384185be | train | function | def max_knn_outlier_scores(
obs,
n_neighbors=1,
margin = 0
):
"""Returns numpy array with data points labelled as outliers
Parameters
----------
obs:numpy array like data_points
algorithm : {'n_neighbors'},
Algorithm used to capture the idea of simil... | def max_knn_outlier_scores(
obs,
n_neighbors=1,
margin = 0
):
| """Returns numpy array with data points labelled as outliers
Parameters
----------
obs:numpy array like data_points
algorithm : {'n_neighbors'},
Algorithm used to capture the idea of similarity
n_neighbours: int , default=1
Your chosen number of neig... | -q1
lower_range = q1 - (1.5 * iqr)
upper_range = q3 + (1.5 * iqr)
lower_range = lower_range - margin
upper_range = upper_range + margin
return lower_range, upper_range
# In[3]:
def max_knn_outlier_scores(
obs,
n_neighbors=1,
margin = 0
):
| 90 | 90 | 303 | 26 | 64 | amit22666/package-outlier | testing methods/testing_based_knn.py | Python | max_knn_outlier_scores | max_knn_outlier_scores | 41 | 95 | 41 | 45 | cba25e44a7ff1adce29812ec3a0d9858930e02e5 | bigcode/the-stack | train |
920107aa948872fb7f91bc3b | train | class | class PlayerAttributeEyesWidth(PlayerAttribute):
@classmethod
def att_class_name(cls):
return "Eyes Width"
@classmethod
def att_class_type(cls):
return PlayerAttributeTypes.Appearance
def get_raw_value(self):
return self.parent.get_value()
def get_value(self):
... | class PlayerAttributeEyesWidth(PlayerAttribute):
@classmethod
| def att_class_name(cls):
return "Eyes Width"
@classmethod
def att_class_type(cls):
return PlayerAttributeTypes.Appearance
def get_raw_value(self):
return self.parent.get_value()
def get_value(self):
return self.parent.get_value()
def get_label(self):
"... | from editor.attributes.player.player_attribute import (
PlayerAttribute,
PlayerAttributeTypes,
)
class PlayerAttributeEyesWidth(PlayerAttribute):
@classmethod
| 30 | 87 | 292 | 12 | 18 | PeterC10/COFPES-OF-Editor-6 | editor/attributes/player/player_attribute_eyes_width.py | Python | PlayerAttributeEyesWidth | PlayerAttributeEyesWidth | 7 | 52 | 7 | 8 | 64fe0166fc39ec46dc096a13fb148cc722b1ea2d | bigcode/the-stack | train |
544eb2362c98010281f3de8c | train | class | class TransactionViewSet(viewsets.ModelViewSet):
'''
API endpoint that allows Transactions to be viewed or edited.
'''
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
| class TransactionViewSet(viewsets.ModelViewSet):
| '''
API endpoint that allows Transactions to be viewed or edited.
'''
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
| /api/' to view the available API options.")
class SkuViewSet(viewsets.ModelViewSet):
'''
API endpoint that allows Skus to be viewed or edited.
'''
queryset = Sku.objects.all()
serializer_class = SkuSerializer
class TransactionViewSet(viewsets.ModelViewSet):
| 64 | 64 | 40 | 10 | 53 | mwidman/sku-it | backend/inventory/views.py | Python | TransactionViewSet | TransactionViewSet | 20 | 25 | 20 | 20 | dd21fe7189705f74f214032800324c5c566a7a90 | bigcode/the-stack | train |
61efbd9c6929f050988e9d7f | train | function | def index(request):
return HttpResponse("Please navigate to '/inventory/api/' to view the available API options.")
| def index(request):
| return HttpResponse("Please navigate to '/inventory/api/' to view the available API options.")
| from django.http import HttpResponse
from rest_framework import viewsets
from inventory.models import Sku, Transaction
from inventory.serializers import SkuSerializer, TransactionSerializer
def index(request):
| 39 | 64 | 23 | 4 | 34 | mwidman/sku-it | backend/inventory/views.py | Python | index | index | 8 | 9 | 8 | 8 | 8e7689f1b0bb403fc07ef58cc8da93c0ddde9cb6 | bigcode/the-stack | train |
bfc19d5f2a0b4da1e5aba6cf | train | class | class SkuViewSet(viewsets.ModelViewSet):
'''
API endpoint that allows Skus to be viewed or edited.
'''
queryset = Sku.objects.all()
serializer_class = SkuSerializer
| class SkuViewSet(viewsets.ModelViewSet):
| '''
API endpoint that allows Skus to be viewed or edited.
'''
queryset = Sku.objects.all()
serializer_class = SkuSerializer
|
from rest_framework import viewsets
from inventory.models import Sku, Transaction
from inventory.serializers import SkuSerializer, TransactionSerializer
def index(request):
return HttpResponse("Please navigate to '/inventory/api/' to view the available API options.")
class SkuViewSet(viewsets.ModelViewSet):
| 63 | 64 | 44 | 11 | 52 | mwidman/sku-it | backend/inventory/views.py | Python | SkuViewSet | SkuViewSet | 12 | 17 | 12 | 12 | 428dd93b9f2cfeed4de6efd2c22878bbc33c91ae | bigcode/the-stack | train |
36a1754ff33e776f7b7ebb4b | train | function | async def client(client: CompanionClient) -> None:
await client.stub.clear_keychain(ClearKeychainRequest())
| async def client(client: CompanionClient) -> None:
| await client.stub.clear_keychain(ClearKeychainRequest())
| #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from idb.grpc.idb_pb2 import ClearKeychainRequest
from idb.grpc.types import CompanionClient
async def client(client: CompanionClient) -> None:
| 58 | 64 | 24 | 11 | 46 | CoverGo/idb | idb/ipc/clear_keychain.py | Python | client | client | 8 | 9 | 8 | 8 | 4fd78ef1288f0d18a4a4c5d9a5cc48631ba84737 | bigcode/the-stack | train |
10a41bc93ecdffd0b756a2fe | train | class | class LegislationDatabase(base.PyCanliiBase):
"""
A database of CanLII Legislation. This object is both indexable and iterable.
Attributes:
:name: A string representing the name of this LegislationDatabase
:type: An instance of the LegislationType enum indicating what kind of Legislation th... | class LegislationDatabase(base.PyCanliiBase):
| """
A database of CanLII Legislation. This object is both indexable and iterable.
Attributes:
:name: A string representing the name of this LegislationDatabase
:type: An instance of the LegislationType enum indicating what kind of Legislation this LegislationDatabasecontains
:id: A ... | import pycanlii.pycanliibase as base
import pycanlii.enums as enums
import requests
class LegislationDatabase(base.PyCanliiBase):
| 36 | 145 | 486 | 12 | 23 | sherlocke/pycanlii | pycanlii/legislation.py | Python | LegislationDatabase | LegislationDatabase | 5 | 52 | 5 | 5 | 980be8d15241f9d809db248a41a2398faaa95d50 | bigcode/the-stack | train |
eb6c3a827ee072026be21796 | train | class | class Legislation(base.PyCanliiBase):
"""
An object representing Legislation on CanLII
Attributes:
:databaseId: A string representing the databaseId of this legislation
:legislationId: A string representing the legislationId of this legislation
:title: A string representing the titl... | class Legislation(base.PyCanliiBase):
| """
An object representing Legislation on CanLII
Attributes:
:databaseId: A string representing the databaseId of this legislation
:legislationId: A string representing the legislationId of this legislation
:title: A string representing the title of this legislation
:content... | ")
self.id = data["databaseId"]
# still need to add jurisdiction although for basic functionality, strictly speaking, not required
self.jurisdiction = enums.Jurisdiction[data['jurisdiction']]
self._legislation = []
self._populated = False
def _getLegislation(self):
... | 216 | 216 | 723 | 11 | 205 | sherlocke/pycanlii | pycanlii/legislation.py | Python | Legislation | Legislation | 55 | 149 | 55 | 55 | 5c3c54aa01d0a92281f7daf46ffcc90b87846301 | bigcode/the-stack | train |
fdacbecb611bca4f6e4fee35 | train | function | def row_process( tweaker, row ) :
resource = tweaker.get_resource_from_resource_id( row[id_name] )
if resource:
tweaker.update_resource( resource['resource_id'], {
'resource_url' : row['Resource URL']
})
else :
print( "not found" )
| def row_process( tweaker, row ) :
| resource = tweaker.get_resource_from_resource_id( row[id_name] )
if resource:
tweaker.update_resource( resource['resource_id'], {
'resource_url' : row['Resource URL']
})
else :
print( "not found" )
|
csv_file = "resources/Wrong_URLs_to_replace_2019.3.9.a.csv"
id_name = "Resource ID"
skip_first_data_row = False
debugging = True
restrict = 5 # use 0 to restrict none.
def row_process( tweaker, row ) :
| 64 | 64 | 66 | 10 | 54 | culturesofknowledge/site-editor | emlo-edit-php-helper/tweaker/tweak_resource-url.py | Python | row_process | row_process | 14 | 24 | 14 | 15 | 1d8346985e11444eb4fca678ee3eaa5023cc6659 | bigcode/the-stack | train |
33a375d5ce5e06e91567b852 | train | function | def main() :
tweaker = DatabaseTweaker.tweaker_from_connection( config["dbname"], config["host"], config["port"], config["user"], config["password"] )
tweaker.set_debug( debugging )
if debugging:
print( "Debug ON so no commit" )
commit = False
else :
commit = do_commit()
csv_rows = tweaker.get_csv_data( c... | def main() :
| tweaker = DatabaseTweaker.tweaker_from_connection( config["dbname"], config["host"], config["port"], config["user"], config["password"] )
tweaker.set_debug( debugging )
if debugging:
print( "Debug ON so no commit" )
commit = False
else :
commit = do_commit()
csv_rows = tweaker.get_csv_data( csv_file )
if... | , row ) :
resource = tweaker.get_resource_from_resource_id( row[id_name] )
if resource:
tweaker.update_resource( resource['resource_id'], {
'resource_url' : row['Resource URL']
})
else :
print( "not found" )
def main() :
| 64 | 64 | 208 | 4 | 60 | culturesofknowledge/site-editor | emlo-edit-php-helper/tweaker/tweak_resource-url.py | Python | main | main | 27 | 61 | 27 | 28 | d9dbdf098e5c4f466649416d675f1c2a187b7a08 | bigcode/the-stack | train |
6283c4ba2aef64654690c3f0 | train | function | def do_commit() :
commit = ( raw_input("Commit changes to database (y/n): ") == "y")
if commit:
print( "COMMITTING changes to database." )
else:
print( "NOT committing changes to database." )
return commit
| def do_commit() :
| commit = ( raw_input("Commit changes to database (y/n): ") == "y")
if commit:
print( "COMMITTING changes to database." )
else:
print( "NOT committing changes to database." )
return commit
| (countdown) + " of " + str(count), ":", csv_row[id_name] )
row_process( tweaker, csv_row )
countdown -= 1
print()
tweaker.print_audit()
tweaker.commit_changes(commit)
print( "Fini" )
def do_commit() :
| 64 | 64 | 56 | 5 | 59 | culturesofknowledge/site-editor | emlo-edit-php-helper/tweaker/tweak_resource-url.py | Python | do_commit | do_commit | 64 | 72 | 64 | 65 | ab027bbcf4ef1f26ca53ff1930ebbbadd3d383fb | bigcode/the-stack | train |
5ed03f1403b053dd420a292c | train | function | def compare_uuid(uuid_to_check, uuid_reference):
name, uuid = uuid_to_check
name_ref, uuid_ref = uuid_reference
if not check_uuid(uuid):
raise CheckException("Invalid {} uuid found : {}".format(
name, uuid))
if uuid != uuid_ref:
raise CheckException("Uuid {} ({}) not equal t... | def compare_uuid(uuid_to_check, uuid_reference):
| name, uuid = uuid_to_check
name_ref, uuid_ref = uuid_reference
if not check_uuid(uuid):
raise CheckException("Invalid {} uuid found : {}".format(
name, uuid))
if uuid != uuid_ref:
raise CheckException("Uuid {} ({}) not equal to {} ({})".format(
name, uuid, name_r... | SD validation.
parse_date = parser.parse(date)
now_date = datetime.now().replace(tzinfo=parse_date.tzinfo)
if parse_date > now_date:
raise CheckException("IssueDate is post dated : {}".format(
parse_date))
def compare_uuid(uuid_to_check, uuid_reference):
| 64 | 64 | 90 | 10 | 54 | Kariboupseudo/ClairMeta | clairmeta/dcp_check_utils.py | Python | compare_uuid | compare_uuid | 53 | 62 | 53 | 53 | 4fac2d67a3c581b3bb6b9f85619242e828b80adb | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.