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
753f0ba7ab43340e48de1123
train
function
@paper.route("/paper") def paper_index(): data = { "title": "Prediksi Tema Paper", "selected": "paper" } return render_template("paper/index.html", data=data)
@paper.route("/paper") def paper_index():
data = { "title": "Prediksi Tema Paper", "selected": "paper" } return render_template("paper/index.html", data=data)
personality_logic import * from flask import Blueprint, render_template, jsonify, request from paper_topic_predictions import * from googletrans import Translator import numpy as np # learn from transformers import pipeline paper = Blueprint('paper',__name__) # paper page @paper.route("/paper") def paper_index():
64
64
45
10
53
ArtificialIfElse/AIC-COMPFEST13
Deployment/paper.py
Python
paper_index
paper_index
15
21
15
16
b9f8244356386ab9ff7fd6af20a907aeab46c334
bigcode/the-stack
train
7f663d64eb5b0202975e59fc
train
function
@paper.route("/paper/predict", methods=["POST"]) def predict_paper(): abstract = request.form['abstract'] language = request.form['language'] if language == 2: translator = Translator() result_translate = translator.translate(abstract, dest='en') abstract = result_translate.text ...
@paper.route("/paper/predict", methods=["POST"]) def predict_paper():
abstract = request.form['abstract'] language = request.form['language'] if language == 2: translator = Translator() result_translate = translator.translate(abstract, dest='en') abstract = result_translate.text classifier = pipeline("zero-shot-classification", model="valhalla/dis...
paper.route("/paper/request-predict") def request_predict(): data = { "title": "Masukkan Hasil Paper Kamu", "selected": "paper" } return render_template("paper/request-paper.html", data=data) @paper.route("/paper/predict", methods=["POST"]) def predict_paper():
67
67
225
17
50
ArtificialIfElse/AIC-COMPFEST13
Deployment/paper.py
Python
predict_paper
predict_paper
32
57
32
33
edf638bc1a92f3eda152742f3d6ddeb66fa5d511
bigcode/the-stack
train
a8bb2d8c71aa0d2cb97693a2
train
class
class ImageWithThumbsField(ImageField): attr_class = ImageWithThumbsFieldFile """ Usage example: ============== photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),) To retrieve image URL, exactly the same way as with ImageField: my_object.photo.url To retrie...
class ImageWithThumbsField(ImageField):
attr_class = ImageWithThumbsFieldFile """ Usage example: ============== photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),) To retrieve image URL, exactly the same way as with ImageField: my_object.photo.url To retrieve thumbnails URL's just add the size to...
raise ValueError('There is already a file named %s' % thumb_name) def delete(self, save=True): name = self.name super(ImageWithThumbsFieldFile, self).delete(save) if self.sizes: for size in self.sizes: (w, h) = size split = nam...
131
131
438
9
121
restless/django-lfs
lfs/core/fields/thumbs.py
Python
ImageWithThumbsField
ImageWithThumbsField
105
155
105
105
e1ed5744fa27ec3faaa7facf6ea66754b24c90fb
bigcode/the-stack
train
83fd245047f6777a3bc82754
train
class
class ImageWithThumbsFieldFile(ImageFieldFile): """ See ImageWithThumbsField for usage example """ def __init__(self, *args, **kwargs): super(ImageWithThumbsFieldFile, self).__init__(*args, **kwargs) self.sizes = self.field.sizes if self.sizes: def get_size(self, siz...
class ImageWithThumbsFieldFile(ImageFieldFile):
""" See ImageWithThumbsField for usage example """ def __init__(self, *args, **kwargs): super(ImageWithThumbsFieldFile, self).__init__(*args, **kwargs) self.sizes = self.field.sizes if self.sizes: def get_size(self, size): if not self: ...
the generated thumbnail, too) """ img.seek(0) image = Image.open(img) # Convert to RGB if necessary if image.mode not in ('L', 'RGB', 'RGBA'): image = image.convert('RGB') new_image = scale_to_max_size(image, *thumb_size) io = cStringIO.StringIO() # PNG and GIF are the same,...
131
131
438
11
120
restless/django-lfs
lfs/core/fields/thumbs.py
Python
ImageWithThumbsFieldFile
ImageWithThumbsFieldFile
54
102
54
54
cb88175c0a7256e824d14a0b25c3668a000f1d6d
bigcode/the-stack
train
b58ce2d8131b98d617c96621
train
function
def generate_thumb(img, thumb_size, format): """ Generates a thumbnail image and returns a ContentFile object with the thumbnail Parameters: =========== img File object thumb_size desired thumbnail size, ie: (200,120) format format of the original image ('jpeg','gif','png',....
def generate_thumb(img, thumb_size, format):
""" Generates a thumbnail image and returns a ContentFile object with the thumbnail Parameters: =========== img File object thumb_size desired thumbnail size, ie: (200,120) format format of the original image ('jpeg','gif','png',...) (this format will be used...
# django imports from django.core.files.base import ContentFile from django.db.models import ImageField from django.db.models.fields.files import ImageFieldFile from django.conf import settings # lfs imports from lfs.utils.images import scale_to_max_size def generate_thumb(img, thumb_size, format):
64
64
198
10
53
restless/django-lfs
lfs/core/fields/thumbs.py
Python
generate_thumb
generate_thumb
22
51
22
22
3657edc91b7082b76a9bcbe6e21adfb94e112478
bigcode/the-stack
train
cd6c290d13fbe0403898cdaf
train
function
@click.command() @click.pass_context # General options. @click.option('--outdir', help='Where to save the results', required=True, metavar='DIR') @click.option('--gpus', help='Number of GPUs to use [default: 1]', type=int, metavar='INT') @click.option('--snap', help='Snapshot interval [default: 50 ticks]', type=int, m...
@click.command() @click.pass_context # General options. @click.option('--outdir', help='Where to save the results', required=True, metavar='DIR') @click.option('--gpus', help='Number of GPUs to use [default: 1]', type=int, metavar='INT') @click.option('--snap', help='Snapshot interval [default: 50 ticks]', type=int, m...
"""Train a GAN using the techniques described in the paper "Training Generative Adversarial Networks with Limited Data". Examples: \b # Train with custom dataset using 1 GPU. python train.py --outdir=~/training-runs --data=~/mydataset.zip --gpus=1 \b # Train class-conditional CIFAR-10...
@click.command() @click.pass_context # General options. @click.option('--outdir', help='Where to save the results', required=True, metavar='DIR') @click.option('--gpus', help='Number of GPUs to use [default: 1]', type=int, metavar='INT') @click.option('--snap', help='Snapshot interval [default: 50 ticks]', type=int, m...
678
256
1,679
678
0
programWhiz/stylegan2-ada-pytorch
train.py
Python
main
main
399
534
399
439
aeda1d3a4584c657123b40ec1535edf62cb6e0be
bigcode/the-stack
train
630f5b4e5d6e870960881267
train
class
class UserError(Exception): pass
class UserError(Exception):
pass
arial Networks with Limited Data".""" import os import click import re import json import tempfile import torch import dnnlib from training import training_loop from metrics import metric_main from torch_utils import training_stats from torch_utils import custom_ops #-------------------------------------------------...
63
64
8
5
58
programWhiz/stylegan2-ada-pytorch
train.py
Python
UserError
UserError
27
28
27
27
8d001c42fe7ae6d94035efd4eae8bca25cf5c46b
bigcode/the-stack
train
3fd0463a7bef373b8a94bb5f
train
function
def subprocess_fn(rank, args, temp_dir): dnnlib.util.Logger(file_name=os.path.join(args.run_dir, 'log.txt'), file_mode='a', should_flush=True) # Init torch.distributed. if args.num_gpus > 1: init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init')) if os.name == 'nt': ...
def subprocess_fn(rank, args, temp_dir):
dnnlib.util.Logger(file_name=os.path.join(args.run_dir, 'log.txt'), file_mode='a', should_flush=True) # Init torch.distributed. if args.num_gpus > 1: init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init')) if os.name == 'nt': init_method = 'file:///' + ini...
32: args.allow_tf32 = True if workers is not None: assert isinstance(workers, int) if not workers >= 1: raise UserError('--workers must be at least 1') args.data_loader_kwargs.num_workers = workers return desc, args #------------------------------------------------...
74
75
252
10
64
programWhiz/stylegan2-ada-pytorch
train.py
Python
subprocess_fn
subprocess_fn
364
384
364
364
0805e49b1d8949a273e4f7e9ebe2ed97a2096bf5
bigcode/the-stack
train
30f2ea2fb1213280c83ba3de
train
class
class CommaSeparatedList(click.ParamType): name = 'list' def convert(self, value, param, ctx): _ = param, ctx if value is None or value.lower() == 'none' or value == '': return [] return value.split(',')
class CommaSeparatedList(click.ParamType):
name = 'list' def convert(self, value, param, ctx): _ = param, ctx if value is None or value.lower() == 'none' or value == '': return [] return value.split(',')
training_stats.init_multiprocessing(rank=rank, sync_device=sync_device) if rank != 0: custom_ops.verbosity = 'none' # Execute training loop. training_loop.training_loop(rank=rank, **args) #---------------------------------------------------------------------------- class CommaSeparatedList(cl...
63
64
58
9
54
programWhiz/stylegan2-ada-pytorch
train.py
Python
CommaSeparatedList
CommaSeparatedList
388
395
388
388
994045021c95cff57098d4f978ea3b90e588d470
bigcode/the-stack
train
f2d785ebb4f2da0693a74b83
train
function
def setup_training_loop_kwargs( # General options (not included in desc). gpus = None, # Number of GPUs: <int>, default = 1 gpu snap = None, # Snapshot interval: <int>, default = 50 ticks metrics = None, # List of metric names: [], ['fid50k_full'] (default), ... seed = None, # R...
def setup_training_loop_kwargs( # General options (not included in desc). gpus = None, # Number of GPUs: <int>, default = 1 gpu snap = None, # Snapshot interval: <int>, default = 50 ticks metrics = None, # List of metric names: [], ['fid50k_full'] (default), ... seed = None, # R...
args = dnnlib.EasyDict() # ------------------------------------------ # General options: gpus, snap, metrics, seed # ------------------------------------------ if gpus is None: gpus = 1 assert isinstance(gpus, int) if not (gpus >= 1 and gpus & (gpus - 1) == 0): raise UserEr...
def setup_training_loop_kwargs( # General options (not included in desc). gpus = None, # Number of GPUs: <int>, default = 1 gpu snap = None, # Snapshot interval: <int>, default = 50 ticks metrics = None, # List of metric names: [], ['fid50k_full'] (default), ... seed = None, # R...
594
256
4,198
594
0
programWhiz/stylegan2-ada-pytorch
train.py
Python
setup_training_loop_kwargs
setup_training_loop_kwargs
32
360
32
67
a9cb19ea6b32c51e59ba0b3c3004cef84b9b4301
bigcode/the-stack
train
33acc7b4cb658c3aecfdb945
train
function
def df2csv(path, filename, function, *args): create_dir(path) path_file = path + filename + ".csv" # file does not exist so save df to csv if(os.path.isfile(path_file) == False): df = function(*args) df.to_csv(path_file, sep = ",") else: print("File already found in path spe...
def df2csv(path, filename, function, *args):
create_dir(path) path_file = path + filename + ".csv" # file does not exist so save df to csv if(os.path.isfile(path_file) == False): df = function(*args) df.to_csv(path_file, sep = ",") else: print("File already found in path specified: {0}.".format(path_file))
###### importing dependencies ############################################################################ import os import pandas as pd # does not take care of race conditions... def create_dir(dir): if not os.path.exists(dir): os.makedirs(dir) def df2csv(path, filename, function, *args):
54
64
91
13
41
achmand/ari5122_assignment
src/fintech/dataio.py
Python
df2csv
df2csv
10
19
10
10
0f9a0b5bf8e6a39ea1e54fb3e3040ffac16b4849
bigcode/the-stack
train
d8d4be4b4b111cbf186c03f8
train
function
def csv2df(path, filename, index_col= None): return pd.read_csv(path + filename + ".csv", index_col=index_col)
def csv2df(path, filename, index_col= None):
return pd.read_csv(path + filename + ".csv", index_col=index_col)
if(os.path.isfile(path_file) == False): df = function(*args) df.to_csv(path_file, sep = ",") else: print("File already found in path specified: {0}.".format(path_file)) def csv2df(path, filename, index_col= None):
64
64
30
13
51
achmand/ari5122_assignment
src/fintech/dataio.py
Python
csv2df
csv2df
21
22
21
21
0dca4f37f8f2f4f42a689cb817f6a451a5252528
bigcode/the-stack
train
d180b9cc0cd09a9dcfa2bcef
train
function
def create_dir(dir): if not os.path.exists(dir): os.makedirs(dir)
def create_dir(dir):
if not os.path.exists(dir): os.makedirs(dir)
###### importing dependencies ############################################################################ import os import pandas as pd # does not take care of race conditions... def create_dir(dir):
28
64
18
5
23
achmand/ari5122_assignment
src/fintech/dataio.py
Python
create_dir
create_dir
6
8
6
6
276abe15da4f0108278bcc18d4483172c71fa986
bigcode/the-stack
train
66d323e7e3c850be9c29bae5
train
class
class TestParkingTicket(unittest.TestCase): def test_four_wheeler_parking_ticket(self): curr_parking_spot = next(FourWheelerParkingTicket.ticket_counter) start = curr_parking_spot + 1 end = start + 100 for i in range(start, end): ticket = FourWheelerParkingTicket() ...
class TestParkingTicket(unittest.TestCase):
def test_four_wheeler_parking_ticket(self): curr_parking_spot = next(FourWheelerParkingTicket.ticket_counter) start = curr_parking_spot + 1 end = start + 100 for i in range(start, end): ticket = FourWheelerParkingTicket() self.assertEqual(i, ticket.id_) ...
from datetime import datetime import unittest from parking_lot.constants import ParkingSpotType from parking_lot.parking_ticket import FourWheelerParkingTicket class TestParkingTicket(unittest.TestCase):
41
64
200
8
32
shenbakeshk/parking-lot
tests/test_parking_ticket.py
Python
TestParkingTicket
TestParkingTicket
7
27
7
7
7409945ab804b9349f2afa19e4a8748efb8b1464
bigcode/the-stack
train
a7b62db96e5a7f2fdae209d6
train
class
class Entropy(Module): XLABEL = 'Offset' YLABEL = 'Entropy' XUNITS = 'B' YUNITS = 'E' FILE_WIDTH = 1024 FILE_FORMAT = 'png' COLORS = ['r', 'g', 'c', 'b', 'm'] DEFAULT_BLOCK_SIZE = 1024 TITLE = "Entropy Analysis" ORDER = 8 CLI = [ Option(short='E', ...
class Entropy(Module):
XLABEL = 'Offset' YLABEL = 'Entropy' XUNITS = 'B' YUNITS = 'E' FILE_WIDTH = 1024 FILE_FORMAT = 'png' COLORS = ['r', 'g', 'c', 'b', 'm'] DEFAULT_BLOCK_SIZE = 1024 TITLE = "Entropy Analysis" ORDER = 8 CLI = [ Option(short='E', long='entr...
import os import math import binwalk.core.common from binwalk.core.compat import * from binwalk.core.module import Module, Option, Kwarg class Entropy(Module):
37
256
1,408
5
31
zhao07/binwalk
src/binwalk/modules/entropy.py
Python
Entropy
Entropy
7
201
7
8
5237b1147a98fc167ced11902ce1278bb48b47b8
bigcode/the-stack
train
cb14bc3c447ce6235fac0cfa
train
class
class Author(Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(250), nullable=False, index=True) birth_date = db.Column(db.DateTime, nullable=False) books = db.relationship('Book', backref='author', lazy="dynamic") def __init__(self, first_name, last_name, birth_date):...
class Author(Model):
id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(250), nullable=False, index=True) birth_date = db.Column(db.DateTime, nullable=False) books = db.relationship('Book', backref='author', lazy="dynamic") def __init__(self, first_name, last_name, birth_date): self.name = ...
.nickname = nickname @classmethod def get_by_id(cls, user_id): return cls.query.get(int(user_id)) def serialize(self, includes=None): d = super().serialize() d.pop('bookings') d.pop('loans') return d class Author(Model):
64
64
197
4
59
gekorob/liebraryrest
liebraryrest/models.py
Python
Author
Author
26
47
26
26
ef5e201af7e47a7247b74e9a703c4292119c3352
bigcode/the-stack
train
61b80716fc693bc60eab529f
train
class
class Book(Model): isbn = db.Column(db.String(13), primary_key=True) title = db.Column(db.Text, nullable=False, index=True) abstract = db.Column(db.Text, nullable=True) pages = db.Column(db.Integer, nullable=True) publisher = db.Column(db.String(250), nullable=True) quantity = db.Column(db.Integ...
class Book(Model):
isbn = db.Column(db.String(13), primary_key=True) title = db.Column(db.Text, nullable=False, index=True) abstract = db.Column(db.Text, nullable=True) pages = db.Column(db.Integer, nullable=True) publisher = db.Column(db.String(250), nullable=True) quantity = db.Column(db.Integer, default=1) ...
): return cls.query.get(int(author_id)) def serialize(self, includes=None): d = super().serialize() d['birth_date'] = d['birth_date'].isoformat() if (includes is not None) and 'books' in includes: d['books'] = Book.serialize_list(self.books.all()) else: ...
85
85
286
4
80
gekorob/liebraryrest
liebraryrest/models.py
Python
Book
Book
50
84
50
50
58a79549f9c836f572865193082ac1de306c27ef
bigcode/the-stack
train
8731ecc4ccb90ea7e4e6c8b3
train
class
class Booking(Model): __table_args__ = (UniqueConstraint('book_isbn', 'user_id', name='_book_isbn_user_id'),) id = db.Column(db.Integer, primary_key=True) book_isbn = db.Column(db.String(13), db.ForeignKey('book.isbn'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=...
class Booking(Model):
__table_args__ = (UniqueConstraint('book_isbn', 'user_id', name='_book_isbn_user_id'),) id = db.Column(db.Integer, primary_key=True) book_isbn = db.Column(db.String(13), db.ForeignKey('book.isbn'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) created_at ...
serialize() if (includes is not None) and 'author' in includes: d['author'] = Book.serialize_list(self.author) else: d.pop('author') d.pop('bookings') return d def is_available(self): return self.quantity > 0 class Booking(Model):
67
67
225
4
62
gekorob/liebraryrest
liebraryrest/models.py
Python
Booking
Booking
87
110
87
87
6a70d55f752a60def9ddf24741d8cf4d69ca5678
bigcode/the-stack
train
79141fa83d744c328a4b9a26
train
class
class User(Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(50), nullable=False, index=True) bookings = db.relationship('Booking', backref='user', lazy="dynamic") loans = db.relationship('Loan', backref='user', lazy="dynamic") def __init__(self, nickname): ...
class User(Model):
id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(50), nullable=False, index=True) bookings = db.relationship('Booking', backref='user', lazy="dynamic") loans = db.relationship('Loan', backref='user', lazy="dynamic") def __init__(self, nickname): self.nickname = ni...
from datetime import datetime from liebraryrest.database import db, Model from sqlalchemy import UniqueConstraint class User(Model):
26
64
137
4
21
gekorob/liebraryrest
liebraryrest/models.py
Python
User
User
6
23
6
6
b9fabfc04522ed19d2134e1c22182855a7ab5eaf
bigcode/the-stack
train
d1bbd7ed32fab35bf7653115
train
class
class Loan(Model): __table_args__ = (UniqueConstraint('book_isbn', 'user_id', name='_book_isbn_user_id_on_loan'),) id = db.Column(db.Integer, primary_key=True) book_isbn = db.Column(db.String(13), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) booking_id =...
class Loan(Model):
__table_args__ = (UniqueConstraint('book_isbn', 'user_id', name='_book_isbn_user_id_on_loan'),) id = db.Column(db.Integer, primary_key=True) book_isbn = db.Column(db.String(13), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) booking_id = db.Column(db.Integ...
, includes=None): return { 'id': self.id, 'isbn': self.book.isbn, 'user_id:': self.user.id, 'created_at': self.created_at.isoformat() } @classmethod def get_by_isbn_and_user_id(cls, book_isbn, user_id): return cls.query.filter(Booking.book...
96
96
323
4
92
gekorob/liebraryrest
liebraryrest/models.py
Python
Loan
Loan
113
148
113
113
5882c5a61e3706b8b572db80ae114746c795bbd4
bigcode/the-stack
train
edd34769c8424a5ffee46445
train
function
def main(argv): topology_name = argv[0] if len(argv) >= 2: is_test = argv[1] == "test" else: is_test = False if is_test: multi_simulation(topology_name) else: single_simulation(topology_name)
def main(argv):
topology_name = argv[0] if len(argv) >= 2: is_test = argv[1] == "test" else: is_test = False if is_test: multi_simulation(topology_name) else: single_simulation(topology_name)
range(50): print("Test number", test_number) simulate(topology_name, multitest=True, iteration=test_number) # plot slices Plotter.plot_10test(num_slices=6, name="moto", plot_mean=False, from_memory=False) def main(argv):
64
64
64
4
60
late-goodbye/memristive-spinal-cord
NEST/second_level/bin/run.py
Python
main
main
86
96
86
86
1b32c7bbfc9c11d4ee8c84ef395a2301aadb7fea
bigcode/the-stack
train
a51d6ccf04ff457700412fc7
train
function
def cleaner(): """Clean the previous results""" Cleaner.clean() Cleaner.create_structure()
def cleaner():
"""Clean the previous results""" Cleaner.clean() Cleaner.create_structure()
PATH sys.path.append('/'.join(os.path.realpath(__file__).split('/')[:-3])) from second_level.src.tools.cleaner import Cleaner from second_level.src.paths import topologies_path from second_level.src.tools.plotter import Plotter from second_level.src.tools.miner import Miner def cleaner():
64
64
21
3
60
late-goodbye/memristive-spinal-cord
NEST/second_level/bin/run.py
Python
cleaner
cleaner
15
18
15
15
bcf17f8a98b1ba8f85b02e84125d775568f5bca6
bigcode/the-stack
train
2798f7e4f147ad07e708a4db
train
function
def plot_results(params): """ Plotting results Args: params: """ to_plot = params.TO_PLOT.value to_plot_with_slices = params.TO_PLOT_WITH_SLICES.value # plot voltages for each node for name in to_plot: Plotter.plot_voltage(name, name, with_spikes=True) Plotter.save_voltage(name) # plot slices for key...
def plot_results(params):
""" Plotting results Args: params: """ to_plot = params.TO_PLOT.value to_plot_with_slices = params.TO_PLOT_WITH_SLICES.value # plot voltages for each node for name in to_plot: Plotter.plot_voltage(name, name, with_spikes=True) Plotter.save_voltage(name) # plot slices for key in to_plot_with_slices.ke...
globals(), locals(), ['Params', 'Topology'], 0) Params = topology.Params topology.Topology(multitest=multitest, iteration=iteration) # simulate the topology nest.Simulate(Params.SIMULATION_TIME.value) return Params def plot_results(params):
64
64
122
5
58
late-goodbye/memristive-spinal-cord
NEST/second_level/bin/run.py
Python
plot_results
plot_results
48
65
48
48
c9959ce84c850eb64a4b148cbae5804127883ad9
bigcode/the-stack
train
17c5e2844ab37e2c1acc3cd1
train
function
def multi_simulation(topology_name): """ Args: topology_name: """ cleaner() for test_number in range(50): print("Test number", test_number) simulate(topology_name, multitest=True, iteration=test_number) # plot slices Plotter.plot_10test(num_slices=6, name="moto", plot_mean=False, from_memory=False)
def multi_simulation(topology_name):
""" Args: topology_name: """ cleaner() for test_number in range(50): print("Test number", test_number) simulate(topology_name, multitest=True, iteration=test_number) # plot slices Plotter.plot_10test(num_slices=6, name="moto", plot_mean=False, from_memory=False)
_plot_with_slices.keys(): Plotter.plot_slices(num_slices=to_plot_with_slices[key], name=key) def single_simulation(topology_name): cleaner() params = simulate(topology_name, multitest=False) plot_results(params) def multi_simulation(topology_name):
64
64
88
8
56
late-goodbye/memristive-spinal-cord
NEST/second_level/bin/run.py
Python
multi_simulation
multi_simulation
72
83
72
72
76e4e78966f2e5fce95d03b101a46a37e428b7f0
bigcode/the-stack
train
e2fc7d4dc8bfaf7639f24e36
train
function
def single_simulation(topology_name): cleaner() params = simulate(topology_name, multitest=False) plot_results(params)
def single_simulation(topology_name):
cleaner() params = simulate(topology_name, multitest=False) plot_results(params)
.plot_voltage(name, name, with_spikes=True) Plotter.save_voltage(name) # plot slices for key in to_plot_with_slices.keys(): Plotter.plot_slices(num_slices=to_plot_with_slices[key], name=key) def single_simulation(topology_name):
64
64
28
8
56
late-goodbye/memristive-spinal-cord
NEST/second_level/bin/run.py
Python
single_simulation
single_simulation
67
70
67
67
0126df51adf69ea0cfc8269db91cdd0cd2c820e3
bigcode/the-stack
train
2e7c38bda2eda92545c03e5a
train
function
def simulate(topology_name, multitest=False, iteration=None): """ Args: topology_name: multitest: iteration: Returns: class: Params class """ nest.ResetKernel() nest.SetKernelStatus({ 'total_num_virtual_procs': 4, 'print_time': True, 'resolution': 0.1, 'overwrite_files': True}) # create topology...
def simulate(topology_name, multitest=False, iteration=None):
""" Args: topology_name: multitest: iteration: Returns: class: Params class """ nest.ResetKernel() nest.SetKernelStatus({ 'total_num_virtual_procs': 4, 'print_time': True, 'resolution': 0.1, 'overwrite_files': True}) # create topology topology = __import__('{}.{}'.format(topologies_path, topolo...
second_level.src.paths import topologies_path from second_level.src.tools.plotter import Plotter from second_level.src.tools.miner import Miner def cleaner(): """Clean the previous results""" Cleaner.clean() Cleaner.create_structure() def simulate(topology_name, multitest=False, iteration=None):
64
64
173
13
51
late-goodbye/memristive-spinal-cord
NEST/second_level/bin/run.py
Python
simulate
simulate
20
45
20
20
a8032d0e9ce6f8dc36e11623d9029a342c7b0691
bigcode/the-stack
train
ff198fb2a1fbe35d211b81ee
train
class
class OGLColorMapWidget(OGLWidget): """This object provides a OpenGL window that displays an RGBA color map""" def __init__( self, master, cmap, title="OGLColorMapWidget", width=None, height=None, cnf=None, **kw ): if width is None: ...
class OGLColorMapWidget(OGLWidget):
"""This object provides a OpenGL window that displays an RGBA color map""" def __init__( self, master, cmap, title="OGLColorMapWidget", width=None, height=None, cnf=None, **kw ): if width is None: kw["width"] = 19 ...
if self.current == "Hue": h = ((self.width - x) / self.xrange) * 0.999 # *.6666666667 cur_val[0] = round(h, 3) else: # use keyList = ['Sat', 'Val', 'Opa'] keyList = self.idList[1:] ind = keyList.index(self.current) + 1 h = (x - sel...
144
144
483
10
134
mesoscope/cellpack
cellpack/mgl_tools/DejaVu/ColormapGui.py
Python
OGLColorMapWidget
OGLColorMapWidget
2,080
2,147
2,080
2,080
3692687bfac87648fc5b646c95efdfbb4f086be1
bigcode/the-stack
train
7c98123b7746b6b521f5b872
train
class
class ColorMapGUI(tkinter.Frame, ColorMap): """The ColorMapGUI is an object providing an interface to expose and to modify a ColorMap object. The ColorMapGUI has a local copy of the colormap.ramp, colormap.mini and colormap.maxi which will be modified through the GUI. The associated colormap object...
class ColorMapGUI(tkinter.Frame, ColorMap):
"""The ColorMapGUI is an object providing an interface to expose and to modify a ColorMap object. The ColorMapGUI has a local copy of the colormap.ramp, colormap.mini and colormap.maxi which will be modified through the GUI. The associated colormap object will only be updated when by the apply_cb ...
> 0: lCurSelection0 = int(lCurSelection[0]) if self.reverse is True: lBoolTest = ( len(self.externalList) - 1 - lCurSelection0 ) >= self.numOfBlockedLabels else: lBoolTest = lCurSelection0 >= self.numOfBlockedLabels...
256
256
16,310
12
243
mesoscope/cellpack
cellpack/mgl_tools/DejaVu/ColormapGui.py
Python
ColorMapGUI
ColorMapGUI
97
2,077
97
97
e46f5d408c4834fa1130283456b5e57a3e2c4c82
bigcode/the-stack
train
4593c76da0caaed2646c1517
train
class
class ComboBoxRename(Pmw.ComboBox): def setExternalList(self, externalList, reverse=False, numOfBlockedLabels=0): self.externalList = externalList self.reverse = reverse self.numOfBlockedLabels = numOfBlockedLabels def _addHistory(self): # print "_addHistory" lCurSelecti...
class ComboBoxRename(Pmw.ComboBox):
def setExternalList(self, externalList, reverse=False, numOfBlockedLabels=0): self.externalList = externalList self.reverse = reverse self.numOfBlockedLabels = numOfBlockedLabels def _addHistory(self): # print "_addHistory" lCurSelection = self.curselection() if ...
Vu.MaterialEditor import OGLWidget from DejaVu.colorMapLegend import ColorMapLegend from DejaVu.Geom import Geom from DejaVu.colorTool import ( RGBARamp, RedWhiteBlueRamp, RedWhiteRamp, WhiteBlueRamp, TkColor, ) from DejaVu.Legend import drawLegendOnly class ComboBoxRename(Pmw.ComboBox):
84
84
280
9
74
mesoscope/cellpack
cellpack/mgl_tools/DejaVu/ColormapGui.py
Python
ComboBoxRename
ComboBoxRename
53
83
53
53
cef10487e9ae4a57ef31cabcd762016cca79c72e
bigcode/the-stack
train
40ebc5d0717d49cbd2a4846c
train
class
class DummyEvent: """dummy Tkinter event """ def __init__(self, x=0, y=0): self.x = x self.y = y
class DummyEvent:
"""dummy Tkinter event """ def __init__(self, x=0, y=0): self.x = x self.y = y
: self.externalList[ len(self.externalList) - 1 - lCurSelection0 ] = input else: self.externalList[lCurSelection0] = input self.selectitem(lCurSelection0) else: self.se...
64
64
38
4
60
mesoscope/cellpack
cellpack/mgl_tools/DejaVu/ColormapGui.py
Python
DummyEvent
DummyEvent
86
91
86
86
0a9a80c81a044e39f016cd1a974804c1099171f6
bigcode/the-stack
train
ffb31d4a892f0c4b771ae785
train
function
@app.route('/') def index(): return render_template("index.html")
@app.route('/') def index():
return render_template("index.html")
from flask import Flask, render_template import os app = Flask(__name__) @app.route('/') def index():
24
64
14
6
18
djengineer/flask-python3-starter-kit
flask_app.py
Python
index
index
6
8
6
7
f483a25cd6dd96d8960a4001456060acd492e262
bigcode/the-stack
train
190656db13682affea31e40a
train
function
@app.route('/page1/') def page1(): return render_template("page1.html")
@app.route('/page1/') def page1():
return render_template("page1.html")
from flask import Flask, render_template import os app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/page1/') def page1():
42
64
19
10
32
djengineer/flask-python3-starter-kit
flask_app.py
Python
page1
page1
10
12
10
11
3432006e24cc58e0bc168451f3f9939f1dd2c42f
bigcode/the-stack
train
a32c2721cf8c9a6196fd6d86
train
class
class RAffycompatible(RPackage): """This package provides an interface to Affymetrix chip annotation and sample attribute files. The package allows an easy way for users to download and manage local data bases of Affynmetrix NetAffx annotation files. The package also provides access to GeneChip Oper...
class RAffycompatible(RPackage):
"""This package provides an interface to Affymetrix chip annotation and sample attribute files. The package allows an easy way for users to download and manage local data bases of Affynmetrix NetAffx annotation files. The package also provides access to GeneChip Operating System (GCOS) and GeneChip ...
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RAffycompatible(RPackage):
62
70
234
8
54
HaochengLIU/spack
var/spack/repos/builtin/packages/r-affycompatible/package.py
Python
RAffycompatible
RAffycompatible
9
25
9
9
40413b640c84192f7fb69d609ce358bf3d76565a
bigcode/the-stack
train
3cb9960184e9d0863b3c71a2
train
function
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() ...
def main(*args):
""" Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() site = pywiki...
ot.output(u'%s is a disambig page, skip...' % page.title()) return else: # Ok, the page need the template. Let's put it there! # Adding the template in the text newtxt = u"%s\n%s" % (self.template, oldtxt) ...
89
89
299
5
84
valhallasw/pywikibot-core
scripts/lonelypages.py
Python
main
main
196
236
196
196
45a18e80ff833db4c19b7786bca1180b818ca02b
bigcode/the-stack
train
deae99afdcd8a570166daa75
train
class
class LonelyPagesBot(Bot): """Orphan page tagging bot.""" def __init__(self, generator, **kwargs): self.availableOptions.update({ 'enablePage': None, # Check if someone set an enablePage or not 'disambigPage': None, # If no disambigPage given, not use it. }) ...
class LonelyPagesBot(Bot):
"""Orphan page tagging bot.""" def __init__(self, generator, **kwargs): self.availableOptions.update({ 'enablePage': None, # Check if someone set an enablePage or not 'disambigPage': None, # If no disambigPage given, not use it. }) super(LonelyPagesBot, self)...
en': u'{{Orphan|date={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}', 'it': u'{{O||mese={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}', 'ja': u'{{孤立|{{subst:DATE}}}}', 'zh': u'{{subst:Orphan/auto}}', } # Use regex to prevent to put the same template twice! exception_regex = { 'ar': [u'\\{\\{(?...
256
256
1,155
7
249
valhallasw/pywikibot-core
scripts/lonelypages.py
Python
LonelyPagesBot
LonelyPagesBot
79
193
79
80
53420e817981a0bd80546de632f5782939b66e6e
bigcode/the-stack
train
9f880ac851b6f75b5ac28d57
train
class
class FakeTask(BaseTask): _task_model = models.FakeTask
class FakeTask(BaseTask):
_task_model = models.FakeTask
from core.tasks import BaseTask from groups.tests import models from SZR.celery import app as celery_app class FakeTask(BaseTask):
31
64
16
6
24
Alek96/SZR
SZR/apps/groups/tests/tasks.py
Python
FakeTask
FakeTask
7
8
7
7
0044e08d5423b7e35611d326262b7e57a4f550ef
bigcode/the-stack
train
0bbb3ebd858b8042ef2c968c
train
class
class Batch(models.Model): """ OCR Batch object. """ user = models.ForeignKey(User, related_name="batches") name = models.CharField(max_length=255) project = models.ForeignKey(Project, related_name="batches") script = models.TextField() task_type = models.CharField(max_length=100) de...
class Batch(models.Model):
""" OCR Batch object. """ user = models.ForeignKey(User, related_name="batches") name = models.CharField(max_length=255) project = models.ForeignKey(Project, related_name="batches") script = models.TextField() task_type = models.CharField(max_length=100) description = models.TextFiel...
""" Object representing a batch operation, consisting of one or more OcrTasks. """ import datetime from django.db import models from django.contrib.auth.models import User from tagging.fields import TagField from ocradmin.projects.models import Project class Batch(models.Model):
56
219
733
5
50
mikesname/ocropodium
ocradmin/batch/models.py
Python
Batch
Batch
14
126
14
14
ca287f7ce551f70776748e82d0f564fb5aed143d
bigcode/the-stack
train
3efa5ad4adda3f7965dff63b
train
function
def present_menu(devices: List[dict], saved_device: Optional[dict] = None) -> dict: """ Format the menu of selectable microphones and receive selection from user. Parameters ---------- devices : List[dict] Device logs for detected microphones saved_device : Optional[dict] The devi...
def present_menu(devices: List[dict], saved_device: Optional[dict] = None) -> dict:
""" Format the menu of selectable microphones and receive selection from user. Parameters ---------- devices : List[dict] Device logs for detected microphones saved_device : Optional[dict] The device log for the saved device - used to indicate on the menu the current save...
a dictionary containing the name and default-config details of the device.""" p = pyaudio.PyAudio() devices = [p.get_device_info_by_index(index) for index in range(0, p.get_device_count())] return [device for device in devices if device['maxInputChannels'] > 0] def present_menu(devices: List[di...
92
92
309
23
69
JuliusStein/Week1_pip
microphone/configure_input.py
Python
present_menu
present_menu
40
81
40
40
ff699e41dd9005aa537d6af26f35cad5c91f1fad
bigcode/the-stack
train
feb6f9e6c4127c428c6cf055
train
function
def get_input_devices() -> List[dict]: """ Use pyaudio to detect available mic-devices. Returns ------- List[dict] Device logs - each is a dictionary containing the name and default-config details of the device.""" p = pyaudio.PyAudio() devices = [p.get_devic...
def get_input_devices() -> List[dict]:
""" Use pyaudio to detect available mic-devices. Returns ------- List[dict] Device logs - each is a dictionary containing the name and default-config details of the device.""" p = pyaudio.PyAudio() devices = [p.get_device_info_by_index(index) for index in ran...
index: device index from config prompt}""" config = configparser.ConfigParser() # This returns an empty array if no config file was found if config.read(str(path / 'config.ini')): return config['input device'] return None def get_input_devices() -> List[dict]:
64
64
108
10
53
JuliusStein/Week1_pip
microphone/configure_input.py
Python
get_input_devices
get_input_devices
27
37
27
27
bb9c0706b6c50d5c60da57629e96ca33a81efc6a
bigcode/the-stack
train
f3a4c889431ef4570e563b72
train
function
def save_ini(selected_device: dict): """ Saves device to songfp/mic_config/config.ini Parameters ---------- selected_device : dict {name : device name, index: device index from config prompt}""" config = configparser.ConfigParser() config['input device'] = {...
def save_ini(selected_device: dict):
""" Saves device to songfp/mic_config/config.ini Parameters ---------- selected_device : dict {name : device name, index: device index from config prompt}""" config = configparser.ConfigParser() config['input device'] = { 'name': selected_device['nam...
strip() if menuInput.isdecimal(): menuSelection = int(menuInput) if menuSelection <= menuIndex: inputValid = True else: print("invalid input") else: print("invalid input") return devices[menuSelection] def save_ini(selec...
64
64
107
8
56
JuliusStein/Week1_pip
microphone/configure_input.py
Python
save_ini
save_ini
84
98
84
84
1169490c61f42fb6525b8dad89c379e29b621c19
bigcode/the-stack
train
04ccf51d48d0b5683c231a7c
train
function
def load_ini() -> Union[dict, None]: """Returns the saved device from config.ini or `None` Returns ------- Union[dict, None] {name : device name, index: device index from config prompt}""" config = configparser.ConfigParser() # This returns an empty array if no config file was...
def load_ini() -> Union[dict, None]:
"""Returns the saved device from config.ini or `None` Returns ------- Union[dict, None] {name : device name, index: device index from config prompt}""" config = configparser.ConfigParser() # This returns an empty array if no config file was found if config.read(str(path / ...
script will prompt the user to select from a list of detected microphones. The selected device fill be logged in a file 'config.ini'""" import pyaudio import configparser from typing import Union, List, Optional from microphone.config import path def load_ini() -> Union[dict, None]:
64
64
97
11
52
JuliusStein/Week1_pip
microphone/configure_input.py
Python
load_ini
load_ini
11
24
11
11
cd335152ea9ea78fac12b39a09ac5e88e2c6e396
bigcode/the-stack
train
9a497108457855d982670a98
train
function
def plot_dynamic_strats(t, v_t_strat, v_t_risky, w_t_risky, h_t_risky, num, j_sel): """For details, see here. Parameters ---------- t : array, shape (t_,) v_t_strat : array, shape (j_,t_) v_t_risky : array, shape (j_,t_) w_t_risky : array, shape (j_,t...
def plot_dynamic_strats(t, v_t_strat, v_t_risky, w_t_risky, h_t_risky, num, j_sel):
"""For details, see here. Parameters ---------- t : array, shape (t_,) v_t_strat : array, shape (j_,t_) v_t_risky : array, shape (j_,t_) w_t_risky : array, shape (j_,t_) h_t_risky: array, shape (j_,t_) num: int j_sel: int """ # adjust v_t_...
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec from matplotlib.ticker import FuncFormatter def tick_label_func(y, pos=None): return '%1.f' % (5 * y * 1e-2 // 5) def tick_label_func_1(y, pos=None): return '%0.0f' ...
128
256
1,531
33
94
dpopadic/arpmRes
arpym/tools/plc.py
Python
plot_dynamic_strats
plot_dynamic_strats
18
137
18
19
de9e5bbd317c45684e7288fb8f339c24012403a7
bigcode/the-stack
train
19a5accce33f9740e974dbcd
train
function
def tick_label_func(y, pos=None): return '%1.f' % (5 * y * 1e-2 // 5)
def tick_label_func(y, pos=None):
return '%1.f' % (5 * y * 1e-2 // 5)
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec from matplotlib.ticker import FuncFormatter def tick_label_func(y, pos=None):
52
64
30
9
42
dpopadic/arpmRes
arpym/tools/plc.py
Python
tick_label_func
tick_label_func
10
11
10
10
d512207306eb7842dd303154b5c057ff075e0efb
bigcode/the-stack
train
da599d6514420428b15d2070
train
function
def tick_label_func_1(y, pos=None): return '%0.0f' % y
def tick_label_func_1(y, pos=None):
return '%0.0f' % y
matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec from matplotlib.ticker import FuncFormatter def tick_label_func(y, pos=None): return '%1.f' % (5 * y * 1e-2 // 5) def tick_label_func_1(y, pos=None):
64
64
22
11
53
dpopadic/arpmRes
arpym/tools/plc.py
Python
tick_label_func_1
tick_label_func_1
14
15
14
14
f63269bfa5366b802fe0a1553927af185e1ec4d0
bigcode/the-stack
train
22f3f1138c19c0d6512e8b58
train
function
def which(program, mode=os.F_OK | os.X_OK, path=None): """ Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or...
def which(program, mode=os.F_OK | os.X_OK, path=None):
""" Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. :...
except FileExistsError: pass return retval def get_user_workspaces_dir(): """ Gets the directory for user workspaces directory. """ return os.path.join(get_app_data_directory(), 'workspaces') def which(program, mode=os.F_OK | os.X_OK, path=None):
64
64
156
17
47
fochoao/cpython
Lib/site-packages/hackedit/api/system.py
Python
which
which
63
79
63
63
cadf54835a0f13059d4c7fc97e248ced0596d199
bigcode/the-stack
train
6eb7c9c2da52e4783da797cc
train
function
def get_cmd_open_folder_in_terminal(): """ Gets a cross-platform, format string which contains the command needed for opening a folder in a terminal. The format string contains one placeholder for the path to open. - Windows: ```cmd.exe /K "cd /d "%s"``` - OSX: ```open -b com.apple.terminal %s`...
def get_cmd_open_folder_in_terminal():
""" Gets a cross-platform, format string which contains the command needed for opening a folder in a terminal. The format string contains one placeholder for the path to open. - Windows: ```cmd.exe /K "cd /d "%s"``` - OSX: ```open -b com.apple.terminal %s``` - Linux: depends on the installe...
one of the following programs: - gksu - kdesu - pseudo on OS X (https://github.com/sstephenson/pseudo) """ if LINUX: for program in ['gksu', 'kdesu', 'kdesudo', 'beesu']: if which(program) is not None: return program elif DARWIN: return '...
105
105
352
8
96
fochoao/cpython
Lib/site-packages/hackedit/api/system.py
Python
get_cmd_open_folder_in_terminal
get_cmd_open_folder_in_terminal
102
135
102
102
40ac22c976b578dd62f6c31f56c475be1e86a1c3
bigcode/the-stack
train
34491f14a4927ab73ea8ae81
train
function
def get_user_workspaces_dir(): """ Gets the directory for user workspaces directory. """ return os.path.join(get_app_data_directory(), 'workspaces')
def get_user_workspaces_dir():
""" Gets the directory for user workspaces directory. """ return os.path.join(get_app_data_directory(), 'workspaces')
', 'Application Support', 'HackEdit') else: return os.path.join(os.path.expanduser("~"), '.hackedit') retval = get_path() try: os.makedirs(retval) except FileExistsError: pass return retval def get_user_workspaces_dir():
64
64
35
7
56
fochoao/cpython
Lib/site-packages/hackedit/api/system.py
Python
get_user_workspaces_dir
get_user_workspaces_dir
56
60
56
56
c4781d270e96c569350290bcf16f2928f9209087
bigcode/the-stack
train
47c77abf84f27a1dddd0a06e
train
function
def get_authentication_program(): """ Gets the authentication program used to run command as root. The function try to use one of the following programs: - gksu - kdesu - pseudo on OS X (https://github.com/sstephenson/pseudo) """ if LINUX: for program in ['gksu', 'k...
def get_authentication_program():
""" Gets the authentication program used to run command as root. The function try to use one of the following programs: - gksu - kdesu - pseudo on OS X (https://github.com/sstephenson/pseudo) """ if LINUX: for program in ['gksu', 'kdesu', 'kdesudo', 'beesu']: ...
. :param program: Program to locate :return: Path of the program or None if the program could not be found. """ ret = shutil.which(program, mode, path) if ret: ret = os.path.normpath(ret) return ret def get_authentication_program():
64
64
123
6
57
fochoao/cpython
Lib/site-packages/hackedit/api/system.py
Python
get_authentication_program
get_authentication_program
82
99
82
82
90dc833d0e43da6c15cf79bbab9cf3e9b076a085
bigcode/the-stack
train
2a772ab9b708f43a0bb452b9
train
function
def get_cmd_run_command_in_terminal(use_hackedit_console=True): """ Gets a cross-platform, format string which contains the command needed for running a command in a terminal. The format string contains one placeholder for command to run. If use_hackedit_console is True, programs will run through t...
def get_cmd_run_command_in_terminal(use_hackedit_console=True):
""" Gets a cross-platform, format string which contains the command needed for running a command in a terminal. The format string contains one placeholder for command to run. If use_hackedit_console is True, programs will run through the ``heconsole`` binary, whose sole purpose is to maintain t...
-terminal']: if which(program) is not None: return '{0} {1}'.format(program, args[program]) return 'xterm -e "cd %s"' elif WINDOWS: return 'cmd.exe /k "cd /d %s"' elif DARWIN: return 'open -b com.apple.terminal %s' def get_cmd_run_command_in_terminal(use_hacke...
90
90
303
14
76
fochoao/cpython
Lib/site-packages/hackedit/api/system.py
Python
get_cmd_run_command_in_terminal
get_cmd_run_command_in_terminal
138
170
138
138
c39598a6526d28308851d188051a213b53ce683b
bigcode/the-stack
train
f6af506149b05437a487469d
train
function
def get_app_data_directory(): """ Gets the platform specific application data directory ( where we store the log file and and the python backend libraries). - GNU/Linux: ``~/.hackedit`` - OSX: ``~/Library/Application Support/HackEdit`` - WINDOWS: ``%APPDATA%\HackEdit`` :return: platform sp...
def get_app_data_directory():
""" Gets the platform specific application data directory ( where we store the log file and and the python backend libraries). - GNU/Linux: ``~/.hackedit`` - OSX: ``~/Library/Application Support/HackEdit`` - WINDOWS: ``%APPDATA%\HackEdit`` :return: platform specific data directory. """...
DESKTOP_SESSION', '') GNOME_DESKTOP = 'gnome' in os.environ.get('DESKTOP_SESSION', '') UNITY_DESKTOP = 'ubuntu' in os.environ.get('DESKTOP_SESSION', '') or \ 'unity' in os.environ.get('DESKTOP_SESSION', '') def get_app_data_directory():
63
64
198
6
57
fochoao/cpython
Lib/site-packages/hackedit/api/system.py
Python
get_app_data_directory
get_app_data_directory
26
53
26
26
ce07ad3d1c9e6cc2183ef8f3fa2f3128225fc24b
bigcode/the-stack
train
4876896e6516d482fa1dbb65
train
class
@_jcustomizer.JImplementationFor('java.lang.Thread') class _JThread(object): """ Customizer for ``java.land.Thread`` This adds addition JPype methods to java.lang.Thread to support Python. """ @staticmethod def isAttached(): """ Checks if a thread is attached to the JVM. Pytho...
@_jcustomizer.JImplementationFor('java.lang.Thread') class _JThread(object):
""" Customizer for ``java.land.Thread`` This adds addition JPype methods to java.lang.Thread to support Python. """ @staticmethod def isAttached(): """ Checks if a thread is attached to the JVM. Python automatically attaches as daemon threads when a Java method is call...
import _jpype import jpype import jpype.imports from . import _jcustomizer @_jcustomizer.JImplementationFor('java.lang.Thread') class _JThread(object):
42
147
490
19
22
baztian/jpype
jpype/_jthread.py
Python
_JThread
_JThread
7
68
7
8
7f3e63a9380257c9983cc9d43c226c3d9078c241
bigcode/the-stack
train
91b1e0a69f30944b18b4754d
train
class
@dataclass(frozen=True) class SendSticker(MessageResultMixin, Request): """\ Represents SendSticker request object: https://core.telegram.org/bots/api#sendsticker """ chat_id: Union[int, str] sticker: Union[InputFile, str] disable_notification: Optional[bool] = None protect_content: Opt...
@dataclass(frozen=True) class SendSticker(MessageResultMixin, Request):
"""\ Represents SendSticker request object: https://core.telegram.org/bots/api#sendsticker """ chat_id: Union[int, str] sticker: Union[InputFile, str] disable_notification: Optional[bool] = None protect_content: Optional[bool] = None reply_to_message_id: Optional[int] = None all...
MIT License (see LICENSE). from dataclasses import dataclass from typing import Union, Optional, List from .input_file import InputFile from .request import Request from .utils import ALL_KEYBOARDS, MessageResultMixin @dataclass(frozen=True) class SendSticker(MessageResultMixin, Request):
64
64
154
15
48
rocketbots/rocketgram
rocketgram/api/send_sticker.py
Python
SendSticker
SendSticker
14
32
14
15
856259220043d5b82922cc3be74d54e31ef85dc9
bigcode/the-stack
train
968442c4a62a613162255c4c
train
class
class Game: def __init__(self): pg.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) self.clock = pg.time.Clock() pg.key.set_repeat(500, 100) self.font = pg.font.Font(FONTTYPE, FONTSIZE) # MAIN LOOP --------------------------------------- def new(self): ...
class Game:
def __init__(self): pg.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) self.clock = pg.time.Clock() pg.key.set_repeat(500, 100) self.font = pg.font.Font(FONTTYPE, FONTSIZE) # MAIN LOOP --------------------------------------- def new(self): self.ini...
import pygame as pg from os import sys import graph as gp from settings import * class Game:
22
168
562
3
19
Saccharine-Coal/Pygame-Interactive-Graph
main.py
Python
Game
Game
9
94
9
9
309c8663ceac63b8b7fcffe869dead6ccc49b44e
bigcode/the-stack
train
3e2df804dac850a1fa468972
train
class
class EmptyItem( Item ): @classmethod def DynamicItem( cls, **kwargs ): cls.fields = { k: Field() for k in kwargs } return cls( **kwargs )
class EmptyItem( Item ): @classmethod
def DynamicItem( cls, **kwargs ): cls.fields = { k: Field() for k in kwargs } return cls( **kwargs )
from scrapy import Item, Field __all__ = [ "DynamicItem" ] class EmptyItem( Item ): @classmethod
29
64
42
11
18
Sphynx-HenryAY/scrapy-compose
scrapy_compose/items.py
Python
EmptyItem
EmptyItem
6
11
6
8
5f6f85e4817766fb42a0f5c03609ecf52a123370
bigcode/the-stack
train
02dea60d2bbc63795b78fbe5
train
function
async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) await cg.register_component(var, config) await switch.register_switch(var, config)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) await cg.register_component(var, config) await switch.register_switch(var, config)
"Restart switches do not support inverted mode!" ), cv.Optional(CONF_ICON, default=ICON_RESTART): switch.icon, cv.Optional( CONF_ENTITY_CATEGORY, default=ENTITY_CATEGORY_CONFIG ): cv.entity_category, } ).extend(cv.COMPONENT_SCHEMA) async def to_code(config):
64
64
36
6
58
OttoWinter/esphomeyaml
esphome/components/restart/switch/__init__.py
Python
to_code
to_code
30
33
30
30
fcc44a0d60d9fa94cea86425526dc67c5e838b6c
bigcode/the-stack
train
887c8d602d073e841c1b4a3c
train
class
class MyUser(AbstractUser): username = models.CharField(max_length=1000, unique=True) email = models.EmailField(max_length=255) mobno = models.BigIntegerField(unique=True) USERNAME_FIELD = 'mobno' REQUIRED_FIELDS = ['username','email'] def __str__(self): return self.email
class MyUser(AbstractUser):
username = models.CharField(max_length=1000, unique=True) email = models.EmailField(max_length=255) mobno = models.BigIntegerField(unique=True) USERNAME_FIELD = 'mobno' REQUIRED_FIELDS = ['username','email'] def __str__(self): return self.email
. cointype = ( ('BTC','BTC'), ('ETH','ETH'), ) # class EnrollUser(models.Model): # email = models.EmailField() # username = models.CharField(max_length=1000) # mobno = models.BigIntegerField() class MyUser(AbstractUser):
64
64
73
6
58
palakshivlani-11/cryptorium
crypto/models.py
Python
MyUser
MyUser
21
32
21
21
a362c573c111db901ce979c260a8bdae284ac92e
bigcode/the-stack
train
4645dad1e4383e112a56ee2e
train
class
class Notification(models.Model): us = models.ForeignKey(MyUser,on_delete=models.CASCADE) coin = models.CharField(max_length=100,choices=cointype,default='BTC') coinprice = models.BigIntegerField() class Meta: verbose_name_plural = "Tracking Notifications!"
class Notification(models.Model):
us = models.ForeignKey(MyUser,on_delete=models.CASCADE) coin = models.CharField(max_length=100,choices=cointype,default='BTC') coinprice = models.BigIntegerField() class Meta: verbose_name_plural = "Tracking Notifications!"
=1000, unique=True) email = models.EmailField(max_length=255) mobno = models.BigIntegerField(unique=True) USERNAME_FIELD = 'mobno' REQUIRED_FIELDS = ['username','email'] def __str__(self): return self.email class Notification(models.Model):
64
64
60
5
58
palakshivlani-11/cryptorium
crypto/models.py
Python
Notification
Notification
35
41
35
35
872e6d483b7a3ca7135245d49fed920fcf4f24d1
bigcode/the-stack
train
afbb83705fb463bfc8f1f35f
train
function
@Client.on_message(filters.document & check_user & filters.private) async def save_doc(client, message): chat_id = message.from_user.id start_time = time.time() downloading = await client.send_message(chat_id, 'Downloading your File!') download_location = await client.download_media( message = ...
@Client.on_message(filters.document & check_user & filters.private) async def save_doc(client, message):
chat_id = message.from_user.id start_time = time.time() downloading = await client.send_message(chat_id, 'Downloading your File!') download_location = await client.download_media( message = message, file_name = Config.DOWNLOAD_DIR+'/', progress = progress_bar, progress_ar...
name)s - %(message)s') logger = logging.getLogger(__name__) logging.getLogger("pyrogram").setLevel(logging.WARNING) import os import time from chat import Chat from config import Config from pyrogram import Client, filters from helper_func.progress_bar import progress_bar from helper_func.dbhelper import Database as ...
162
162
540
21
141
sdhtele/sub-muxer
plugins/save_file.py
Python
save_doc
save_doc
30
109
30
32
1da27fb43c93337c21477ba74ee9c6849dc4a63d
bigcode/the-stack
train
5b1da4579112e72ca944b4ae
train
function
@Client.on_message(filters.text & filters.regex('^http') & check_user) async def save_url(client, message): chat_id = message.from_user.id save_filename = None if "|" in message.text: if len(message.text.split('|')) ==2 : save_filename = message.text.split('|')[1].strip() u...
@Client.on_message(filters.text & filters.regex('^http') & check_user) async def save_url(client, message):
chat_id = message.from_user.id save_filename = None if "|" in message.text: if len(message.text.split('|')) ==2 : save_filename = message.text.split('|')[1].strip() url = message.text.split('|')[0].strip() else : url = message.text.strip() if save_filename a...
) tg_filename = os.path.basename(download_location) try: og_filename = message.video.file_name except: og_filename = False if og_filename: save_filename = og_filename else : save_filename = tg_filename ext = save_filename.split('.').pop() filename ...
195
195
651
25
170
sdhtele/sub-muxer
plugins/save_file.py
Python
save_url
save_url
169
253
169
171
892d8bb778e4c5ffd48a4d95e436bc6e678f831a
bigcode/the-stack
train
9ab2471c91f5fd22cf271ad2
train
function
@Client.on_message(filters.video & check_user & filters.private) async def save_video(client, message): chat_id = message.from_user.id start_time = time.time() downloading = await client.send_message(chat_id, 'Downloading your File!') download_location = await client.download_media( message = m...
@Client.on_message(filters.video & check_user & filters.private) async def save_video(client, message):
chat_id = message.from_user.id start_time = time.time() downloading = await client.send_message(chat_id, 'Downloading your File!') download_location = await client.download_media( message = message, file_name = Config.DOWNLOAD_DIR+'/', progress = progress_bar, progress_ar...
text = text, chat_id = chat_id, message_id = downloading.message_id ) else: text = Chat.UNSUPPORTED_FORMAT.format(ext)+f'\nFile = {tg_filename}' await client.edit_message_text( text = text, chat_id = chat_id, message_id = download...
104
104
348
21
83
sdhtele/sub-muxer
plugins/save_file.py
Python
save_video
save_video
112
166
112
114
52184bb27352f245eae1786670a7aa62b40f9ff0
bigcode/the-stack
train
044012e0c3b98a6a310f7153
train
function
async def _check_user(filt, c, m): chat_id = str(m.from_user.id) if chat_id in Config.ALLOWED_USERS: return True else : return False
async def _check_user(filt, c, m):
chat_id = str(m.from_user.id) if chat_id in Config.ALLOWED_USERS: return True else : return False
from config import Config from pyrogram import Client, filters from helper_func.progress_bar import progress_bar from helper_func.dbhelper import Database as Db import re import requests from urllib.parse import quote, unquote db = Db() async def _check_user(filt, c, m):
64
64
43
12
52
sdhtele/sub-muxer
plugins/save_file.py
Python
_check_user
_check_user
21
26
21
21
e60bb3437023db5f89e50681064c58c449644236
bigcode/the-stack
train
87fff25d2491c2643a588029
train
function
def _filter_none(item): return list(list(filter(None, item)))
def _filter_none(item):
return list(list(filter(None, item)))
(n, iterable, fillvalue=None): """ _grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n return itertools.zip_longest(fillvalue=fillvalue, *args) def _filter_none(item):
64
64
15
6
58
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
_filter_none
_filter_none
99
100
99
99
535c2e7538fded66b08caf41e6f1f314116fe14d
bigcode/the-stack
train
0dedb5e2c6192b477768987a
train
function
def _split_q(q): q_list = re.split(r'\s+', q) if q_list[0]: return q_list return []
def _split_q(q):
q_list = re.split(r'\s+', q) if q_list[0]: return q_list return []
self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = HTMLStripper() s.feed(html) return s.get_data() def _split_q(q):
64
64
33
6
58
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
_split_q
_split_q
36
40
36
36
022c27efadc62a9dc1f2da94ee96d609c0894c92
bigcode/the-stack
train
28f58336b5cc132e3f276cb7
train
function
def _grouper(n, iterable, fillvalue=None): """ _grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n return itertools.zip_longest(fillvalue=fillvalue, *args)
def _grouper(n, iterable, fillvalue=None):
""" _grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n return itertools.zip_longest(fillvalue=fillvalue, *args)
_item(i, 'books') for i in document_list] results_list = document_results count = 1 for item in results_list: item['order'] = count count += 1 return results_list def _grouper(n, iterable, fillvalue=None):
64
64
63
13
50
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
_grouper
_grouper
91
96
91
91
83525f3f17a9872a85d04fe318bd948a0027e8b1
bigcode/the-stack
train
4dbc2b4ed83f0702a46a12c1
train
function
def _search_documents(query_list): by_title = reduce( operator.or_, (Q(title__icontains=q) for q in query_list)) by_description = reduce( operator.or_, (Q(description__icontains=q) for q in query_list)) queries = Q() queries.add(by_title, Q.OR) queries.add(by_description, Q.OR) ...
def _search_documents(query_list):
by_title = reduce( operator.or_, (Q(title__icontains=q) for q in query_list)) by_description = reduce( operator.or_, (Q(description__icontains=q) for q in query_list)) queries = Q() queries.add(by_title, Q.OR) queries.add(by_description, Q.OR) return Document.published_objects....
def strip_tags(html): s = HTMLStripper() s.feed(html) return s.get_data() def _split_q(q): q_list = re.split(r'\s+', q) if q_list[0]: return q_list return [] def _search_documents(query_list):
63
64
88
7
56
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
_search_documents
_search_documents
43
53
43
43
3df23ff9235cc0af55bb20e9c937c14a5f806fa3
bigcode/the-stack
train
21e1ed6899325ad502101a45
train
function
def _search_item(item_dict, section): title = '' snippet = '' if section == 'books': title = item_dict['title'] snippet = item_dict['description'] elif section == 'publications': title = item_dict['headline'] snippet = item_dict['text'] return dict( id=item_...
def _search_item(item_dict, section):
title = '' snippet = '' if section == 'books': title = item_dict['title'] snippet = item_dict['description'] elif section == 'publications': title = item_dict['headline'] snippet = item_dict['text'] return dict( id=item_dict['id'], title=title, ...
_description = reduce( operator.or_, (Q(description__icontains=q) for q in query_list)) queries = Q() queries.add(by_title, Q.OR) queries.add(by_description, Q.OR) return Document.published_objects.filter(queries) def _search_item(item_dict, section):
64
64
97
9
55
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
_search_item
_search_item
56
72
56
56
be53fd89b5755aaf0d76ea52f0a0afb4d1ec8a5d
bigcode/the-stack
train
b2fd8abbe4cc8d99c90f3abe
train
function
def _search(query_str): query_list = _split_q(query_str) document_list = list( _search_documents(query_list).values('id', 'title', 'description')) document_results = [_search_item(i, 'books') for i in document_list] results_list = document_results count = 1 for item in results_list: ...
def _search(query_str):
query_list = _split_q(query_str) document_list = list( _search_documents(query_list).values('id', 'title', 'description')) document_results = [_search_item(i, 'books') for i in document_list] results_list = document_results count = 1 for item in results_list: item['order'] = c...
'] elif section == 'publications': title = item_dict['headline'] snippet = item_dict['text'] return dict( id=item_dict['id'], title=title, snippet=strip_tags(snippet[:200]), section=section ) def _search(query_str):
64
64
96
6
58
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
_search
_search
75
88
75
75
0aa82aaff8993d739086a6457f88fbd5f0442b1a
bigcode/the-stack
train
0a278f0d68cf464b79023de0
train
function
def strip_tags(html): s = HTMLStripper() s.feed(html) return s.get_data()
def strip_tags(html):
s = HTMLStripper() s.feed(html) return s.get_data()
def __init__(self): self.reset() self.strict = False self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html):
64
64
23
5
59
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
strip_tags
strip_tags
30
33
30
30
90c990cdba9cc3cde624904eae8f023f4e2f467c
bigcode/the-stack
train
e03355ed3342e1b12fb68dc2
train
function
def searcher(query_str, request): page_size = settings.REST_FRAMEWORK['PAGE_SIZE'] results_list = _search(query_str) total_count = len(results_list) page = int(request.query_params.get('page', 1)) paginator = Pagination(page, page_size, total_count, request) data = [_filter_none(i) for i in _g...
def searcher(query_str, request):
page_size = settings.REST_FRAMEWORK['PAGE_SIZE'] results_list = _search(query_str) total_count = len(results_list) page = int(request.query_params.get('page', 1)) paginator = Pagination(page, page_size, total_count, request) data = [_filter_none(i) for i in _grouper(page_size, results_list)] ...
'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n return itertools.zip_longest(fillvalue=fillvalue, *args) def _filter_none(item): return list(list(filter(None, item))) def searcher(query_str, request):
63
64
190
8
55
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
searcher
searcher
103
124
103
103
39ec55ba4e496c4419a8c593ffc963e8bef775d4
bigcode/the-stack
train
69587c8323ae07b8e1b7e259
train
class
class HTMLStripper(HTMLParser): def __init__(self): self.reset() self.strict = False self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed)
class HTMLStripper(HTMLParser):
def __init__(self): self.reset() self.strict = False self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed)
import itertools from functools import reduce from html.parser import HTMLParser from collections import OrderedDict from django.db.models import Q from django.conf import settings from rest_framework.response import Response from documents.models import Document from .paginators import Pagination class HTMLStripper...
64
64
68
8
55
Bibliotecaio/biblioteca
api/apps/search/utils.py
Python
HTMLStripper
HTMLStripper
16
27
16
16
5d860ca4d77ce744192fb76505618190fc45621a
bigcode/the-stack
train
e4138d2a5a7b2f3e73447f9c
train
class
class test(object): pass
class test(object):
pass
from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap ## 3rd Party Imports from redbaron import RedBaron as RB from gpi.helpers import astHelpers, dialogs from gpi.widgets import standardWidgets # find script directory class test(object):
64
64
7
4
59
jaredtay/gpi
gpi/view.py
Python
test
test
21
22
21
21
0f8a560e5c7e7055f9e89e8454708ce73a575708
bigcode/the-stack
train
e06a89e957812e4895676229
train
class
class view(QWidget): ast = None fileName = None # fileChanged = False def __init__( self , statusBar): QWidget.__init__(self) scriptdir=os.path.abspath(os.path.split(sys.modules[test.__module__].__file__)[0]) # Main View mainLayout = QVBoxLayout() s...
class view(QWidget):
ast = None fileName = None # fileChanged = False def __init__( self , statusBar): QWidget.__init__(self) scriptdir=os.path.abspath(os.path.split(sys.modules[test.__module__].__file__)[0]) # Main View mainLayout = QVBoxLayout() self.setLayout(mainLay...
#! /usr/bin/python3 ## Pure Python Imports import os import sys import traceback ## PyQt5 Imports from PyQt5.QtWidgets import QWidget, QVBoxLayout, QScrollArea, QLabel , QFileDialog from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap ## 3rd Party Imports from redbaron import RedBaron as RB from gpi.helpers ...
125
256
1,030
4
121
jaredtay/gpi
gpi/view.py
Python
view
view
25
184
25
25
e0e55114a12a2febf1815968c24f4d0339c74059
bigcode/the-stack
train
7b8720a8b3bbdc372b8fbae0
train
class
class TestLevelFiveActions(unittest.TestCase): matchmaking_mock = { "network": "eth", "funded": True, "broadcastInterval": 2, "interchainWallet": "0xwallet", "wallet": "0xWallet", "ddss": "5000", } fake_l5_block = { "version": "1", "dcrn": "Blo...
class TestLevelFiveActions(unittest.TestCase):
matchmaking_mock = { "network": "eth", "funded": True, "broadcastInterval": 2, "interchainWallet": "0xwallet", "wallet": "0xWallet", "ddss": "5000", } fake_l5_block = { "version": "1", "dcrn": "Block::L5::AtRest", "header": {"dc_id": "2...
compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except...
256
256
6,497
9
246
deanshelton913/dragonchain
dragonchain/transaction_processor/level_5_actions_utest.py
Python
TestLevelFiveActions
TestLevelFiveActions
28
527
28
28
efd97d7872ab0796217e740d514a412a23914389
bigcode/the-stack
train
7bbcafcd513cb1f4bc1e0a91
train
function
def img_to_base64_html(file_name__or__bytes__or__file_object): arg = file_name__or__bytes__or__file_object if type(arg) == str: with open(arg, mode='rb') as f: img_bytes = f.read() elif type(arg) == bytes: img_bytes = arg else: img_bytes = arg.read() bytes_io ...
def img_to_base64_html(file_name__or__bytes__or__file_object):
arg = file_name__or__bytes__or__file_object if type(arg) == str: with open(arg, mode='rb') as f: img_bytes = f.read() elif type(arg) == bytes: img_bytes = arg else: img_bytes = arg.read() bytes_io = io.BytesIO(img_bytes) img = Image.open(bytes_io) img...
'blur': blur, 'blur5': lambda img: blur(img, 5) } # SOURCE: https://github.com/gil9red/SimplePyScripts/blob/master/img_to_base64_html/main.py def img_to_base64_html(file_name__or__bytes__or__file_object):
64
64
149
18
45
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
img_to_base64_html
img_to_base64_html
38
57
38
38
ee3b458e893a31b4f2ab58ab217037f87956806d
bigcode/the-stack
train
f64d41822f31ab737b34f050
train
function
@app.route("/upload_file", methods=['POST']) def upload_file(): print(request.files) # check if the post request has the file part if 'file' not in request.files: return redirect('/') file = request.files['file'] file_data = file.stream.read() save_last_image(file_data) return js...
@app.route("/upload_file", methods=['POST']) def upload_file():
print(request.files) # check if the post request has the file part if 'file' not in request.files: return redirect('/') file = request.files['file'] file_data = file.stream.read() save_last_image(file_data) return jsonify({ 'img_original': img_to_base64_html(file_data), ...
progress', progress, false); } return myXhr; }, success: on_success, }); return false; }); }); </script> </body> </html> ''', commands=COMMANDS) @app.route("/upload_...
64
64
95
14
50
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
upload_file
upload_file
285
301
285
286
bc6b62cd71d50a72c795aa536e1a27b95d69ce58
bigcode/the-stack
train
c410f2dd83b1e19db395685d
train
function
def load_last_image(): with open(LAST_IMAGE, 'rb') as f: return f.read()
def load_last_image():
with open(LAST_IMAGE, 'rb') as f: return f.read()
improvement on the cost of cacheability. app.config['JSON_SORT_KEYS'] = False logging.basicConfig(level=logging.DEBUG) LAST_IMAGE = 'last_image.jpg' def save_last_image(file_data): with open(LAST_IMAGE, 'wb') as f: f.write(file_data) def load_last_image():
64
64
23
5
59
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
load_last_image
load_last_image
80
82
80
80
736b66349c9d728d0231b3f3ab2fc4a48d52d9e8
bigcode/the-stack
train
826c52c0c5f50c7d8e4ee85b
train
function
@app.route("/image_process", methods=['POST']) def image_process(): print(request.form) command = request.form['command'] img_original = load_last_image() data_io = io.BytesIO(img_original) img = Image.open(data_io).convert('RGB') # Получение и вызов функции result = COMMANDS[command](img)...
@app.route("/image_process", methods=['POST']) def image_process():
print(request.form) command = request.form['command'] img_original = load_last_image() data_io = io.BytesIO(img_original) img = Image.open(data_io).convert('RGB') # Получение и вызов функции result = COMMANDS[command](img) data_io = io.BytesIO() result.save(data_io, 'JPEG') i...
url = request.form['url'] file_data = requests.get(url).content save_last_image(file_data) return jsonify({ 'img_original': img_to_base64_html(file_data), 'img_process': None, }) @app.route("/image_process", methods=['POST']) def image_process():
64
64
134
14
50
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
image_process
image_process
322
342
322
323
daf75ff36e5d4be0cd658da2d96bd4a368d83637
bigcode/the-stack
train
bd546de7c12624a3e0c63db3
train
function
def save_last_image(file_data): with open(LAST_IMAGE, 'wb') as f: f.write(file_data)
def save_last_image(file_data):
with open(LAST_IMAGE, 'wb') as f: f.write(file_data)
. You can override the default behavior by changing this variable. This is not recommended but might give # you a performance improvement on the cost of cacheability. app.config['JSON_SORT_KEYS'] = False logging.basicConfig(level=logging.DEBUG) LAST_IMAGE = 'last_image.jpg' def save_last_image(file_data):
64
64
26
7
57
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
save_last_image
save_last_image
75
77
75
75
ac6c110cb426cf2cc7d2e0f02d86405d66febb5e
bigcode/the-stack
train
ffcbfa02cbac3810fcdcaa04
train
function
@app.route("/upload_url", methods=['POST']) def upload_url(): print(request.form) if 'url' not in request.form: return redirect('/') url = request.form['url'] file_data = requests.get(url).content save_last_image(file_data) return jsonify({ 'img_original': img_to_base64_html(...
@app.route("/upload_url", methods=['POST']) def upload_url():
print(request.form) if 'url' not in request.form: return redirect('/') url = request.form['url'] file_data = requests.get(url).content save_last_image(file_data) return jsonify({ 'img_original': img_to_base64_html(file_data), 'img_process': None, })
') file = request.files['file'] file_data = file.stream.read() save_last_image(file_data) return jsonify({ 'img_original': img_to_base64_html(file_data), 'img_process': None, }) @app.route("/upload_url", methods=['POST']) def upload_url():
64
64
85
14
50
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
upload_url
upload_url
304
319
304
305
f6398f64197a2a72e4ef47f671b750b6996d30ab
bigcode/the-stack
train
97288ab653c87e5b73a2722d
train
function
@app.route('/') def index(): return render_template_string('''\ <html> <head> <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/> <title>get_upload_and_image_process</title> <script type="text/javascript" src="{{ url_for('static', filename='js/jquery-3.1.1.min.js') }}">...
@app.route('/') def index():
return render_template_string('''\ <html> <head> <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/> <title>get_upload_and_image_process</title> <script type="text/javascript" src="{{ url_for('static', filename='js/jquery-3.1.1.min.js') }}"></script> </head...
img_bytes = arg.read() bytes_io = io.BytesIO(img_bytes) img = Image.open(bytes_io) img_base64 = base64.b64encode(img_bytes).decode('utf-8') # print(img_base64) return 'data:image/{};base64,'.format(img.format.lower()) + img_base64 app = Flask(__name__) # http://flask.pocoo.org/docs/0.12/confi...
256
256
1,361
6
250
gil9red/SimplePyScripts
flask__webservers/get_upload_and_image_process/main.py
Python
index
index
85
282
85
86
017fef1a67f52155ac7502528e186200ef4e8e99
bigcode/the-stack
train
730494eb3c77454f2accdecb
train
function
def load_dataset(dataset): info = OrderedDict() if 'VOT' in dataset: base_path = join(realpath(dirname(__file__)), '../data', dataset) if not exists(base_path): logging.error("Please download test dataset!!!") exit() list_path = join(base_path, 'list.txt') ...
def load_dataset(dataset):
info = OrderedDict() if 'VOT' in dataset: base_path = join(realpath(dirname(__file__)), '../data', dataset) if not exists(base_path): logging.error("Please download test dataset!!!") exit() list_path = join(base_path, 'list.txt') with open(list_path) as f:...
# -------------------------------------------------------- # SiamMask # Licensed under The MIT License # Written by Qiang Wang (wangqiang2015 at ia.ac.cn) # -------------------------------------------------------- from os.path import join, realpath, dirname, exists, isdir from os import listdir import logging import gl...
199
247
825
5
194
RJT1990/SiamMask
utils/benchmark_helper.py
Python
load_dataset
load_dataset
34
97
34
34
b907d47700fc21d2920b11df48ac987c09b4b82b
bigcode/the-stack
train
33358a3638b64db603a7a7fb
train
function
def get_dataset_zoo(): root = realpath(join(dirname(__file__), '../data')) zoos = listdir(root) def valid(x): y = join(root, x) if not isdir(y): return False return exists(join(y, 'list.txt')) \ or exists(join(y, 'train', 'meta.json'))\ or exists(join(...
def get_dataset_zoo():
root = realpath(join(dirname(__file__), '../data')) zoos = listdir(root) def valid(x): y = join(root, x) if not isdir(y): return False return exists(join(y, 'list.txt')) \ or exists(join(y, 'train', 'meta.json'))\ or exists(join(y, 'ImageSets', '2016',...
iang Wang (wangqiang2015 at ia.ac.cn) # -------------------------------------------------------- from os.path import join, realpath, dirname, exists, isdir from os import listdir import logging import glob import numpy as np import json from collections import OrderedDict def get_dataset_zoo():
64
64
109
6
57
RJT1990/SiamMask
utils/benchmark_helper.py
Python
get_dataset_zoo
get_dataset_zoo
15
28
15
15
7fcf6dc2e8ac4664f340870aff1985dca6f4712e
bigcode/the-stack
train
ad359979b78c71c58844f70f
train
class
class SearchScope: """ Encapsulates the locations that pip is configured to search. """ __slots__ = ["find_links", "index_urls"] @classmethod def create( cls, find_links, # type: List[str] index_urls, # type: List[str] ): # type: (...) -> SearchScope ...
class SearchScope:
""" Encapsulates the locations that pip is configured to search. """ __slots__ = ["find_links", "index_urls"] @classmethod def create( cls, find_links, # type: List[str] index_urls, # type: List[str] ): # type: (...) -> SearchScope """ Crea...
import itertools import logging import os import posixpath import urllib.parse from typing import List from pip._vendor.packaging.utils import canonicalize_name from pip._internal.models.index import PyPI from pip._internal.utils.compat import has_tls from pip._internal.utils.misc import normalize_path, redact_auth_f...
82
256
877
4
78
GinaJame/Portfolio_MLH
python3-virtualenv/lib/python3.6/site-packages/pip/_internal/models/search_scope.py
Python
SearchScope
SearchScope
17
134
17
18
a1781ba4a9206104117fdf28abdbf395cb8053a1
bigcode/the-stack
train
e56915d0dc95f64971b1e58d
train
class
class SawyerReachXYEnv(SawyerReachXYZEnv): def __init__(self, *args, fixed_goal=(0.15, 0.6), hand_z_position=0.055, **kwargs): self.quick_init(locals()) SawyerReachXYZEnv.__init__( self, *args, fixed_goal=(fixed_goal[0], fixed_goa...
class SawyerReachXYEnv(SawyerReachXYZEnv):
def __init__(self, *args, fixed_goal=(0.15, 0.6), hand_z_position=0.055, **kwargs): self.quick_init(locals()) SawyerReachXYZEnv.__init__( self, *args, fixed_goal=(fixed_goal[0], fixed_goal[1], hand_z_position), **kwarg...
_stats=True, )) return statistics def get_env_state(self): base_state = super().get_env_state() goal = self._state_goal.copy() return base_state, goal def set_env_state(self, state): base_state, goal = state super().set_env_state(base_state) ...
96
96
322
12
84
Neo-X/R_multiworld
multiworld/envs/mujoco/sawyer_xyz/sawyer_reach.py
Python
SawyerReachXYEnv
SawyerReachXYEnv
216
248
216
216
e6862d67f6d66e182a3f206cbe7c4118eb211e53
bigcode/the-stack
train
37168d4ea6da727a1ba36963
train
class
class SawyerReachXYZEnv(SawyerXYZEnv, MultitaskEnv): def __init__( self, reward_type='hand_distance', indicator_threshold=0.06, fix_goal=False, fixed_goal=(0.15, 0.6, 0.3), goal_low=None, goal_high=None, hide_goal_mark...
class SawyerReachXYZEnv(SawyerXYZEnv, MultitaskEnv):
def __init__( self, reward_type='hand_distance', indicator_threshold=0.06, fix_goal=False, fixed_goal=(0.15, 0.6, 0.3), goal_low=None, goal_high=None, hide_goal_markers=False, **kwargs ): self....
from collections import OrderedDict import numpy as np from gym.spaces import Box, Dict from multiworld.envs.env_util import get_stat_in_paths, \ create_stats_ordered_dict, get_asset_full_path from multiworld.core.multitask_env import MultitaskEnv from multiworld.envs.mujoco.sawyer_xyz.base import SawyerXYZEnv cla...
94
256
1,571
16
77
Neo-X/R_multiworld
multiworld/envs/mujoco/sawyer_xyz/sawyer_reach.py
Python
SawyerReachXYZEnv
SawyerReachXYZEnv
11
213
11
11
bb7c4d9e6680dd42ef6ebac535039c441591fe6b
bigcode/the-stack
train
85999a9ac57ae5d2b818b2e5
train
function
@app.route("/google/success") def after_google(): """ This just renders a confirmation page, to let the user know that they've successfully connected to Google and need to move on to the next step: passing those authentication credentials to Nylas. """ return render_template("after_google.html")...
@app.route("/google/success") def after_google():
""" This just renders a confirmation page, to let the user know that they've successfully connected to Google and need to move on to the next step: passing those authentication credentials to Nylas. """ return render_template("after_google.html")
"], ) # We'll use the Nylas client to fetch information from Nylas # about the current user, and pass that to the template. account = client.account return render_template("after_connected.html", account=account) @app.route("/google/success") def after_google():
64
64
66
11
53
sanketsaurav/nylas-python
examples/native-authentication-gmail/server.py
Python
after_google
after_google
126
133
126
127
571721f45572119dcb362d84d67f17406c8bc75a
bigcode/the-stack
train
0f70eaaf1777002020033786
train
function
@app.route("/nylas/connect") def pass_creds_to_nylas(): """ This view loads the credentials from Google and passes them to Nylas, to set up native authentication. """ # If you haven't already connected with Google, this won't work. if not google.authorized: return "Error: not yet connect...
@app.route("/nylas/connect") def pass_creds_to_nylas():
""" This view loads the credentials from Google and passes them to Nylas, to set up native authentication. """ # If you haven't already connected with Google, this won't work. if not google.authorized: return "Error: not yet connected with Google!", 400 if "refresh_token" not in goo...
user has already connected # to both Google and Nylas. # Let's set up the SDK client with the OAuth token: client = APIClient( app_id=app.config["NYLAS_OAUTH_CLIENT_ID"], app_secret=app.config["NYLAS_OAUTH_CLIENT_SECRET"], access_token=session["nylas_access_token"], ) # We'...
206
206
688
16
190
sanketsaurav/nylas-python
examples/native-authentication-gmail/server.py
Python
pass_creds_to_nylas
pass_creds_to_nylas
136
202
136
137
97f04fe657342ee5a194a87f60919d990f55d1f1
bigcode/the-stack
train
6db3808c1305f13df9fa0507
train
function
def ngrok_url(): """ If ngrok is running, it exposes an API on port 4040. We can use that to figure out what URL it has assigned, and suggest that to the user. https://ngrok.com/docs#list-tunnels """ try: ngrok_resp = requests.get("http://localhost:4040/api/tunnels") except requests....
def ngrok_url():
""" If ngrok is running, it exposes an API on port 4040. We can use that to figure out what URL it has assigned, and suggest that to the user. https://ngrok.com/docs#list-tunnels """ try: ngrok_resp = requests.get("http://localhost:4040/api/tunnels") except requests.ConnectionError: ...
use it when we need it. session["nylas_access_token"] = nylas_access_token # We're all done here. Redirect the user back to the home page, # which will pick up the access token we just saved. return redirect(url_for("index")) def ngrok_url():
63
64
151
5
58
sanketsaurav/nylas-python
examples/native-authentication-gmail/server.py
Python
ngrok_url
ngrok_url
205
222
205
205
12bccbd9055b4cf6a58abacc742e3b7dfad3f7b6
bigcode/the-stack
train
a6d1a5471dad8b3e21d852c5
train
function
@app.route("/") def index(): # If the user has already connected to Google via OAuth, # `google.authorized` will be True. We also need to be sure that # we have a refresh token from Google. If we don't have both of those, # that indicates that we haven't correctly connected with Google. if not (goog...
@app.route("/") def index(): # If the user has already connected to Google via OAuth, # `google.authorized` will be True. We also need to be sure that # we have a refresh token from Google. If we don't have both of those, # that indicates that we haven't correctly connected with Google.
if not (google.authorized and "refresh_token" in google.token): # Google requires HTTPS. The template will display a handy warning, # unless we've overridden the check. return render_template( "before_google.html", insecure_override=os.environ.get("OAUTHLIB_INSECURE_T...
rok proxy app.wsgi_app = ProxyFix(app.wsgi_app) # Define what Flask should do when someone visits the root URL of this website. @app.route("/") def index(): # If the user has already connected to Google via OAuth, # `google.authorized` will be True. We also need to be sure that # we have a refresh token fr...
99
99
331
68
31
sanketsaurav/nylas-python
examples/native-authentication-gmail/server.py
Python
index
index
91
123
91
96
f723898e44652125a45b16e0f3b507245e823f94
bigcode/the-stack
train
88633708afdd985f79c157ce
train
function
@admin_required def setup(request, *args, **kwargs): return HttpResponse(Page( h2("Setup", cls="page-title"), Card("Problems", "Create problems to go in the contests", "/problems_mgmt"), Card("Contests", "Create contests", "/contests"), Card("Users", "Create users who will participat...
@admin_required def setup(request, *args, **kwargs):
return HttpResponse(Page( h2("Setup", cls="page-title"), Card("Problems", "Create problems to go in the contests", "/problems_mgmt"), Card("Contests", "Create contests", "/contests"), Card("Users", "Create users who will participate in contests, as well as other admin users who can c...
from django.http import HttpResponse from uuid import uuid4 from contest.auth import admin_required from contest.pages.lib.htmllib import UIElement, div, h, h2, h1 from contest.pages.lib.page import Page, Card @admin_required def setup(request, *args, **kwargs):
64
64
99
14
49
MBRUN138/open-contest
opencontest/contest/pages/static.py
Python
setup
setup
10
17
10
11
cf26b14f362785bcf149be76e55b5f0df92ea24b
bigcode/the-stack
train
19c92036d04f9b4762ef850b
train
function
def faqs(request): return HttpResponse(Page( h2("FAQs", cls="page-title"), FAQ("What is a programming contest?", """A programming contest is a contest where programmers attempt to solve problems by writing programs. These problems are typically posed as a problem statement ...
def faqs(request):
return HttpResponse(Page( h2("FAQs", cls="page-title"), FAQ("What is a programming contest?", """A programming contest is a contest where programmers attempt to solve problems by writing programs. These problems are typically posed as a problem statement to describe the pro...
data you submit, " + "including your name (which the organizers provide) and any code submissions, which they may use for any purpose."), Card("Data collected", div( h.span("OpenContest collects the following data:"), h.ul( h.li("You...
256
256
1,390
5
250
MBRUN138/open-contest
opencontest/contest/pages/static.py
Python
faqs
faqs
100
177
100
100
7db642945b018e680bc8d9bdf66a32eb0e379fce
bigcode/the-stack
train
88a436cd9d004308e41158ff
train
function
def privacy(request): return HttpResponse(Page( h2("Privacy Policy", cls="page-title"), Card("TL;DR", "OpenContest as an organization is too lazy to steal your data (we're busy enough keeping track of our own). " + "However, the organizers of your contest may collect any data you submit...
def privacy(request):
return HttpResponse(Page( h2("Privacy Policy", cls="page-title"), Card("TL;DR", "OpenContest as an organization is too lazy to steal your data (we're busy enough keeping track of our own). " + "However, the organizers of your contest may collect any data you submit, " + "in...
>Caedmon Evans improved the judge diff view and made several other enhancements.</li> </ul> """) )) # Fake privacy policy for laughs def fake_privacy(request): return HttpResponse(Page( h2("Privacy Policy", cls="page-title"), h1("LOL", cls="jumbotron center"), h1("After...
92
93
310
4
88
MBRUN138/open-contest
opencontest/contest/pages/static.py
Python
privacy
privacy
66
96
66
66
c2c69f61b86b3209b08eff8b78cbef3a7131b1cf
bigcode/the-stack
train
ef9ca2992174c660d6d7b4a3
train
function
def fake_privacy(request): return HttpResponse(Page( h2("Privacy Policy", cls="page-title"), h1("LOL", cls="jumbotron center"), h1("After all, you use Facebook", cls="center") ))
def fake_privacy(request):
return HttpResponse(Page( h2("Privacy Policy", cls="page-title"), h1("LOL", cls="jumbotron center"), h1("After all, you use Facebook", cls="center") ))
li> <li>Heather East Duke ported the system to the Django framework.</li> <li>Caedmon Evans improved the judge diff view and made several other enhancements.</li> </ul> """) )) # Fake privacy policy for laughs def fake_privacy(request):
64
64
53
6
57
MBRUN138/open-contest
opencontest/contest/pages/static.py
Python
fake_privacy
fake_privacy
58
63
58
58
9a9e5e47a4a9b7dbfae13e018aad3082f8ca13a3
bigcode/the-stack
train
892be14f949ec58c68283280
train
class
class FAQ(UIElement): def __init__(self, q, a): id = str(uuid4()) self.html = div( h.h4(q, cls="qa-question collapsed", **{"data-toggle": "collapse", "data-target": f"#qa-{id}"}), div(a, id=f"qa-{id}", cls="collapse"), cls="faq" )
class FAQ(UIElement):
def __init__(self, q, a): id = str(uuid4()) self.html = div( h.h4(q, cls="qa-question collapsed", **{"data-toggle": "collapse", "data-target": f"#qa-{id}"}), div(a, id=f"qa-{id}", cls="collapse"), cls="faq" )
in the contests", "/problems_mgmt"), Card("Contests", "Create contests", "/contests"), Card("Users", "Create users who will participate in contests, as well as other admin users who can create and judge contests and problems", "/users") )) class FAQ(UIElement):
63
64
82
5
58
MBRUN138/open-contest
opencontest/contest/pages/static.py
Python
FAQ
FAQ
20
27
20
20
ef46b356af187ed3fd6a9b251aac4c3168f0d3d9
bigcode/the-stack
train
fd19f74131a8131419b98746
train
function
def about(request): return HttpResponse(Page( h2("About", cls="page-title"), Card("The Creator", """ OpenContest was written by Nathan Collins, a senior computer science student at BJU, as an independent study project in the fall of 2018. """), Card("Enhancements", ""...
def about(request):
return HttpResponse(Page( h2("About", cls="page-title"), Card("The Creator", """ OpenContest was written by Nathan Collins, a senior computer science student at BJU, as an independent study project in the fall of 2018. """), Card("Enhancements", """ Dr. Schaub...
users") )) class FAQ(UIElement): def __init__(self, q, a): id = str(uuid4()) self.html = div( h.h4(q, cls="qa-question collapsed", **{"data-toggle": "collapse", "data-target": f"#qa-{id}"}), div(a, id=f"qa-{id}", cls="collapse"), cls="faq" ) def abou...
91
91
305
4
87
MBRUN138/open-contest
opencontest/contest/pages/static.py
Python
about
about
30
54
30
30
592303e3b7472a9f31220f146cb7f6f64cf454a5
bigcode/the-stack
train
a8c0ecd8f786e6a54a2c55cd
train
function
def vis_detections(im, class_name, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return im = im[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(im, aspect='equal') for i in inds: bbox =...
def vis_detections(im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return im = im[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(im, aspect='equal') for i in inds: bbox = dets[i, :4] score = dets[i, -1] ax.a...
',), 'res101': ('res101_faster_rcnn_iter_110000.ckpt',)} DATASETS = {'pascal_voc': ('voc_2007_trainval',), 'pascal_voc_0712': ('voc_2007_trainval+voc_2012_trainval',)} def vis_detections(im, class_name, dets, thresh=0.5):
83
84
281
19
64
Linby1103/Faster-Rcnn
demo.py
Python
vis_detections
vis_detections
43
73
43
43
8b0c94aa08d3a15bb158785d6105b98144be827b
bigcode/the-stack
train
b63cc3f6c92600a0ae24e615
train
function
def SignalImage_Test(sess, net,image_path): im=cv2.imread(image_path) timer = Timer() timer.tic() scores, boxes = im_detect(sess, net, im) timer.toc() print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0])) # Visualize detections for each class ...
def SignalImage_Test(sess, net,image_path):
im=cv2.imread(image_path) timer = Timer() timer.tic() scores, boxes = im_detect(sess, net, im) timer.toc() print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0])) # Visualize detections for each class CONF_THRESH = 0.4 NMS_THRESH = 0.35 ...
choices=NETS.keys(), default='res101') parser.add_argument('--dataset', dest='dataset', help='Trained dataset [pascal_voc pascal_voc_0712]', choices=DATASETS.keys(), default='pascal_voc_0712') args = parser.parse_args() return args def SignalImage_Test(sess, ...
79
79
264
10
68
Linby1103/Faster-Rcnn
demo.py
Python
SignalImage_Test
SignalImage_Test
115
145
115
116
8bd7fa403ab3a469fdcb8b3e5722aee73300b30b
bigcode/the-stack
train
be8181b25fcf86b931b1729c
train
function
def demo(sess, net, image_name): """Detect object classes in an image using pre-computed object proposals.""" # Load the demo image im_file = os.path.join(cfg.FLAGS2["data_dir"], 'demo', image_name) im = cv2.imread(im_file) # Detect all object classes and regress object bounds timer = Timer() ...
def demo(sess, net, image_name):
"""Detect object classes in an image using pre-computed object proposals.""" # Load the demo image im_file = os.path.join(cfg.FLAGS2["data_dir"], 'demo', image_name) im = cv2.imread(im_file) # Detect all object classes and regress object bounds timer = Timer() timer.tic() scores, boxes...
color='blue', alpha=0.5), fontsize=14, color='white') ax.set_title(('{} detections with ' 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh), fontsize=14) plt.axis('off') plt.tight_layout() ...
82
82
276
9
73
Linby1103/Faster-Rcnn
demo.py
Python
demo
demo
76
101
76
76
8d62ddbb1bf7ad830b948743abd14d2ce51df6dc
bigcode/the-stack
train
6da38d428a6418c5cb706587
train
function
def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN demo') parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16 res101]', choices=NETS.keys(), default='res101') parser.add_argument('--dataset', ...
def parse_args():
"""Parse input arguments.""" parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN demo') parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16 res101]', choices=NETS.keys(), default='res101') parser.add_argument('--dataset', dest='dataset', he...
= np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32) keep = nms(dets, NMS_THRESH) dets = dets[keep, :] vis_detections(im, cls, dets, thresh=CONF_THRESH) def parse_args():
64
64
119
4
60
Linby1103/Faster-Rcnn
demo.py
Python
parse_args
parse_args
104
113
104
104
cd6e4d747096279826ee1b9078b40f7b93c9b272
bigcode/the-stack
train
1c73faf3003f8da88bf926f0
train
class
class TestCommonArchive(AiidaTestCase): """Tests for the :py:class:`~aiida.common.archive.Archive` class.""" def test_context_required(self): """Verify that accessing a property of an Archive outside of a context manager raises.""" with self.assertRaises(InvalidOperation): filepath ...
class TestCommonArchive(AiidaTestCase):
"""Tests for the :py:class:`~aiida.common.archive.Archive` class.""" def test_context_required(self): """Verify that accessing a property of an Archive outside of a context manager raises.""" with self.assertRaises(InvalidOperation): filepath = get_archive_file('export_v0.1_simple.a...
division from __future__ import print_function from __future__ import absolute_import from aiida.backends.testbase import AiidaTestCase from aiida.common.archive import Archive, CorruptArchive from aiida.common.exceptions import InvalidOperation from aiida.backends.tests.utils.archives import get_archive_file class T...
74
74
249
10
63
PercivalN/aiida-core
aiida/backends/tests/common/test_archive.py
Python
TestCommonArchive
TestCommonArchive
21
42
21
21
465e327d4f5b4cd818a014154195e95b3530dbbe
bigcode/the-stack
train