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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ac50fc8ee863147bc6608f36 | train | function | def vectorize_candidates(candidates, word_idx, sentence_size):
shape = (len(candidates), sentence_size)
C = []
for i, candidate in enumerate(candidates):
lc = max(0, sentence_size - len(candidate))
C.append([word_idx[w] if w in word_idx else 0 for w in candidate] + [0] * lc)
return Var(l... | def vectorize_candidates(candidates, word_idx, sentence_size):
| shape = (len(candidates), sentence_size)
C = []
for i, candidate in enumerate(candidates):
lc = max(0, sentence_size - len(candidate))
C.append([word_idx[w] if w in word_idx else 0 for w in candidate] + [0] * lc)
return Var(ldtype(C))
| context.append(r)
else:
r = tokenize(line)
r.append('$r')
r.append('#' + str(nid))
context.append(r)
else:
# clear context
context = []
return data
def vectorize_candidates(candidates, word_id... | 64 | 64 | 86 | 13 | 50 | abhi608/task_oriented_nlp_system | memn2n_src/data_utils2.py | Python | vectorize_candidates | vectorize_candidates | 120 | 126 | 120 | 120 | 6513ed822d2ee2bf64b0abbcb5881c4034bcbbde | bigcode/the-stack | train |
731888f9d296f9f4d61113b6 | train | function | @app.post("/upload_img")
async def upload_img(img: List[UploadFile] = File(...)):
for file in img:
with open(file.filename, 'wb') as buffer:
shutil.copyfileobj(file.file, buffer)
return {"file_name": file.filename}
| @app.post("/upload_img")
async def upload_img(img: List[UploadFile] = File(...)):
| for file in img:
with open(file.filename, 'wb') as buffer:
shutil.copyfileobj(file.file, buffer)
return {"file_name": file.filename}
| async def upload_file(file: UploadFile = File(...)):
with open(file.filename, 'wb') as buffer:
shutil.copyfileobj(file.file, buffer)
return {"file_name": file.filename}
@app.post("/upload_img")
async def upload_img(img: List[UploadFile] = File(...)):
| 64 | 64 | 58 | 21 | 43 | OlegZaichuk/Fast_Api_Pyth_3.10 | main.py | Python | upload_img | upload_img | 22 | 27 | 22 | 23 | 900c5c8d2f415d7ce800ced4ebaf38cd31c5000c | bigcode/the-stack | train |
d8d4e04f670ca951bb6916ae | train | function | @app.post("/upload_file")
async def upload_file(file: UploadFile = File(...)):
with open(file.filename, 'wb') as buffer:
shutil.copyfileobj(file.file, buffer)
return {"file_name": file.filename}
| @app.post("/upload_file")
async def upload_file(file: UploadFile = File(...)):
| with open(file.filename, 'wb') as buffer:
shutil.copyfileobj(file.file, buffer)
return {"file_name": file.filename}
| , Path, Body, UploadFile, File
import uvicorn
import shutil
from typing import List, Optional
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.post("/upload_file")
async def upload_file(file: UploadFile = File(...)):
| 63 | 64 | 49 | 18 | 45 | OlegZaichuk/Fast_Api_Pyth_3.10 | main.py | Python | upload_file | upload_file | 15 | 19 | 15 | 16 | 5a230591de016e56bca2ff2ecc98e0fa1c557594 | bigcode/the-stack | train |
642465f0e51f9c4f0094bc75 | train | function | @app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
| @app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
| return {"item_id": item_id, "q": q}
| (...)):
for file in img:
with open(file.filename, 'wb') as buffer:
shutil.copyfileobj(file.file, buffer)
return {"file_name": file.filename}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
| 64 | 64 | 39 | 25 | 39 | OlegZaichuk/Fast_Api_Pyth_3.10 | main.py | Python | read_item | read_item | 30 | 32 | 30 | 31 | c4ecfef17e9ee923efc7157d3579cd8d1a8265dd | bigcode/the-stack | train |
81c57e359199a1522789f888 | train | function | @app.get("/")
async def read_root():
return {"Hello": "World"}
| @app.get("/")
async def read_root():
| return {"Hello": "World"}
| from fastapi import FastAPI, Query, Path, Body, UploadFile, File
import uvicorn
import shutil
from typing import List, Optional
app = FastAPI()
@app.get("/")
async def read_root():
| 45 | 64 | 16 | 8 | 37 | OlegZaichuk/Fast_Api_Pyth_3.10 | main.py | Python | read_root | read_root | 10 | 12 | 10 | 11 | 264c7dd8e284df504cb3e2e43e684db53ec436bb | bigcode/the-stack | train |
7473f26de7bb0aadb5a558b5 | train | class | class GitFolderHandling(Enum):
"""
This enum defines way, how is .git folder handled during project build.
"""
DELETE_BEFORE_BUILD = 1
DELETE_AFTER_BUILD = 2
DISABLE_DELETE = 3
| class GitFolderHandling(Enum):
| """
This enum defines way, how is .git folder handled during project build.
"""
DELETE_BEFORE_BUILD = 1
DELETE_AFTER_BUILD = 2
DISABLE_DELETE = 3
| from enum import Enum
class GitFolderHandling(Enum):
| 11 | 64 | 51 | 6 | 4 | inktrap/flux-ci | flux/enums.py | Python | GitFolderHandling | GitFolderHandling | 4 | 11 | 4 | 4 | 8ef3228ae2496a296aa9da159a1b8ed34cc050af | bigcode/the-stack | train |
7d82db435cd89c4c726e6cd7 | train | class | @pulumi.output_type
class GetTableServicePropertiesResult:
"""
The properties of a storage account’s Table service.
"""
def __init__(__self__, cors=None, id=None, name=None, type=None):
if cors and not isinstance(cors, dict):
raise TypeError("Expected argument 'cors' to be a dict")
... | @pulumi.output_type
class GetTableServicePropertiesResult:
| """
The properties of a storage account’s Table service.
"""
def __init__(__self__, cors=None, id=None, name=None, type=None):
if cors and not isinstance(cors, dict):
raise TypeError("Expected argument 'cors' to be a dict")
pulumi.set(__self__, "cors", cors)
if id and... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | 123 | 136 | 455 | 13 | 110 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/storage/v20210101/get_table_service_properties.py | Python | GetTableServicePropertiesResult | GetTableServicePropertiesResult | 18 | 67 | 18 | 19 | f0a1426032f6372231c25caca5af96782d79592d | bigcode/the-stack | train |
fef49962177bdebfb38fc32f | train | function | def get_table_service_properties(account_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
table_service_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTableSe... | def get_table_service_properties(account_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
table_service_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTableSe... | """
The properties of a storage account’s Table service.
:param str account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
:param str resource_group_name: The na... | __(self):
if False:
yield self
return GetTableServicePropertiesResult(
cors=self.cors,
id=self.id,
name=self.name,
type=self.type)
def get_table_service_properties(account_name: Optional[str] = None,
resource_gr... | 98 | 98 | 327 | 58 | 40 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/storage/v20210101/get_table_service_properties.py | Python | get_table_service_properties | get_table_service_properties | 82 | 108 | 82 | 85 | cce0385170f35db203e085decdc3ca97b1264ced | bigcode/the-stack | train |
160f18c7faf1ba4e9bdb40f8 | train | class | class AwaitableGetTableServicePropertiesResult(GetTableServicePropertiesResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetTableServicePropertiesResult(
cors=self.cors,
id=self.id,
name=self.name,
... | class AwaitableGetTableServicePropertiesResult(GetTableServicePropertiesResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetTableServicePropertiesResult(
cors=self.cors,
id=self.id,
name=self.name,
type=self.type)
| :
"""
The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
"""
return pulumi.get(self, "type")
class AwaitableGetTableServicePropertiesResult(GetTableServicePropertiesResult):
# pylint: disable=using-constant-test
| 64 | 64 | 69 | 25 | 39 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/storage/v20210101/get_table_service_properties.py | Python | AwaitableGetTableServicePropertiesResult | AwaitableGetTableServicePropertiesResult | 70 | 79 | 70 | 71 | 9134884573fabfb7fffcb56e8efc7fb64da4ec78 | bigcode/the-stack | train |
8813379ddd272c7a4f1c97b9 | train | function | @logger('loading data')
def load_data(filename: str, limit: Optional[int] = None) -> List[Example]:
data = []
with open(filename) as json_data:
questions = json.load(json_data)["questions"][:limit]
for question in questions:
tokenized_text = nltk.word_tokenize(question['text'].lower())
label = question['pag... | @logger('loading data')
def load_data(filename: str, limit: Optional[int] = None) -> List[Example]:
| data = []
with open(filename) as json_data:
questions = json.load(json_data)["questions"][:limit]
for question in questions:
tokenized_text = nltk.word_tokenize(question['text'].lower())
label = question['page']
if label:
data.append(Example(tokenized_text, label))
return data
| _dataset.pkl'
TEST_DATASET = 'test_dataset.pkl'
WORD_MAPS = 'word_maps.pkl'
class Example(NamedTuple):
tokenized_text: List[str]
label: str
@logger('loading data')
def load_data(filename: str, limit: Optional[int] = None) -> List[Example]:
| 64 | 64 | 97 | 26 | 37 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | load_data | load_data | 28 | 38 | 28 | 29 | d45022160538732795e7cb6dbf1bb94fdb9d9e0d | bigcode/the-stack | train |
e81819677ca8224428bf0d27 | train | class | class Model(nn.Module):
def __init__(self,
n_classes,
vocab_size,
embedding_dimension=EMBEDDING_LENGTH,
embedder=None,
n_hidden=50,
dropout_rate=.5):
super(Model, self).__init__()
self.n_classes = n_classes
self.vocab_size = vocab_size
self.n_hidden = n_hidden
self.e... | class Model(nn.Module):
| def __init__(self,
n_classes,
vocab_size,
embedding_dimension=EMBEDDING_LENGTH,
embedder=None,
n_hidden=50,
dropout_rate=.5):
super(Model, self).__init__()
self.n_classes = n_classes
self.vocab_size = vocab_size
self.n_hidden = n_hidden
self.embedding_dimension = emb... | = list(labels)
labels = torch.LongTensor(labels)
x1 = torch.LongTensor(len(questions), max(question_lens)).zero_()
for i, (question, q_len) in enumerate(zip(questions, question_lens)):
x1[i, :q_len].copy_(torch.LongTensor(question))
return {
'text': x1,
'len': torch.FloatTensor(question_lens),
'labels': ... | 101 | 101 | 339 | 5 | 96 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | Model | Model | 144 | 194 | 144 | 144 | 9669cf90e41a7210f478398e7eaca73dbb3c34ab | bigcode/the-stack | train |
94042771d3f32682f3839155 | train | class | class QuestionDataset(Dataset):
def __init__(self,
examples: List[Example],
word2index: Dict[str, int],
num_classes: int,
class2index: Optional[Dict[str, int]] = None):
self.tokenized_questions = []
self.labels = []
tokenized_questions, labels = zip(*examples)
self.tokenized_questions = li... | class QuestionDataset(Dataset):
| def __init__(self,
examples: List[Example],
word2index: Dict[str, int],
num_classes: int,
class2index: Optional[Dict[str, int]] = None):
self.tokenized_questions = []
self.labels = []
tokenized_questions, labels = zip(*examples)
self.tokenized_questions = list(tokenized_questions)
self.l... | ] >= cutoff])
new_train = []
new_dev = []
for example in training_examples:
if example.label in ans_keep:
new_train.append(example)
for example in dev_examples:
if example.label in ans_keep:
new_dev.append(example)
return new_train, new_dev, len(ans_keep)/len(ans_count)
class QuestionDataset(Dataset):
| 73 | 73 | 244 | 6 | 67 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | QuestionDataset | QuestionDataset | 85 | 117 | 85 | 85 | b4ebb2c3fe9af851c7e60aa0c36ae723737d81f1 | bigcode/the-stack | train |
c4087cba3bccb7210bed5d8e | train | function | @logger('loading words')
def load_words(examples: List[Example]) -> Tuple[
List[str], Dict[str, int], Dict[int, str]]:
words = {kPAD, kUNK}
tokenized_texts, _ = zip(*examples)
for tokenized_text in tokenized_texts:
for token in tokenized_text:
if token not in words:
words.add(token)
words = list(words)
... | @logger('loading words')
def load_words(examples: List[Example]) -> Tuple[
List[str], Dict[str, int], Dict[int, str]]:
| words = {kPAD, kUNK}
tokenized_texts, _ = zip(*examples)
for tokenized_text in tokenized_texts:
for token in tokenized_text:
if token not in words:
words.add(token)
words = list(words)
index2word = dict(enumerate(words))
word2index = {v: k for k, v in index2word.items()}
return words, word2index, ind... | (enumerate(classes))
class2index = {v: k for k, v in index2class.items()}
return class2index, index2class
@logger('loading words')
def load_words(examples: List[Example]) -> Tuple[
List[str], Dict[str, int], Dict[int, str]]:
| 64 | 64 | 130 | 32 | 31 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | load_words | load_words | 50 | 65 | 50 | 52 | eb623ecfe1c361b0a3a85be00092d2e8a405b76b | bigcode/the-stack | train |
7ae328f92a2ad2528f441313 | train | function | @logger('clip dataset')
def clip_data(training_examples, dev_examples, cutoff=2):
ans_count = defaultdict(int)
for example in (training_examples + dev_examples):
ans_count[example.label] += 1
ans_keep = set([x for x in ans_count if ans_count[x] >= cutoff])
new_train = []
new_dev = []
for example in training_exa... | @logger('clip dataset')
def clip_data(training_examples, dev_examples, cutoff=2):
| ans_count = defaultdict(int)
for example in (training_examples + dev_examples):
ans_count[example.label] += 1
ans_keep = set([x for x in ans_count if ans_count[x] >= cutoff])
new_train = []
new_dev = []
for example in training_examples:
if example.label in ans_keep:
new_train.append(example)
for example i... | words = list(words)
index2word = dict(enumerate(words))
word2index = {v: k for k, v in index2word.items()}
return words, word2index, index2word
@logger('clip dataset')
def clip_data(training_examples, dev_examples, cutoff=2):
| 64 | 64 | 128 | 19 | 44 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | clip_data | clip_data | 68 | 82 | 68 | 69 | 4db10bbe0db751fe0004b96bed35e92c5c67b6d9 | bigcode/the-stack | train |
8d01c0f6b42b0353247492c2 | train | function | @logger('creating class labels')
def class_labels(examples: List[Example]) -> Tuple[
Dict[str, int], Dict[int, str]]:
classes = set([example.label for example in examples])
index2class = dict(enumerate(classes))
class2index = {v: k for k, v in index2class.items()}
return class2index, index2class
| @logger('creating class labels')
def class_labels(examples: List[Example]) -> Tuple[
Dict[str, int], Dict[int, str]]:
| classes = set([example.label for example in examples])
index2class = dict(enumerate(classes))
class2index = {v: k for k, v in index2class.items()}
return class2index, index2class
| _tokenize(question['text'].lower())
label = question['page']
if label:
data.append(Example(tokenized_text, label))
return data
@logger('creating class labels')
def class_labels(examples: List[Example]) -> Tuple[
Dict[str, int], Dict[int, str]]:
| 64 | 64 | 80 | 31 | 32 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | class_labels | class_labels | 41 | 47 | 41 | 43 | b0ebdeb779704f5d86eb7c319b0d1133b670bec0 | bigcode/the-stack | train |
c57bdff88994ddd2c6cfc569 | train | class | class Example(NamedTuple):
tokenized_text: List[str]
label: str
| class Example(NamedTuple):
| tokenized_text: List[str]
label: str
| der import EMBEDDING_LENGTH, Embedder
kUNK = '<unk>'
kPAD = '<pad>'
TRAIN_DATASET = 'train_dataset.pkl'
DEV_DATASET = 'dev_dataset.pkl'
TEST_DATASET = 'test_dataset.pkl'
WORD_MAPS = 'word_maps.pkl'
class Example(NamedTuple):
| 64 | 64 | 17 | 6 | 58 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | Example | Example | 23 | 25 | 23 | 23 | fe0c3cad3e7bc82fc9bf9b8ecbedebb8309bfcd6 | bigcode/the-stack | train |
0c92bdf7f63fc6e49070e0d5 | train | function | def evaluate(data_loader: torch.utils.data.DataLoader,
model: Model,
device: torch.device) -> float:
model.eval()
num_examples = 0
error = 0
for i, batch in enumerate(data_loader):
question_text = batch['text'].to(device)
question_len = batch['len'].to(device)
labels = batch['labels'].to(device)
lo... | def evaluate(data_loader: torch.utils.data.DataLoader,
model: Model,
device: torch.device) -> float:
| model.eval()
num_examples = 0
error = 0
for i, batch in enumerate(data_loader):
question_text = batch['text'].to(device)
question_len = batch['len'].to(device)
labels = batch['labels'].to(device)
logits = model(question_text, question_len)
top_n, top_i = logits.topk(1)
num_examples += question_text.si... | 0), -1)
if is_prob:
logits = self._softmax(logits)
else:
logits = self.classifier(average_embedding)
return logits
def evaluate(data_loader: torch.utils.data.DataLoader,
model: Model,
device: torch.device) -> float:
| 64 | 64 | 152 | 25 | 38 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | evaluate | evaluate | 197 | 216 | 197 | 199 | 9246d168286a658afb7fa3e081c00e6add32bb18 | bigcode/the-stack | train |
68654591dfd18bd474af1ef6 | train | function | def train(args: argparse.Namespace,
model: Model,
train_data_loader: torch.utils.data.DataLoader,
dev_data_loader: torch.utils.data.DataLoader,
accuracy: float,
device: torch.device,
learning_rate: float) -> float:
model.train()
if args.optim == 'adamax':
optimizer = torch.optim.Adamax... | def train(args: argparse.Namespace,
model: Model,
train_data_loader: torch.utils.data.DataLoader,
dev_data_loader: torch.utils.data.DataLoader,
accuracy: float,
device: torch.device,
learning_rate: float) -> float:
| model.train()
if args.optim == 'adamax':
optimizer = torch.optim.Adamax(model.parameters(), lr=learning_rate)
elif args.optim == 'rprop':
optimizer = torch.optim.Rprop(model.parameters(), lr=learning_rate)
criterion = nn.CrossEntropyLoss()
# print_loss_total = 0
# epoch_loss_total = 0
# start = time.time()
... | )
top_n, top_i = logits.topk(1)
num_examples += question_text.size(0)
error += torch.nonzero(top_i.squeeze() - labels).size(0)
accuracy = 1 - error / num_examples
print(accuracy)
return accuracy
def train(args: argparse.Namespace,
model: Model,
train_data_loader: torch.utils.data.DataLoader,
dev_... | 113 | 113 | 378 | 54 | 58 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | train | train | 219 | 263 | 219 | 225 | 514e28de063a538808df2ddce0d1b66c12560e64 | bigcode/the-stack | train |
07487adffd59000ed4502c46 | train | function | def batchify(batch: List[Tuple[List[int], int]]) -> Dict[
str, Union[torch.LongTensor, torch.FloatTensor]]:
"""
Create a batch of examples which includes the
question text, question length and labels.
"""
questions, labels = zip(*batch)
questions = list(questions)
question_lens = [len(q) for q in questions]
l... | def batchify(batch: List[Tuple[List[int], int]]) -> Dict[
str, Union[torch.LongTensor, torch.FloatTensor]]:
| """
Create a batch of examples which includes the
question text, question length and labels.
"""
questions, labels = zip(*batch)
questions = list(questions)
question_lens = [len(q) for q in questions]
labels = list(labels)
labels = torch.LongTensor(labels)
x1 = torch.LongTensor(len(questions), max(question_... | [int]:
return [self.word2index[word] if word in self.word2index else
self.word2index[kUNK]
for word in tokenized_text]
def batchify(batch: List[Tuple[List[int], int]]) -> Dict[
str, Union[torch.LongTensor, torch.FloatTensor]]:
| 64 | 64 | 178 | 28 | 36 | ExSidius/qanta-codalab | src/qanta/guesser_model.py | Python | batchify | batchify | 120 | 141 | 120 | 121 | f6001fd611702614e5925c0dadb78638ec0ba7ac | bigcode/the-stack | train |
c93448960d2657c632f68799 | train | function | def run_program_for_single_img( # pylint: disable=too-many-branches, too-many-statements
image: str,
resize: bool = False,
size: Optional[Tuple[int, int]] = None,
place: str = DEFAULT_PLACE,
match_filter: Optional[str] = None,
browser: Optional[mechanicalsoup.StatefulBrowser] = None,
scrape... | def run_program_for_single_img( # pylint: disable=too-many-branches, too-many-statements
image: str,
resize: bool = False,
size: Optional[Tuple[int, int]] = None,
place: str = DEFAULT_PLACE,
match_filter: Optional[str] = None,
browser: Optional[mechanicalsoup.StatefulBrowser] = None,
scrape... | """Run program for single image.
Args:
image: image path
resize: resize the image
size: resized image size
place: iqdb place, see `iqdb_url_dict`
match_filter: whitelist matched items
browser: mechanicalsoup browser instance
scraper: cfscrape instance
... | =url, browser=browser, use_requests=use_requests)
# if ok, will output: <Response [200]>
result = list(
models.ImageMatch.get_or_create_from_page(page=page, image=post_img, place=im_place))
result = [x[0] for x in result]
# temp_f
temp_f.close()
os.remove(temp_file_name)
... | 256 | 256 | 960 | 148 | 107 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | run_program_for_single_img | run_program_for_single_img | 156 | 259 | 156 | 168 | 507de73dfc5e3a5ec5669368f0bea06eb6e8ceb6 | bigcode/the-stack | train |
4cfa06d4aa87456188464440 | train | function | @click.group(cls=CustomFlaskGroup, create_app=create_app)
def cli():
"""Run cli. This is a management script for application."""
| @click.group(cls=CustomFlaskGroup, create_app=create_app)
def cli():
| """Run cli. This is a management script for application."""
| % {
'app_name': 'Iqdb-tagger',
'app_version': __version__,
'version': flask_version,
'python_version': sys.version,
}, color=ctx.color)
ctx.exit()
@click.group(cls=CustomFlaskGroup, create_app=create_app)
def cli():
| 64 | 64 | 30 | 17 | 47 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | cli | cli | 354 | 356 | 354 | 355 | eae8ad6469f005c34c295ceb2a6d630c91703ec8 | bigcode/the-stack | train |
0ef609bb1176c932aa0b8a86 | train | function | def write_url_from_match_result(match_result, folder=None):
"""Write url from match result."""
netloc = urlparse(match_result.link).netloc
sanitized_netloc = netloc.replace('.', '_')
text_file_basename = sanitized_netloc + '.txt'
text_file = os.path.join(folder, text_file_basename) if folder is not ... | def write_url_from_match_result(match_result, folder=None):
| """Write url from match result."""
netloc = urlparse(match_result.link).netloc
sanitized_netloc = netloc.replace('.', '_')
text_file_basename = sanitized_netloc + '.txt'
text_file = os.path.join(folder, text_file_basename) if folder is not None else text_file_basename
with open(text_file, 'a') a... | Init program."""
# create user data dir
pathlib.Path(user_data_dir).mkdir(parents=True, exist_ok=True)
pathlib.Path(thumb_folder).mkdir(parents=True, exist_ok=True)
models.init_db(db_path, db_version)
def write_url_from_match_result(match_result, folder=None):
| 64 | 64 | 107 | 12 | 52 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | write_url_from_match_result | write_url_from_match_result | 88 | 96 | 88 | 88 | 53a1ede7bae81871ec39a492e1513576e4c11667 | bigcode/the-stack | train |
67588d05315d8188ed9c7840 | train | function | def init_program(db_path: Optional[str] = default_db_path):
"""Init program."""
# create user data dir
pathlib.Path(user_data_dir).mkdir(parents=True, exist_ok=True)
pathlib.Path(thumb_folder).mkdir(parents=True, exist_ok=True)
models.init_db(db_path, db_version)
| def init_program(db_path: Optional[str] = default_db_path):
| """Init program."""
# create user data dir
pathlib.Path(user_data_dir).mkdir(parents=True, exist_ok=True)
pathlib.Path(thumb_folder).mkdir(parents=True, exist_ok=True)
models.init_db(db_path, db_version)
| in tables:
res = models.ImageMatch.parse_table(table)
if not res:
continue
additional_res = models.get_additional_result_from_table(table, res)
if additional_res:
yield additional_res
yield res
def init_program(db_path: Optional[str] = default_db_path):
| 64 | 64 | 68 | 14 | 49 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | init_program | init_program | 80 | 85 | 80 | 80 | 2bb655b2146673f1d26946e2aa4c8b53a2f5f19d | bigcode/the-stack | train |
59fbb585b99b76d7cd2b1071 | train | function | def get_iqdb_result(image, iqdb_url):
"""Get iqdb result."""
e621_iqdb_url = 'http://iqdb.harry.lu'
use_requests = iqdb_url != e621_iqdb_url
if use_requests:
files = {'file': open(image, 'rb')}
resp = requests.post(iqdb_url, files=files, timeout=10)
html_text = BeautifulSoup(resp... | def get_iqdb_result(image, iqdb_url):
| """Get iqdb result."""
e621_iqdb_url = 'http://iqdb.harry.lu'
use_requests = iqdb_url != e621_iqdb_url
if use_requests:
files = {'file': open(image, 'rb')}
resp = requests.post(iqdb_url, files=files, timeout=10)
html_text = BeautifulSoup(resp.text, 'lxml')
else:
brows... | '
DEFAULT_PLACE = 'iqdb'
minsim = 75
services = ['1', '2', '3', '4', '5', '6', '10', '11']
forcegray = False
log = structlog.getLogger()
def get_iqdb_result(image, iqdb_url):
| 64 | 64 | 183 | 12 | 52 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | get_iqdb_result | get_iqdb_result | 48 | 64 | 48 | 48 | 003841b0add7cade8bb0248db55e08ff232bbd3b | bigcode/the-stack | train |
493ede6a4829c1d23e402371 | train | function | def get_custom_version(ctx, _, value):
"""Get version."""
if not value or ctx.resilient_parsing:
return
message = '%(app_name)s %(app_version)s\nFlask %(version)s\nPython %(python_version)s'
click.echo(message % {
'app_name': 'Iqdb-tagger',
'app_version': __version__,
've... | def get_custom_version(ctx, _, value):
| """Get version."""
if not value or ctx.resilient_parsing:
return
message = '%(app_name)s %(app_version)s\nFlask %(version)s\nPython %(python_version)s'
click.echo(message % {
'app_name': 'Iqdb-tagger',
'app_version': __version__,
'version': flask_version,
'python_... | """Custom Flask Group."""
def __init__(self, **kwargs):
"""Class init."""
super().__init__(**kwargs)
self.params[0].help = 'Show the program version'
self.params[0].callback = get_custom_version
def get_custom_version(ctx, _, value):
| 64 | 64 | 105 | 9 | 54 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | get_custom_version | get_custom_version | 340 | 351 | 340 | 340 | 2e83a3c12ec7f2e3a2dd58c2679d5cf0546574a7 | bigcode/the-stack | train |
10a35413aa0be44839ccb2d9 | train | function | @cli.command()
@click.argument('tag', nargs=-1)
@click.option('--access_key', help='Hydrus access key')
@click.option('--hydrus_url', help='URL for hydrus client e.g. http://127.0.0.1:45869/')
def search_hydrus_and_send_url(tag: List[str], access_key: Optional[str] = None, hydrus_url: Optional[str] = 'http://127.0.0.1:... | @cli.command()
@click.argument('tag', nargs=-1)
@click.option('--access_key', help='Hydrus access key')
@click.option('--hydrus_url', help='URL for hydrus client e.g. http://127.0.0.1:45869/')
def search_hydrus_and_send_url(tag: List[str], access_key: Optional[str] = None, hydrus_url: Optional[str] = 'http://127.0.0.1:... | """Search hydrus and send url."""
# compatibility
search_tags = tag
if Client is None:
print('Hydrus package is required')
return
cl = Client(access_key, hydrus_url)
for res_dict in get_hydrus_set(search_tags, cl):
match_results = [x[0] for x in res_dict['iqdb_result']['... | @cli.command()
@click.argument('tag', nargs=-1)
@click.option('--access_key', help='Hydrus access key')
@click.option('--hydrus_url', help='URL for hydrus client e.g. http://127.0.0.1:45869/')
def search_hydrus_and_send_url(tag: List[str], access_key: Optional[str] = None, hydrus_url: Optional[str] = 'http://127.0.0.1:... | 101 | 64 | 207 | 101 | 0 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | search_hydrus_and_send_url | search_hydrus_and_send_url | 491 | 508 | 491 | 495 | 723524da8006f308a9173c9106bcc40635436475 | bigcode/the-stack | train |
5bd994e2f9fb880791d3ec71 | train | function | def parse_iqdb_result_page(page):
"""Parse iqdb result page."""
tables = page.select('.pages table')
for table in tables:
res = models.ImageMatch.parse_table(table)
if not res:
continue
additional_res = models.get_additional_result_from_table(table, res)
if additi... | def parse_iqdb_result_page(page):
| """Parse iqdb result page."""
tables = page.select('.pages table')
for table in tables:
res = models.ImageMatch.parse_table(table)
if not res:
continue
additional_res = models.get_additional_result_from_table(table, res)
if additional_res:
yield additi... | = True
browser.open(iqdb_url)
html_form = browser.select_form('form')
html_form.input({'file': image})
browser.submit_selected()
html_text = browser.get_current_page()
return parse_iqdb_result_page(html_text)
def parse_iqdb_result_page(page):
| 64 | 64 | 79 | 9 | 55 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | parse_iqdb_result_page | parse_iqdb_result_page | 67 | 77 | 67 | 67 | 28dffd6bf1a1b36ae500cd17e68e7b484c54b9ba | bigcode/the-stack | train |
b4145d12e73aa8ae2f2daac6 | train | class | class CustomFlaskGroup(flask_cli.FlaskGroup):
"""Custom Flask Group."""
def __init__(self, **kwargs):
"""Class init."""
super().__init__(**kwargs)
self.params[0].help = 'Show the program version'
self.params[0].callback = get_custom_version
| class CustomFlaskGroup(flask_cli.FlaskGroup):
| """Custom Flask Group."""
def __init__(self, **kwargs):
"""Class init."""
super().__init__(**kwargs)
self.params[0].help = 'Show the program version'
self.params[0].callback = get_custom_version
| _view(ModelView(ImageModel, category='DB'))
# app_admin.add_view(ModelView(MatchTagRelationship, category='DB'))
# routing
app.add_url_rule('/thumb/<path:basename>', view_func=thumb)
return app
class CustomFlaskGroup(flask_cli.FlaskGroup):
| 64 | 64 | 67 | 12 | 51 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | CustomFlaskGroup | CustomFlaskGroup | 330 | 337 | 330 | 330 | 9ea099641ab56e38646c9a8fbdb0c5c7290b2470 | bigcode/the-stack | train |
2d53259a309155fbd9e9c78d | train | function | def create_app(script_info=None):
"""Create app."""
app = Flask(__name__)
# logging
if not os.path.exists(user_data_dir):
os.makedirs(user_data_dir)
log_dir = os.path.join(user_data_dir, 'log')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
peewee_logger = logging.getLo... | def create_app(script_info=None):
| """Create app."""
app = Flask(__name__)
# logging
if not os.path.exists(user_data_dir):
os.makedirs(user_data_dir)
log_dir = os.path.join(user_data_dir, 'log')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
peewee_logger = logging.getLogger('peewee')
peewee_logger.s... | tags_verbose = [x.full_name for x in tags]
match_result_tag_pairs.append((match_result, tags))
log.debug('{} tag(s) founds'.format(len(tags_verbose)))
if tags and not disable_tag_print:
print('\n'.join(tags_verbose))
if tags and write_tags:
... | 195 | 195 | 653 | 7 | 188 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | create_app | create_app | 267 | 327 | 267 | 267 | c0314b8dac1b29570e72fcff8c4fefa4b0660607 | bigcode/the-stack | train |
280756093bfcb7a426209bae | train | function | def thumb(basename):
"""Get thumbnail."""
return send_from_directory(thumb_folder, basename)
| def thumb(basename):
| """Get thumbnail."""
return send_from_directory(thumb_folder, basename)
| _from_match_result(match_result, folder)
except Exception as e: # pylint:disable=broad-except
log.error('Error', e=str(e))
error_set.append(e)
return {'error': error_set, 'match result tag pairs': match_result_tag_pairs}
def thumb(basename):
| 64 | 64 | 22 | 6 | 58 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | thumb | thumb | 262 | 264 | 262 | 262 | 32723503d2bf024ea3c6b8bdc7ea3b2f0f0a3cf3 | bigcode/the-stack | train |
bd1c3b27e55a8437a986f43c | train | function | @cli.command()
@click.version_option()
@click.option(
'--place', type=click.Choice([x for x in iqdb_url_dict]),
default=DEFAULT_PLACE,
help='Specify iqdb place, default:{}'.format(DEFAULT_PLACE)
)
@click.option(
'--minimum-similarity', type=float, help='Minimum similarity.')
@click.option('--resize', is... | @cli.command()
@click.version_option()
@click.option(
'--place', type=click.Choice([x for x in iqdb_url_dict]),
default=DEFAULT_PLACE,
help='Specify iqdb place, default:{}'.format(DEFAULT_PLACE)
)
@click.option(
'--minimum-similarity', type=float, help='Minimum similarity.')
@click.option('--resize', is... | """Get similar image from iqdb."""
assert prog_input is not None, "Input is not a valid path"
# logging
log_level = None
if verbose:
log_level = logging.INFO
if debug:
log_level = logging.DEBUG
if log_level:
logging.basicConfig(handlers=[logging.FileHandler(os.path.... | @cli.command()
@click.version_option()
@click.option(
'--place', type=click.Choice([x for x in iqdb_url_dict]),
default=DEFAULT_PLACE,
help='Specify iqdb place, default:{}'.format(DEFAULT_PLACE)
)
@click.option(
'--minimum-similarity', type=float, help='Minimum similarity.')
@click.option('--resize', is... | 337 | 256 | 868 | 337 | 0 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | cli_run | cli_run | 359 | 451 | 359 | 392 | fb5531a944f5a53bf8162cb9862fecea58eebcf2 | bigcode/the-stack | train |
94f402f3531e6dd6ecb4a0ed | train | function | def get_hydrus_set(search_tags: List[str], client: Client) -> Iterator[Dict[str, Any]]:
"""Get hydrus result.
Args:
search_tags: tags used to search hydrus
client: client instance
Returns:
hydrus metadata and iqdb results
"""
# compatibility
cl = client
file_ids = ... | def get_hydrus_set(search_tags: List[str], client: Client) -> Iterator[Dict[str, Any]]:
| """Get hydrus result.
Args:
search_tags: tags used to search hydrus
client: client instance
Returns:
hydrus metadata and iqdb results
"""
# compatibility
cl = client
file_ids = cl.search_files(search_tags)
metadata_sets = cl.file_metadata(file_ids=file_ids, onl... | _set.extend([(image, x) for x in result['error']])
if error_set:
log.error('Found error(s)')
for x in error_set:
log.error('path: ' + x[0] + '\nerror: ' + str(x[1]))
def get_hydrus_set(search_tags: List[str], client: Client) -> Iterator[Dict[str, Any]]:
| 83 | 84 | 281 | 24 | 59 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | get_hydrus_set | get_hydrus_set | 454 | 488 | 454 | 454 | 897f9822143b5cab248049dc071e8fea122a0fbc | bigcode/the-stack | train |
cb0dcf0dbf2b5113e0cd5c58 | train | function | @cli.command()
@click.argument('tag', nargs=-1)
@click.option('--access_key', help='Hydrus access key')
@click.option('--hydrus_url', help='URL for hydrus client e.g. http://127.0.0.1:45869/')
@click.option('--tag_repo', help='tag repo name e.g. local tags')
def search_hydrus_and_send_tag(tag: List[str], access_key: Op... | @cli.command()
@click.argument('tag', nargs=-1)
@click.option('--access_key', help='Hydrus access key')
@click.option('--hydrus_url', help='URL for hydrus client e.g. http://127.0.0.1:45869/')
@click.option('--tag_repo', help='tag repo name e.g. local tags')
def search_hydrus_and_send_tag(tag: List[str], access_key: Op... | """Search hydrus and send tag."""
# compatibility
search_tags = tag
if Client is None:
print('Hydrus package is required')
return
cl = Client(access_key, hydrus_url)
for res_dict in get_hydrus_set(search_tags, cl):
f_hash = res_dict['metadata']['hash']
tag_sets =... | @cli.command()
@click.argument('tag', nargs=-1)
@click.option('--access_key', help='Hydrus access key')
@click.option('--hydrus_url', help='URL for hydrus client e.g. http://127.0.0.1:45869/')
@click.option('--tag_repo', help='tag repo name e.g. local tags')
def search_hydrus_and_send_tag(tag: List[str], access_key: Op... | 128 | 82 | 276 | 128 | 0 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | search_hydrus_and_send_tag | search_hydrus_and_send_tag | 511 | 531 | 511 | 516 | c888018c9f8d9956fb6a51c505e1711cfcde24d4 | bigcode/the-stack | train |
ff6c681f8b5f764752b14c28 | train | function | def get_result_on_windows(
image: str, place: str,
resize: Optional[bool] = False, size: Optional[Tuple[int, int]] = None,
browser: Optional[mechanicalsoup.StatefulBrowser] = None
) -> List[models.ImageMatch]:
"""Get result on Windows.
Args:
image: image path
place: iqdb... | def get_result_on_windows(
image: str, place: str,
resize: Optional[bool] = False, size: Optional[Tuple[int, int]] = None,
browser: Optional[mechanicalsoup.StatefulBrowser] = None
) -> List[models.ImageMatch]:
| """Get result on Windows.
Args:
image: image path
place: iqdb place code
resize: resize the image
size: resized image size
browser: browser instance
Returns:
matching items
"""
result = []
# temp_f
temp_f = NamedTemporaryFile(mode='w+t', dele... | loc = urlparse(match_result.link).netloc
sanitized_netloc = netloc.replace('.', '_')
text_file_basename = sanitized_netloc + '.txt'
text_file = os.path.join(folder, text_file_basename) if folder is not None else text_file_basename
with open(text_file, 'a') as f:
f.write(match_result.link)
... | 145 | 145 | 486 | 60 | 85 | a1270/iqdb_tagger | iqdb_tagger/__main__.py | Python | get_result_on_windows | get_result_on_windows | 99 | 153 | 99 | 103 | 1344ba51174f01a58b512982efeac24ab4d40e9e | bigcode/the-stack | train |
10d760e34b3c6175256e11bb | train | function | def _select_stub_methods(gen: StubGenerator, method: ProtoServiceMethod):
if method.type() is ProtoServiceMethod.Type.UNARY:
return gen.unary_signature, gen.unary_stub
if method.type() is ProtoServiceMethod.Type.SERVER_STREAMING:
return gen.server_streaming_signature, gen.server_streaming_stub
... | def _select_stub_methods(gen: StubGenerator, method: ProtoServiceMethod):
| if method.type() is ProtoServiceMethod.Type.UNARY:
return gen.unary_signature, gen.unary_stub
if method.type() is ProtoServiceMethod.Type.SERVER_STREAMING:
return gen.server_streaming_signature, gen.server_streaming_stub
if method.type() is ProtoServiceMethod.Type.CLIENT_STREAMING:
... | ,
output: OutputFile) -> None:
"""Returns the stub for this bidirectional streaming method."""
output.write_line(STUB_READER_WRITER_TODO)
output.write_line('static_cast<void>(reader_writer);')
def _select_stub_methods(gen: StubGenerator, method: ProtoServiceMethod):
| 64 | 64 | 148 | 16 | 48 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _select_stub_methods | _select_stub_methods | 431 | 445 | 431 | 431 | 72f971e3070710777789cceb86cd287e41ac4ce8 | bigcode/the-stack | train |
fa69bb3a54c99d0398e27561 | train | function | def _generate_service_and_client(gen: CodeGenerator,
service: ProtoService) -> None:
gen.line('// Wrapper class that namespaces server and client code for '
'this RPC service.')
gen.line(f'class {service.name()} final {{')
gen.line(' public:')
with gen.inde... | def _generate_service_and_client(gen: CodeGenerator,
service: ProtoService) -> None:
| gen.line('// Wrapper class that namespaces server and client code for '
'this RPC service.')
gen.line(f'class {service.name()} final {{')
gen.line(' public:')
with gen.indent():
gen.line(f'{service.name()}() = delete;')
gen.line()
_generate_service(gen, service)
... | _namespace)
gen.line()
gen.line('// Specialize MethodInfo for each RPC to provide metadata at '
'compile time.')
for service in services:
_generate_info(gen, file_namespace, service)
def _generate_service_and_client(gen: CodeGenerator,
service: ProtoSer... | 64 | 64 | 158 | 20 | 44 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _generate_service_and_client | _generate_service_and_client | 193 | 216 | 193 | 194 | 87b77a8a84b3d3a67939053da90367aa279ee75d | bigcode/the-stack | train |
9d5895db83cf737db46e8466 | train | function | def _service_definition_stub(service: ProtoService, output: OutputFile,
stub_generator: StubGenerator) -> None:
output.write_line(f'// Method definitions for {service.proto_path()}.')
blank_line = False
for method in service.methods():
if blank_line:
output... | def _service_definition_stub(service: ProtoService, output: OutputFile,
stub_generator: StubGenerator) -> None:
| output.write_line(f'// Method definitions for {service.proto_path()}.')
blank_line = False
for method in service.methods():
if blank_line:
output.write_line()
else:
blank_line = True
signature, stub = _select_stub_methods(stub_generator, method)
ou... | _line = True
signature, _ = _select_stub_methods(stub_generator, method)
output.write_line(signature(method, '') + ';')
output.write_line('};\n')
def _service_definition_stub(service: ProtoService, output: OutputFile,
stub_generator: StubGenerator) -> None:
| 64 | 64 | 124 | 25 | 39 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _service_definition_stub | _service_definition_stub | 537 | 554 | 537 | 538 | 7bbcf3ce19b814bde83e71c49976915289e946c8 | bigcode/the-stack | train |
6437641765b5a366b97681b1 | train | function | def get_id(item: Union[ProtoService, ProtoServiceMethod]) -> str:
name = item.proto_path() if isinstance(item, ProtoService) else item.name()
return f'0x{pw_rpc.ids.calculate(name):08x}'
| def get_id(item: Union[ProtoService, ProtoServiceMethod]) -> str:
| name = item.proto_path() if isinstance(item, ProtoService) else item.name()
return f'0x{pw_rpc.ids.calculate(name):08x}'
| client stream callback and send a response as '
'appropriate for your application')
STUB_READER_WRITER_TODO = (
'// TODO: Set the client stream callback and send responses as '
'appropriate for your application')
def get_id(item: Union[ProtoService, ProtoServiceMethod]) -> str:
| 64 | 64 | 51 | 17 | 47 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | get_id | get_id | 46 | 48 | 46 | 46 | 312a7f1915abe798278201b607d682e765af8daf | bigcode/the-stack | train |
3f1762c7d1cd5af397c39d20 | train | function | def generate_package(file_descriptor_proto, proto_package: ProtoNode,
gen: CodeGenerator) -> None:
"""Generates service and client code for a package."""
assert proto_package.type() == ProtoNode.Type.PACKAGE
gen.line(f'// {os.path.basename(gen.output.name())} automatically '
... | def generate_package(file_descriptor_proto, proto_package: ProtoNode,
gen: CodeGenerator) -> None:
| """Generates service and client code for a package."""
assert proto_package.type() == ProtoNode.Type.PACKAGE
gen.line(f'// {os.path.basename(gen.output.name())} automatically '
f'generated by {PLUGIN_NAME} {PLUGIN_VERSION}')
gen.line(f'// on {datetime.now().isoformat()}')
gen.line('// ... | the Client member functions."""
@abc.abstractmethod
def client_static_function(self, method: ProtoServiceMethod) -> None:
"""Generates method static functions that instantiate a Client."""
def method_info_specialization(self, method: ProtoServiceMethod) -> None:
"""Generates impl-specific... | 138 | 139 | 466 | 22 | 116 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | generate_package | generate_package | 126 | 190 | 126 | 127 | 667cd56f3b6edcc7db5bb88f5235957bd6a58d6a | bigcode/the-stack | train |
9542971f74d224e6dfc52c0e | train | function | def _generate_info(gen: CodeGenerator, namespace: str,
service: ProtoService) -> None:
"""Generates MethodInfo for each method."""
service_id = get_id(service)
info = f'struct {RPC_NAMESPACE.lstrip(":")}::internal::MethodInfo'
for method in service.methods():
gen.line('templa... | def _generate_info(gen: CodeGenerator, namespace: str,
service: ProtoService) -> None:
| """Generates MethodInfo for each method."""
service_id = get_id(service)
info = f'struct {RPC_NAMESPACE.lstrip(":")}::internal::MethodInfo'
for method in service.methods():
gen.line('template <>')
gen.line(f'{info}<{namespace}::pw_rpc::{gen.name()}::'
f'{service.name()}... | '
'These functions are ')
gen.line('// equivalent to instantiating a Client and calling the '
'corresponding RPC.')
for method in service.methods():
_check_method_name(method)
gen.client_static_function(method)
gen.line()
def _generate_info(gen: CodeGenerator, ... | 76 | 76 | 255 | 22 | 54 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _generate_info | _generate_info | 255 | 285 | 255 | 256 | 63bdf8605c08a7905f2ddd9bb0510f1472e90724 | bigcode/the-stack | train |
da25ae14ada8a5f9f57b156d | train | function | def _service_declaration_stub(service: ProtoService, output: OutputFile,
stub_generator: StubGenerator) -> None:
output.write_line(f'// Implementation class for {service.proto_path()}.')
output.write_line(
f'class {service.name()} '
f': public generated::{service.na... | def _service_declaration_stub(service: ProtoService, output: OutputFile,
stub_generator: StubGenerator) -> None:
| output.write_line(f'// Implementation class for {service.proto_path()}.')
output.write_line(
f'class {service.name()} '
f': public generated::{service.name()}<{service.name()}> {{')
output.write_line(' public:')
with output.indent():
blank_line = False
for method in se... | _definition_stub(node, output, stub_generator)
output.write_line()
finish_ns()
output.write_line('#endif // _PW_RPC_COMPILE_GENERATED_SERVICE_STUBS')
def _service_declaration_stub(service: ProtoService, output: OutputFile,
stub_generator: StubGenerator) -> None:
| 64 | 64 | 153 | 26 | 38 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _service_declaration_stub | _service_declaration_stub | 512 | 534 | 512 | 513 | d94d489994daecc1693d45785f5970aae726300f | bigcode/the-stack | train |
6bbe24a3b50ac0f35c63c36f | train | function | def client_call_type(method: ProtoServiceMethod, prefix: str) -> str:
"""Returns Client ReaderWriter/Reader/Writer/Recevier for the call."""
if method.type() is ProtoServiceMethod.Type.UNARY:
call_class = 'UnaryReceiver'
elif method.type() is ProtoServiceMethod.Type.SERVER_STREAMING:
call_cl... | def client_call_type(method: ProtoServiceMethod, prefix: str) -> str:
| """Returns Client ReaderWriter/Reader/Writer/Recevier for the call."""
if method.type() is ProtoServiceMethod.Type.UNARY:
call_class = 'UnaryReceiver'
elif method.type() is ProtoServiceMethod.Type.SERVER_STREAMING:
call_class = 'ClientReader'
elif method.type() is ProtoServiceMethod.Type... | Union[ProtoService, ProtoServiceMethod]) -> str:
name = item.proto_path() if isinstance(item, ProtoService) else item.name()
return f'0x{pw_rpc.ids.calculate(name):08x}'
def client_call_type(method: ProtoServiceMethod, prefix: str) -> str:
| 63 | 64 | 154 | 17 | 46 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | client_call_type | client_call_type | 51 | 64 | 51 | 51 | 503a20d392354d1083570b245a68d4277a8497b2 | bigcode/the-stack | train |
d0b55ebba710e1da694580ee | train | class | class CodeGenerator(abc.ABC):
"""Generates RPC code for services and clients."""
def __init__(self, output_filename: str) -> None:
self.output = OutputFile(output_filename)
def indent(self, amount: int = OutputFile.INDENT_WIDTH) -> Any:
"""Indents the output. Use in a with block."""
... | class CodeGenerator(abc.ABC):
| """Generates RPC code for services and clients."""
def __init__(self, output_filename: str) -> None:
self.output = OutputFile(output_filename)
def indent(self, amount: int = OutputFile.INDENT_WIDTH) -> Any:
"""Indents the output. Use in a with block."""
return self.output.indent(amo... | /Writer/Recevier for the call."""
if method.type() is ProtoServiceMethod.Type.UNARY:
call_class = 'UnaryReceiver'
elif method.type() is ProtoServiceMethod.Type.SERVER_STREAMING:
call_class = 'ClientReader'
elif method.type() is ProtoServiceMethod.Type.CLIENT_STREAMING:
call_class = '... | 137 | 138 | 463 | 8 | 129 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | CodeGenerator | CodeGenerator | 67 | 123 | 67 | 67 | c219547511a0385b9e50cca50225f7e09bf6ea49 | bigcode/the-stack | train |
95e455d184301b1cc509b1e2 | train | class | class StubGenerator(abc.ABC):
"""Generates stub method implementations that can be copied-and-pasted."""
@abc.abstractmethod
def unary_signature(self, method: ProtoServiceMethod, prefix: str) -> str:
"""Returns the signature of this unary method."""
@abc.abstractmethod
def unary_stub(self, ... | class StubGenerator(abc.ABC):
| """Generates stub method implementations that can be copied-and-pasted."""
@abc.abstractmethod
def unary_signature(self, method: ProtoServiceMethod, prefix: str) -> str:
"""Returns the signature of this unary method."""
@abc.abstractmethod
def unary_stub(self, method: ProtoServiceMethod,
... | # Generate the method lookup table
_method_lookup_table(gen, service)
gen.line('};')
def _method_lookup_table(gen: CodeGenerator, service: ProtoService) -> None:
"""Generates array of method IDs for looking up methods at compile time."""
gen.line('static constexpr std::array<uint32_t, '
... | 134 | 134 | 448 | 8 | 126 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | StubGenerator | StubGenerator | 381 | 428 | 381 | 381 | 407281a13497ed41118c76df47c4f98e4c83b679 | bigcode/the-stack | train |
1c7804548df387f3d9cdb489 | train | function | def _generate_deprecated_aliases(gen: CodeGenerator,
services: Sequence[ProtoService]) -> None:
"""Generates aliases for the original, deprecated naming scheme."""
gen.line('// Aliases for the deprecated namespaces.')
gen.line('namespace generated {')
gen.line()
for... | def _generate_deprecated_aliases(gen: CodeGenerator,
services: Sequence[ProtoService]) -> None:
| """Generates aliases for the original, deprecated naming scheme."""
gen.line('// Aliases for the deprecated namespaces.')
gen.line('namespace generated {')
gen.line()
for service in services:
gen.line('template <typename Implementation>')
gen.line(f'using {service.name()} = pw_rpc::... | ')
with gen.indent():
gen.line(f'return &ServiceImpl::{method.name()};')
gen.line('}')
gen.method_info_specialization(method)
gen.line('};')
gen.line()
def _generate_deprecated_aliases(gen: CodeGenerator,
services: ... | 68 | 68 | 228 | 23 | 45 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _generate_deprecated_aliases | _generate_deprecated_aliases | 288 | 315 | 288 | 289 | 1114b588fff5cd32804126171c016a6587946301 | bigcode/the-stack | train |
fa84e6c46d879363788fd47a | train | function | def package_stubs(proto_package: ProtoNode, output: OutputFile,
stub_generator: StubGenerator) -> None:
"""Generates the RPC stubs for a package."""
if proto_package.cpp_namespace():
file_ns = proto_package.cpp_namespace()
if file_ns.startswith('::'):
file_ns = file... | def package_stubs(proto_package: ProtoNode, output: OutputFile,
stub_generator: StubGenerator) -> None:
| """Generates the RPC stubs for a package."""
if proto_package.cpp_namespace():
file_ns = proto_package.cpp_namespace()
if file_ns.startswith('::'):
file_ns = file_ns[2:]
start_ns = lambda: output.write_line(f'namespace {file_ns} {{\n')
finish_ns = lambda: output.writ... | _/ / /_/ (__ )_/
/____/\__/\__,_/_.___/____(_)
*/
// This section provides stub implementations of the RPC services in this file.
// The code below may be referenced or copied to serve as a starting point for
// your RPC service implementations.
'''
def package_stubs(proto_package: ProtoNode, output: OutputFile,
... | 83 | 84 | 282 | 25 | 58 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | package_stubs | package_stubs | 469 | 509 | 469 | 470 | c08cb9d2a0ee5fc2c91edc224bbc9ed6d5da6d8b | bigcode/the-stack | train |
aec5f1716b795d8429b1e3e0 | train | function | def _generate_service(gen: CodeGenerator, service: ProtoService) -> None:
"""Generates a C++ class for an RPC service."""
base_class = f'{RPC_NAMESPACE}::Service'
gen.line('// The RPC service base class.')
gen.line(
'// Inherit from this to implement an RPC service for a pw_rpc server.'
)
... | def _generate_service(gen: CodeGenerator, service: ProtoService) -> None:
| """Generates a C++ class for an RPC service."""
base_class = f'{RPC_NAMESPACE}::Service'
gen.line('// The RPC service base class.')
gen.line(
'// Inherit from this to implement an RPC service for a pw_rpc server.'
)
gen.line('template <typename Implementation>')
gen.line(f'class Ser... | .
if gen.name() == 'nanopb':
gen.line(f'namespace {gen.name()} {{')
gen.line()
for service in services:
gen.line(f'using {service.name()}Client = '
f'pw_rpc::{gen.name()}::{service.name()}::Client;')
gen.line()
gen.line(f'}} // namespace {g... | 98 | 99 | 330 | 17 | 81 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _generate_service | _generate_service | 318 | 366 | 318 | 318 | 6c0132dc7c76e3a3129f7fb73a114199fa3a3cf6 | bigcode/the-stack | train |
5cec538f315e327197fe443d | train | function | def _generate_client(gen: CodeGenerator, service: ProtoService) -> None:
gen.line('// The Client is used to invoke RPCs for this service.')
gen.line(f'class Client final : public {RPC_NAMESPACE}::internal::'
'ServiceClient {')
gen.line(' public:')
with gen.indent():
gen.line(f'cons... | def _generate_client(gen: CodeGenerator, service: ProtoService) -> None:
| gen.line('// The Client is used to invoke RPCs for this service.')
gen.line(f'class Client final : public {RPC_NAMESPACE}::internal::'
'ServiceClient {')
gen.line(' public:')
with gen.indent():
gen.line(f'constexpr Client({RPC_NAMESPACE}::Client& client,'
' uint32_... | (
f'"{method.service().proto_path()}.{method.name()}" is not a '
f'valid method name! The name "{method.name()}" is reserved '
'for internal use by pw_rpc.')
def _generate_client(gen: CodeGenerator, service: ProtoService) -> None:
| 63 | 64 | 207 | 17 | 46 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _generate_client | _generate_client | 227 | 252 | 227 | 227 | fa83805e6464c6e4a9a5bc48433a927915a76914 | bigcode/the-stack | train |
2b033bc405ff237a7c270e97 | train | function | def _check_method_name(method: ProtoServiceMethod) -> None:
if method.name() in ('Service', 'Client'):
raise ValueError(
f'"{method.service().proto_path()}.{method.name()}" is not a '
f'valid method name! The name "{method.name()}" is reserved '
'for internal use by pw_rp... | def _check_method_name(method: ProtoServiceMethod) -> None:
| if method.name() in ('Service', 'Client'):
raise ValueError(
f'"{method.service().proto_path()}.{method.name()}" is not a '
f'valid method name! The name "{method.name()}" is reserved '
'for internal use by pw_rpc.')
| )
with gen.indent():
gen.line(f'// Hash of "{service.proto_path()}".')
gen.line(f'static constexpr uint32_t kServiceId = {get_id(service)};')
gen.line('};')
def _check_method_name(method: ProtoServiceMethod) -> None:
| 64 | 64 | 76 | 14 | 50 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _check_method_name | _check_method_name | 219 | 224 | 219 | 219 | 6560b1752856c5e91e96410f5ab08bdbe5d7b862 | bigcode/the-stack | train |
cb5a346bb543cc04e4d7db8e | train | function | def _method_lookup_table(gen: CodeGenerator, service: ProtoService) -> None:
"""Generates array of method IDs for looking up methods at compile time."""
gen.line('static constexpr std::array<uint32_t, '
f'{len(service.methods())}> kPwRpcMethodIds = {{')
with gen.indent(4):
for method i... | def _method_lookup_table(gen: CodeGenerator, service: ProtoService) -> None:
| """Generates array of method IDs for looking up methods at compile time."""
gen.line('static constexpr std::array<uint32_t, '
f'{len(service.methods())}> kPwRpcMethodIds = {{')
with gen.indent(4):
for method in service.methods():
gen.line(f'{get_id(method)}, // Hash of "{m... | 4):
for method in service.methods():
gen.method_descriptor(method)
gen.line('};\n')
# Generate the method lookup table
_method_lookup_table(gen, service)
gen.line('};')
def _method_lookup_table(gen: CodeGenerator, service: ProtoService) -> None:
| 64 | 64 | 104 | 18 | 46 | curtin-space/pigweed | pw_rpc/py/pw_rpc/codegen.py | Python | _method_lookup_table | _method_lookup_table | 369 | 378 | 369 | 369 | 767d2bf39ce9ff4794a52a1e90eaf98318780050 | bigcode/the-stack | train |
7944761eb0595c7820acc122 | train | class | class NetworkSecurityGroup(Resource):
"""NetworkSecurityGroup resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype ty... | class NetworkSecurityGroup(Resource):
| """NetworkSecurityGroup resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource ... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 90 | 237 | 792 | 6 | 83 | JonathanGailliez/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_07_01/models/network_security_group_py3.py | Python | NetworkSecurityGroup | NetworkSecurityGroup | 15 | 86 | 15 | 15 | 2ffa2494429cb274a8ffa3c2442fe64e8872f170 | bigcode/the-stack | train |
72eb40f840333f42bbf8b60a | train | function | @pytest.fixture()
def runner(app):
return app.test_cli_runner()
| @pytest.fixture()
def runner(app):
| return app.test_cli_runner()
| oped_session(options=options)
db.session = session
def teardown():
session.close()
transaction.rollback()
connection.close()
request.addfinalizer(teardown)
return session
@pytest.fixture(scope='function')
def test_client(app):
return app.test_client()
@pytest.fixture()
d... | 64 | 64 | 14 | 7 | 57 | candicecz/conp-portal | tests/conftest.py | Python | runner | runner | 79 | 81 | 79 | 80 | 64979dfdce2347cb9186b6bf3d4b19ccebd00c05 | bigcode/the-stack | train |
e493a17887d7983bbdf9ca21 | train | function | @pytest.fixture(scope='function')
def session(db, request):
"""
This creates a mock session
"""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection)
session = db.create_scoped_session(options=options)
db.session = session
def teardown()... | @pytest.fixture(scope='function')
def session(db, request):
| """
This creates a mock session
"""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection)
session = db.create_scoped_session(options=options)
db.session = session
def teardown():
session.close()
transaction.rollback()
... | _file):
os.unlink(test_db_file)
def teardown():
_db.drop_all()
os.unlink(test_db_file)
_db.app = app
_db.create_all()
request.addfinalizer(teardown)
return _db
@pytest.fixture(scope='function')
def session(db, request):
| 64 | 64 | 90 | 12 | 51 | candicecz/conp-portal | tests/conftest.py | Python | session | session | 52 | 71 | 52 | 53 | 56be29d242d10033a0f9c29be3bd39a1359b526d | bigcode/the-stack | train |
bc52b9526610f0caa84b8ef5 | train | function | @pytest.fixture(scope='session')
def db(app, request):
"""
This is creates the test db
"""
test_db_file = app.config['SQLALCHEMY_DATABASE_URI'].split(":///")[1]
if os.path.exists(test_db_file):
os.unlink(test_db_file)
def teardown():
_db.drop_all()
os.unlink(test_db_fil... | @pytest.fixture(scope='session')
def db(app, request):
| """
This is creates the test db
"""
test_db_file = app.config['SQLALCHEMY_DATABASE_URI'].split(":///")[1]
if os.path.exists(test_db_file):
os.unlink(test_db_file)
def teardown():
_db.drop_all()
os.unlink(test_db_file)
_db.app = app
_db.create_all()
request... | TestingConfig in Config.py
"""
app = create_app(config_settings=TestingConfig)
ctx = app.test_request_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
@pytest.fixture(scope='session')
def db(app, request):
| 64 | 64 | 104 | 12 | 51 | candicecz/conp-portal | tests/conftest.py | Python | db | db | 31 | 49 | 31 | 32 | 7a8e08d840cd4d8faf477b395d8583b3d3f868b0 | bigcode/the-stack | train |
88d39e45bed7639ad706250b | train | function | @pytest.fixture(scope='function')
def test_client(app):
return app.test_client()
| @pytest.fixture(scope='function')
def test_client(app):
| return app.test_client()
| options = dict(bind=connection)
session = db.create_scoped_session(options=options)
db.session = session
def teardown():
session.close()
transaction.rollback()
connection.close()
request.addfinalizer(teardown)
return session
@pytest.fixture(scope='function')
def test_clie... | 64 | 64 | 17 | 11 | 52 | candicecz/conp-portal | tests/conftest.py | Python | test_client | test_client | 74 | 76 | 74 | 75 | 3f87eec4e09a1c69dd5d9c46b3ad349ea823d320 | bigcode/the-stack | train |
c09c9e28a7f73b67c36d03ff | train | function | @pytest.fixture(scope='session')
def app(request):
"""
This is creates the mock app for testing, it uses the
TestingConfig in Config.py
"""
app = create_app(config_settings=TestingConfig)
ctx = app.test_request_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinal... | @pytest.fixture(scope='session')
def app(request):
| """
This is creates the mock app for testing, it uses the
TestingConfig in Config.py
"""
app = create_app(config_settings=TestingConfig)
ctx = app.test_request_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
| 8 -*-
"""
This is the initial module that contains the pytest configuration fixtures
"""
import pytest
import os
from app import create_app
from app import db as _db
from sqlalchemy import event
from sqlalchemy.orm import sessionmaker
from config import TestingConfig
@pytest.fixture(scope='session')
def app(request):
| 64 | 64 | 78 | 10 | 53 | candicecz/conp-portal | tests/conftest.py | Python | app | app | 14 | 28 | 14 | 15 | 11cab38869529afdb4492d02a6f7e1361acd8225 | bigcode/the-stack | train |
8e1e5f92a3ab20fd7c0a444d | train | function | def register_args(*args):
'''
Set `mit_argc` and `mit_argv`.
- args - an iterable of `str` and/or `bytes`.
'''
bargs = []
for arg in args:
if isinstance(arg, str):
arg = bytes(arg, 'utf-8')
assert isinstance(arg, bytes)
bargs.append(arg)
global argc, arg... | def register_args(*args):
| '''
Set `mit_argc` and `mit_argv`.
- args - an iterable of `str` and/or `bytes`.
'''
bargs = []
for arg in args:
if isinstance(arg, str):
arg = bytes(arg, 'utf-8')
assert isinstance(arg, bytes)
bargs.append(arg)
global argc, argv
argc.value = len(bar... | _extend(x):
if x & sign_bit:
x |= -1 & ~uword_max
return x
argc = c_int.in_dll(libmit, "mit_argc")
argv = POINTER(c_char_p).in_dll(libmit, "mit_argv")
def register_args(*args):
| 64 | 64 | 111 | 6 | 58 | rrthomas/m | python/mit/binding.py | Python | register_args | register_args | 140 | 154 | 140 | 140 | 312d14ec54c2af0d6635170b6de771ba9f5d73b6 | bigcode/the-stack | train |
2eafe87b8fc6a33a11a9c8fc | train | class | class Error(Exception):
'''
An error from the Python bindings for Mit.
'''
pass
| class Error(Exception):
| '''
An error from the Python bindings for Mit.
'''
pass
| :
# For Windows
# TODO: Do this portably
# TODO: Substitute version when library is versioned
library_file = find_library("libmit-0")
assert(library_file)
libmit = CDLL(library_file)
assert(libmit)
# Errors
class Error(Exception):
| 64 | 64 | 21 | 4 | 59 | rrthomas/m | python/mit/binding.py | Python | Error | Error | 32 | 36 | 32 | 32 | 045ecb7a354d1fb5d6dfd6645031bb4cb7de73ca | bigcode/the-stack | train |
475a1a6f29cc842e78b30fa4 | train | function | def errcheck(error_enum):
'''
Returns a callback suitable for use as `ctypes._FuncPtr.errcheck`.
- code_to_message - a mapping from int to message. If the message is
`None` the code is considered to be a success, and `None` is returned.
If the code is not found in `code_to_message`:
-... | def errcheck(error_enum):
| '''
Returns a callback suitable for use as `ctypes._FuncPtr.errcheck`.
- code_to_message - a mapping from int to message. If the message is
`None` the code is considered to be a success, and `None` is returned.
If the code is not found in `code_to_message`:
- if an "ok" code exists, a... | Mit.
'''
pass
class VMError(Error):
'''
An error from Mit.
Public fields:
- error_code - int
- message - str
'''
def __init__(self, error_code, message):
super().__init__(error_code, message)
def errcheck(error_enum):
| 67 | 67 | 225 | 6 | 61 | rrthomas/m | python/mit/binding.py | Python | errcheck | errcheck | 51 | 76 | 51 | 51 | 61b89e2698457ce9626f2653952c70a57c845c8c | bigcode/the-stack | train |
3c1556eb51afcb27f9d6e9fe | train | function | def run(pc, ir, stack, stack_words, stack_depth_ptr):
return mit_error(_run(pc, ir, stack, stack_words, stack_depth_ptr))
| def run(pc, ir, stack, stack_words, stack_depth_ptr):
| return mit_error(_run(pc, ir, stack, stack_words, stack_depth_ptr))
| _mit_fn.in_dll(libmit, "mit_run_fast")
# run_profile = c_mit_fn.in_dll(libmit, "mit_run_profile")
# Cannot add errcheck to a CFUNCTYPE, so wrap it manually.
def run(pc, ir, stack, stack_words, stack_depth_ptr):
| 64 | 64 | 34 | 15 | 49 | rrthomas/m | python/mit/binding.py | Python | run | run | 117 | 118 | 117 | 117 | e6f75c4f84822d061c4388fee241aa2dbf5c5101 | bigcode/the-stack | train |
c84e455b7e2cf9ec10dce389 | train | class | class VMError(Error):
'''
An error from Mit.
Public fields:
- error_code - int
- message - str
'''
def __init__(self, error_code, message):
super().__init__(error_code, message)
| class VMError(Error):
| '''
An error from Mit.
Public fields:
- error_code - int
- message - str
'''
def __init__(self, error_code, message):
super().__init__(error_code, message)
| library is versioned
library_file = find_library("libmit-0")
assert(library_file)
libmit = CDLL(library_file)
assert(libmit)
# Errors
class Error(Exception):
'''
An error from the Python bindings for Mit.
'''
pass
class VMError(Error):
| 64 | 64 | 54 | 5 | 58 | rrthomas/m | python/mit/binding.py | Python | VMError | VMError | 39 | 48 | 39 | 39 | 959502373a34353537af602f26aec59dd2fc0a2a | bigcode/the-stack | train |
96a572f47e588d7b10b60333 | train | function | def is_aligned(addr):
return (addr & (word_bytes - 1)) == 0
| def is_aligned(addr):
| return (addr & (word_bytes - 1)) == 0
| ):
return mit_error(_run(pc, ir, stack, stack_words, stack_depth_ptr))
# libmit.mit_profile_reset.restype = None
# libmit.mit_profile_reset.argtypes = None
# libmit.mit_profile_dump.argtypes = [c_int]
def is_aligned(addr):
| 64 | 64 | 22 | 6 | 58 | rrthomas/m | python/mit/binding.py | Python | is_aligned | is_aligned | 126 | 127 | 126 | 126 | 8a24a46e0cbb479f02e5a3002cb68242c01e70c3 | bigcode/the-stack | train |
12cab8f7e223dc2a4d2687b6 | train | function | def sign_extend(x):
if x & sign_bit:
x |= -1 & ~uword_max
return x
| def sign_extend(x):
| if x & sign_bit:
x |= -1 & ~uword_max
return x
| libmit.mit_profile_reset.restype = None
# libmit.mit_profile_reset.argtypes = None
# libmit.mit_profile_dump.argtypes = [c_int]
def is_aligned(addr):
return (addr & (word_bytes - 1)) == 0
def sign_extend(x):
| 64 | 64 | 27 | 5 | 58 | rrthomas/m | python/mit/binding.py | Python | sign_extend | sign_extend | 130 | 133 | 130 | 130 | 567d2c382258ce376dac94fcf6ebb4ff94088a1e | bigcode/the-stack | train |
6138c505e0690477f3c9cfb2 | train | function | @contextmanager
def databases_engine():
driver = os.environ["MS_SQL_ODBC_DRIVER"]
username = os.environ["MS_SQL_UHL_DWH_USER"]
password = os.environ["MS_SQL_UHL_DWH_PASSWORD"]
host = os.environ["MS_SQL_UHL_DWH_HOST"]
database = os.environ["MS_SQL_UHL_DWH_DATABASE"]
database_echo = os.environ["DATABASE_ECHO... | @contextmanager
def databases_engine():
| driver = os.environ["MS_SQL_ODBC_DRIVER"]
username = os.environ["MS_SQL_UHL_DWH_USER"]
password = os.environ["MS_SQL_UHL_DWH_PASSWORD"]
host = os.environ["MS_SQL_UHL_DWH_HOST"]
database = os.environ["MS_SQL_UHL_DWH_DATABASE"]
database_echo = os.environ["DATABASE_ECHO"] == 'True'
connectionstring = f'mssq... | orenames, PATINDEX('%[ -/]%', forenames + ' ') - 1) AS name
FROM DWREPO.dbo.PATIENT
) x
WHERE name IS NOT NULL
AND LEN(name) > 2
ORDER BY LOWER(name)
;
"""
@contextmanager
def databases_engine():
| 64 | 64 | 143 | 8 | 56 | LCBRU/ppi_finder | get_names.py | Python | databases_engine | databases_engine | 30 | 43 | 30 | 32 | c354895e6e6f33f353cc496032f0aa31fa19296e | bigcode/the-stack | train |
9fe235404b3339011f0df1d5 | train | function | def main():
with databases_engine() as conn:
names = {r for r, in conn.execute(NAMES_SQL)}
with open("_names.txt", "w") as outfile:
outfile.write("\n".join(names))
| def main():
| with databases_engine() as conn:
names = {r for r, in conn.execute(NAMES_SQL)}
with open("_names.txt", "w") as outfile:
outfile.write("\n".join(names))
| ["DATABASE_ECHO"] == 'True'
connectionstring = f'mssql+pyodbc://{username}:{password}@{host}/{database}?driver={driver.replace(" ", "+")}'
engine = create_engine(connectionstring, echo=database_echo)
yield engine
engine.dispose()
def main():
| 64 | 64 | 48 | 3 | 61 | LCBRU/ppi_finder | get_names.py | Python | main | main | 46 | 51 | 46 | 46 | ad52a680425417741d1d614d55bc9ffbfee5586a | bigcode/the-stack | train |
7f121a9693fc0c962832fa06 | train | class | @skipIf(NO_MOCK, NO_MOCK_REASON)
class SensehatBeaconTestCase(TestCase, LoaderModuleMockMixin):
'''
Test case for salt.beacons.[s]
'''
def setup_loader_modules(self):
self.HUMIDITY_MOCK = MagicMock(return_value=80)
self.TEMPERATURE_MOCK = MagicMock(return_value=30)
self.PRESSUR... | @skipIf(NO_MOCK, NO_MOCK_REASON)
class SensehatBeaconTestCase(TestCase, LoaderModuleMockMixin):
| '''
Test case for salt.beacons.[s]
'''
def setup_loader_modules(self):
self.HUMIDITY_MOCK = MagicMock(return_value=80)
self.TEMPERATURE_MOCK = MagicMock(return_value=30)
self.PRESSURE_MOCK = MagicMock(return_value=1500)
self.addCleanup(delattr, self, 'HUMIDITY_MOCK')
... | # coding: utf-8
# Python libs
from __future__ import absolute_import
# Salt testing libs
from tests.support.unit import skipIf, TestCase
from tests.support.mock import NO_MOCK, NO_MOCK_REASON, MagicMock
from tests.support.mixins import LoaderModuleMockMixin
# Salt libs
import salt.beacons.sensehat as sensehat
@skipI... | 104 | 204 | 680 | 26 | 77 | byteskeptical/salt | tests/unit/beacons/test_sensehat.py | Python | SensehatBeaconTestCase | SensehatBeaconTestCase | 15 | 109 | 15 | 16 | ada01321c822e4cd694800077c1023e96fc79fba | bigcode/the-stack | train |
a6448e75631d75be60c2a8cf | train | class | class Migration(migrations.Migration):
dependencies = [
('base', '0026_auto_20201003_2209'),
]
operations = [
migrations.AlterField(
model_name='schedule',
name='duration',
field=models.IntegerField(choices=[(900, '15min'), (1800, '30min'), (2700, '45min... | class Migration(migrations.Migration):
| dependencies = [
('base', '0026_auto_20201003_2209'),
]
operations = [
migrations.AlterField(
model_name='schedule',
name='duration',
field=models.IntegerField(choices=[(900, '15min'), (1800, '30min'), (2700, '45min'), (3600, '60min'), (4500, '75min'), (5... | # Generated by Django 3.0.6 on 2020-10-04 01:13
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 104 | 348 | 7 | 30 | arantesdv/LaeliaAppProject | Laelia/apps/base/migrations/0027_auto_20201003_2213.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | 357ed6d6ec9787fc081862afbcc4dcd7e17b3342 | bigcode/the-stack | train |
3477fa67d2d0f17de737bb58 | train | class | class RMSE(MSE):
def __init__(self):
super().__init__()
self.name = "Root Mean Squared Error"
# calculates MSE and takes square root
def get_error(self, cover_image, stego_image):
mean_squared_error = self.calculate_image_error(cover_image, stego_image)
root_mean_squared... | class RMSE(MSE):
| def __init__(self):
super().__init__()
self.name = "Root Mean Squared Error"
# calculates MSE and takes square root
def get_error(self, cover_image, stego_image):
mean_squared_error = self.calculate_image_error(cover_image, stego_image)
root_mean_squared_error = math.sqrt... | """
Root Mean Squared Error (MSE)
Calculates the RMSE between a cover and stego image
"""
import cv2
import math
from MSE import MSE
class RMSE(MSE):
| 44 | 64 | 88 | 6 | 37 | FaiZaman/Steganograph-app-y | evaluation/imperceptibility/RMSE.py | Python | RMSE | RMSE | 10 | 23 | 10 | 11 | 933abd226afbbc4a0252c67396607decbc64548f | bigcode/the-stack | train |
7e859a1390ebf98c06339fbe | train | class | class TestBuildOrderDeviation(unittest.TestCase):
#region time_deviation
def test_time_deviation_calculated_correctly_when_late_on_time(self):
golden_bo = []
compare_bo = []
golden_bo.append(BuildOrderElement(1, 'Probe', 12, 0, 0))
golden_bo.append(BuildOrderElement(2, 'A... | class TestBuildOrderDeviation(unittest.TestCase):
#region time_deviation
| def test_time_deviation_calculated_correctly_when_late_on_time(self):
golden_bo = []
compare_bo = []
golden_bo.append(BuildOrderElement(1, 'Probe', 12, 0, 0))
golden_bo.append(BuildOrderElement(2, 'Assimilator', 15, 50, 200))
compare_bo.append(BuildOrderElement(1, 'Pro... | import os
import sys
if __name__ == '__main__':
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)))
if sys.version_info[:2] < (2, 7):
import unittest2 as unittest
else:
import unittest
import metrics
from metrics.bod import BuildOrderDeviatio... | 113 | 256 | 9,884 | 15 | 97 | matthewj8489/Starcraft2Metrics | tests/unit/test_bod.py | Python | TestBuildOrderDeviation | TestBuildOrderDeviation | 17 | 879 | 17 | 20 | 524c36207fcdda820eef1014d4d879d5b2bc8f49 | bigcode/the-stack | train |
927023ac7e01a1195e6c6495 | train | function | def deprecated(reason):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
"""
if isinstance(reason, string_types):
# The @deprecated is used with a 'reason'.
#
# .. code-block:... | def deprecated(reason):
| """
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
"""
if isinstance(reason, string_types):
# The @deprecated is used with a 'reason'.
#
# .. code-block:: python
#
... | import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def deprecated(reason):
| 25 | 136 | 455 | 4 | 21 | rudimeier/BrainStat | surfstat/python/deprecated.py | Python | deprecated | deprecated | 8 | 78 | 8 | 8 | 7c0cf21c7af6fe8b8be15c0446929356427b8901 | bigcode/the-stack | train |
f1e92d2d8938c94c5e0e4d33 | train | class | class TreeNode(object):
"""A node in the MCTS tree. Each node keeps track of its own value Q, prior probability P, and
its visit-count-adjusted prior score u.
"""
def __init__(self, parent, prior_p):
self._parent = parent
self._children = {} # a map from action to TreeNode
self... | class TreeNode(object):
| """A node in the MCTS tree. Each node keeps track of its own value Q, prior probability P, and
its visit-count-adjusted prior score u.
"""
def __init__(self, parent, prior_p):
self._parent = parent
self._children = {} # a map from action to TreeNode
self._n_visits = 0
s... | """Monte Carlo Tree Search, as described in Silver et al 2015.
This is a "pure" implementation of the AlphaGo MCTS algorithm in that it is not specific to the
game of Go; everything in this file is implemented generically with respect to some state, actions,
policy function, and value function.
"""
import numpy as np
... | 83 | 210 | 701 | 5 | 77 | sjkim04/AlphaGOZero-python-tensorflow | support/RocAlphaGo-develop/AlphaGo/mcts.py | Python | TreeNode | TreeNode | 11 | 91 | 11 | 11 | 01cb1e7f7f9f8de6fcf013b0ec45827e5606df61 | bigcode/the-stack | train |
c1b69bd8bfd5536e97cd2687 | train | class | class ParallelMCTS(MCTS):
pass
| class ParallelMCTS(MCTS):
| pass
| be garbage-collected.
"""
if last_move in self._root._children:
self._root = self._root._children[last_move]
self._root._parent = None
else:
self._root = TreeNode(None, 1.0)
class ParallelMCTS(MCTS):
| 64 | 64 | 10 | 7 | 57 | sjkim04/AlphaGOZero-python-tensorflow | support/RocAlphaGo-develop/AlphaGo/mcts.py | Python | ParallelMCTS | ParallelMCTS | 219 | 220 | 219 | 219 | a47ae282f6080380f061b3777a4b8ffecc5fccc2 | bigcode/the-stack | train |
b0e14fb3c9a950192ff73602 | train | class | class MCTS(object):
"""A simple (and slow) single-threaded implementation of Monte Carlo Tree Search.
Search works by exploring moves randomly according to the given policy up to a certain
depth, which is relatively small given the search space. "Leaves" at this depth are assigned a
value comprising a ... | class MCTS(object):
| """A simple (and slow) single-threaded implementation of Monte Carlo Tree Search.
Search works by exploring moves randomly according to the given policy up to a certain
depth, which is relatively small given the search space. "Leaves" at this depth are assigned a
value comprising a weighted combination... | u is not normalized to be a distribution.
if not self.is_root():
self._u = c_puct * self._P * np.sqrt(self._parent._n_visits) / (1 + self._n_visits)
def update_recursive(self, leaf_value, c_puct):
"""Like a call to update(), but applied recursively for all ancestors.
Note: it ... | 256 | 256 | 1,354 | 5 | 250 | sjkim04/AlphaGOZero-python-tensorflow | support/RocAlphaGo-develop/AlphaGo/mcts.py | Python | MCTS | MCTS | 94 | 216 | 94 | 94 | 2a2e9831ae9f84de8a0fbeb422c063f3ab235d35 | bigcode/the-stack | train |
565e89caa608175bf1cda569 | train | function | def test_bench():
main(fast=True)
| def test_bench():
| main(fast=True)
| from ..bench import main
def test_bench():
| 11 | 64 | 11 | 5 | 5 | lpsinger/astropy-healpix | astropy_healpix/tests/test_bench.py | Python | test_bench | test_bench | 4 | 5 | 4 | 4 | 5cd3a820ced62c05f36cf3d1259664d60ff0427d | bigcode/the-stack | train |
3823e035c387dd6374ba40c9 | train | class | class AuthFail(RbacError):
def __init__(self,msg="Authentication fail",id=USER_PW_INVLD, **kw):
super().__init__(msg=msg,id=id,**kw)
| class AuthFail(RbacError):
| def __init__(self,msg="Authentication fail",id=USER_PW_INVLD, **kw):
super().__init__(msg=msg,id=id,**kw)
| : 2022 - Symas Corporation
'''
from ..util import RbacError
from ..util.global_ids import USER_PW_INVLD,USER_PW_CHK_FAILED
class NotFound(RbacError):
pass
class NotUnique(RbacError):
pass
class AuthFail(RbacError):
| 64 | 64 | 43 | 7 | 56 | shawnmckinney/py-fortress | rbac/file/fileex.py | Python | AuthFail | AuthFail | 14 | 16 | 14 | 14 | 58f90687782ab47a8fefd3a0bbcd19b70284e581 | bigcode/the-stack | train |
0eed375b0072983c2aaa1f55 | train | class | class AuthError(RbacError):
def __init__(self,msg="Authentication error",id=USER_PW_CHK_FAILED, **kw):
super().__init__(msg=msg,id=id,**kw)
| class AuthError(RbacError):
| def __init__(self,msg="Authentication error",id=USER_PW_CHK_FAILED, **kw):
super().__init__(msg=msg,id=id,**kw)
| ):
pass
class NotUnique(RbacError):
pass
class AuthFail(RbacError):
def __init__(self,msg="Authentication fail",id=USER_PW_INVLD, **kw):
super().__init__(msg=msg,id=id,**kw)
class AuthError(RbacError):
| 64 | 64 | 44 | 7 | 57 | shawnmckinney/py-fortress | rbac/file/fileex.py | Python | AuthError | AuthError | 18 | 20 | 18 | 18 | 648b2805f5da0ee49b2d9b530009eefd090a5ded | bigcode/the-stack | train |
1edb11656f749cb955bd5302 | train | class | class NotUnique(RbacError):
pass
| class NotUnique(RbacError):
| pass
| '''
@copyright: 2022 - Symas Corporation
'''
from ..util import RbacError
from ..util.global_ids import USER_PW_INVLD,USER_PW_CHK_FAILED
class NotFound(RbacError):
pass
class NotUnique(RbacError):
| 57 | 64 | 10 | 7 | 49 | shawnmckinney/py-fortress | rbac/file/fileex.py | Python | NotUnique | NotUnique | 11 | 12 | 11 | 11 | 487aebb927649b3605b30d883bf6250d5a1618b0 | bigcode/the-stack | train |
88aad34e782f2355da385041 | train | class | class NotFound(RbacError):
pass
| class NotFound(RbacError):
| pass
| '''
@copyright: 2022 - Symas Corporation
'''
from ..util import RbacError
from ..util.global_ids import USER_PW_INVLD,USER_PW_CHK_FAILED
class NotFound(RbacError):
| 47 | 64 | 10 | 7 | 39 | shawnmckinney/py-fortress | rbac/file/fileex.py | Python | NotFound | NotFound | 8 | 9 | 8 | 8 | 694385575ccf0e2589e84d6dd04dfce51af52148 | bigcode/the-stack | train |
59e94b575bf102e6d5e88e96 | train | function | def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
| def conv3x3(in_planes, out_planes, stride=1):
| """3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
| import torch
import torch.nn as nn
import time
def conv3x3(in_planes, out_planes, stride=1):
| 27 | 64 | 53 | 15 | 11 | luk-ai-420/ExcelFIT_project | cor_src/cor_LSTM_network.py | Python | conv3x3 | conv3x3 | 6 | 9 | 6 | 6 | c528404493d0c64a6a3efc3ebfd94c3192386a34 | bigcode/the-stack | train |
00c3ee360371113be5775e81 | train | function | def cor_LSTM_resnet34(num_classes,frame_num,grayscale):
"""Constructs a ResNet-34 model."""
model = LSTM_ResNet(block=BasicBlock,
layers=[3, 4, 6, 3],
num_classes=num_classes,
frame_num = frame_num,
grayscale=grayscale)
retur... | def cor_LSTM_resnet34(num_classes,frame_num,grayscale):
| """Constructs a ResNet-34 model."""
model = LSTM_ResNet(block=BasicBlock,
layers=[3, 4, 6, 3],
num_classes=num_classes,
frame_num = frame_num,
grayscale=grayscale)
return model | STM_t + time.time() - start_t)/2
logits = self.fc(x)
logits = logits + self.linear_1_bias
probas = torch.sigmoid(logits)
return logits, probas
def cor_LSTM_resnet34(num_classes,frame_num,grayscale):
| 64 | 64 | 77 | 16 | 47 | luk-ai-420/ExcelFIT_project | cor_src/cor_LSTM_network.py | Python | cor_LSTM_resnet34 | cor_LSTM_resnet34 | 129 | 136 | 129 | 129 | 23cbd3af1dc68d236aa8ee299012fc329fe29c5e | bigcode/the-stack | train |
2008fb946183fe2b3d95b4a7 | train | class | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.... | class BasicBlock(nn.Module):
| expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes... | nn
import time
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
| 64 | 64 | 208 | 6 | 58 | luk-ai-420/ExcelFIT_project | cor_src/cor_LSTM_network.py | Python | BasicBlock | BasicBlock | 11 | 40 | 11 | 11 | 08fb2c036fc2f6d7643062349b379b8d968291d7 | bigcode/the-stack | train |
daa59e9655278bbfad87a0cd | train | class | class LSTM_ResNet(nn.Module):
def __init__(self, block, layers, num_classes,frame_num, grayscale):
self.num_classes = num_classes
self.inplanes = 64
self.LSTMlayer_num = 2
self.LSTMframe_num = frame_num
self.LSTMinputsize = 2048
self.LSTMhiddensize = 2048
... | class LSTM_ResNet(nn.Module):
| def __init__(self, block, layers, num_classes,frame_num, grayscale):
self.num_classes = num_classes
self.inplanes = 64
self.LSTMlayer_num = 2
self.LSTMframe_num = frame_num
self.LSTMinputsize = 2048
self.LSTMhiddensize = 2048
self.average_LSTM_t = 0
... | .Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes,... | 243 | 243 | 812 | 9 | 233 | luk-ai-420/ExcelFIT_project | cor_src/cor_LSTM_network.py | Python | LSTM_ResNet | LSTM_ResNet | 42 | 127 | 42 | 43 | ebcbf9100ce1bc1f46f6942a1a1e84d06a22b79f | bigcode/the-stack | train |
21aa986d7b3bb95fb3eb4642 | train | function | def test_diet_check_option_prints_configuration():
expected = """\
commands:
optipng: {0}/optipng
pipelines:
png:
- optipng
""".format(TOOLS_DIR)
helpers.TOOLS = ('optipng',)
runner = CliRunner()
result = runner.invoke(diet.diet, ['--check'])
assert result.output == expected
assert resu... | def test_diet_check_option_prints_configuration():
| expected = """\
commands:
optipng: {0}/optipng
pipelines:
png:
- optipng
""".format(TOOLS_DIR)
helpers.TOOLS = ('optipng',)
runner = CliRunner()
result = runner.invoke(diet.diet, ['--check'])
assert result.output == expected
assert result.exit_code == 0
| OLS_DIR', '/usr/local/bin')
TEST_DIR = abspath(dirname(__file__))
TEST_FILES_DIR = join(TEST_DIR, 'test_files')
TEST_FILE = join(TEST_FILES_DIR, 'nature.png')
TEST_CONFIG = join(TEST_FILES_DIR, 'config2.yaml')
def test_diet_check_option_prints_configuration():
| 64 | 64 | 96 | 10 | 54 | biopredictive/pyimagediet | tests/test_scripts.py | Python | test_diet_check_option_prints_configuration | test_diet_check_option_prints_configuration | 18 | 33 | 18 | 18 | c0a45834d7823d435826bd7ce1dd03960761742e | bigcode/the-stack | train |
9dec0ad226129ac24eaf5e88 | train | function | def test_diet_complains_if_no_file_is_provided():
err = 'Usage: diet [OPTIONS] FILE\n\nError: Missing argument "file".\n'
runner = CliRunner()
result = runner.invoke(diet.diet, ['--config', TEST_CONFIG])
assert result.output == err
assert result.exit_code == 2
| def test_diet_complains_if_no_file_is_provided():
| err = 'Usage: diet [OPTIONS] FILE\n\nError: Missing argument "file".\n'
runner = CliRunner()
result = runner.invoke(diet.diet, ['--config', TEST_CONFIG])
assert result.output == err
assert result.exit_code == 2
| ] FILE\n\nError: Missing option "--config".\n'
runner = CliRunner()
result = runner.invoke(diet.diet, [TEST_FILE])
assert result.output == err
assert result.exit_code == 2
def test_diet_complains_if_no_file_is_provided():
| 64 | 64 | 76 | 14 | 49 | biopredictive/pyimagediet | tests/test_scripts.py | Python | test_diet_complains_if_no_file_is_provided | test_diet_complains_if_no_file_is_provided | 44 | 50 | 44 | 44 | 0c17c12381156910421762a913399ff54ec68bee | bigcode/the-stack | train |
4f9c6400379c12cd721ba0ff | train | function | def test_diet_squeezes_file():
backup = process.backup_file(TEST_FILE, 'back')
assert filecmp.cmp(TEST_FILE, backup)
try:
runner = CliRunner()
result = runner.invoke(diet.diet, ['--config', TEST_CONFIG, backup])
assert not filecmp.cmp(TEST_FILE, backup)
assert result.exit_c... | def test_diet_squeezes_file():
| backup = process.backup_file(TEST_FILE, 'back')
assert filecmp.cmp(TEST_FILE, backup)
try:
runner = CliRunner()
result = runner.invoke(diet.diet, ['--config', TEST_CONFIG, backup])
assert not filecmp.cmp(TEST_FILE, backup)
assert result.exit_code == 0
finally:
o... | OPTIONS] FILE\n\nError: Missing argument "file".\n'
runner = CliRunner()
result = runner.invoke(diet.diet, ['--config', TEST_CONFIG])
assert result.output == err
assert result.exit_code == 2
def test_diet_squeezes_file():
| 64 | 64 | 92 | 10 | 53 | biopredictive/pyimagediet | tests/test_scripts.py | Python | test_diet_squeezes_file | test_diet_squeezes_file | 53 | 64 | 53 | 53 | 4bbeb4060f79b6f218fd5399b9567862ec102716 | bigcode/the-stack | train |
bb6d7fafe684566aaaeaa307 | train | function | def test_diet_complains_if_no_configuration_provided():
err = 'Usage: diet [OPTIONS] FILE\n\nError: Missing option "--config".\n'
runner = CliRunner()
result = runner.invoke(diet.diet, [TEST_FILE])
assert result.output == err
assert result.exit_code == 2
| def test_diet_complains_if_no_configuration_provided():
| err = 'Usage: diet [OPTIONS] FILE\n\nError: Missing option "--config".\n'
runner = CliRunner()
result = runner.invoke(diet.diet, [TEST_FILE])
assert result.output == err
assert result.exit_code == 2
| TOOLS_DIR)
helpers.TOOLS = ('optipng',)
runner = CliRunner()
result = runner.invoke(diet.diet, ['--check'])
assert result.output == expected
assert result.exit_code == 0
def test_diet_complains_if_no_configuration_provided():
| 64 | 64 | 72 | 13 | 50 | biopredictive/pyimagediet | tests/test_scripts.py | Python | test_diet_complains_if_no_configuration_provided | test_diet_complains_if_no_configuration_provided | 36 | 41 | 36 | 36 | 4dddc4a66bed9a8c0d0fbbdcc8b8e1f84e9f22ec | bigcode/the-stack | train |
50828e9dcfc62fa9c85b3a97 | train | class | class IlluminaToPCLTestCase(TestCase, testing_utils.ProcessorJobTestCaseMixin):
@tag("illumina")
def test_illumina_to_pcl(self):
"""Most basic Illumina to PCL test"""
organism = Organism(name="HOMO_SAPIENS", taxonomy_id=9606, is_scientific_name=True)
organism.save()
job = prepa... | class IlluminaToPCLTestCase(TestCase, testing_utils.ProcessorJobTestCaseMixin):
@tag("illumina")
| def test_illumina_to_pcl(self):
"""Most basic Illumina to PCL test"""
organism = Organism(name="HOMO_SAPIENS", taxonomy_id=9606, is_scientific_name=True)
organism.save()
job = prepare_illumina_job({**GSE22427, "organism": organism})
# Remove the title of one of the samples... | ID_REF",
"LV-C&si-Control-1",
"Detection Pval",
"LV-C&si-Control-2",
"Detection Pval",
"LV-C&si-Control-3",
"Detection Pval",
"LV-C&si-EZH2-1",
"Detection Pval",
"LV-C&si-EZH2-2",
"Detection Pval",
"LV-C&si-EZH2-3",
"Detection Pval",
"LV-EZH2&si-EZH2-1",
"Detectio... | 256 | 256 | 4,261 | 28 | 228 | AlexsLemonade/refinebio | workers/data_refinery_workers/processors/test_illumina.py | Python | IlluminaToPCLTestCase | IlluminaToPCLTestCase | 152 | 552 | 152 | 153 | 537df3d3c346dd8220ef34926227215565520978 | bigcode/the-stack | train |
859d533bbda113f2d42880f1 | train | function | def prepare_illumina_job(job_info: Dict) -> ProcessorJob:
pj = ProcessorJob()
pj.pipeline_applied = "ILLUMINA_TO_PCL"
pj.save()
og_file = OriginalFile()
og_file.source_filename = job_info["source_filename"]
og_file.filename = job_info["filename"]
og_file.absolute_file_path = job_info["absol... | def prepare_illumina_job(job_info: Dict) -> ProcessorJob:
| pj = ProcessorJob()
pj.pipeline_applied = "ILLUMINA_TO_PCL"
pj.save()
og_file = OriginalFile()
og_file.source_filename = job_info["source_filename"]
og_file.filename = job_info["filename"]
og_file.absolute_file_path = job_info["absolute_file_path"]
og_file.is_downloaded = True
og_fi... | import os
import os.path
import shutil
import tempfile
from typing import Dict
from django.test import TestCase, tag
from data_refinery_common.enums import PipelineEnum
from data_refinery_common.models import (
Organism,
OriginalFile,
OriginalFileSampleAssociation,
Pipeline,
ProcessorJob,
Proc... | 112 | 112 | 375 | 15 | 96 | AlexsLemonade/refinebio | workers/data_refinery_workers/processors/test_illumina.py | Python | prepare_illumina_job | prepare_illumina_job | 24 | 72 | 24 | 24 | 49058f6fd3a8120ce7a9ef68aceaae4c7c407bf2 | bigcode/the-stack | train |
26b982cdfdf1c65138bd7e27 | train | function | def _make_original_file_with_contents(contents: str) -> OriginalFile:
_, path = tempfile.mkstemp(suffix=".txt")
with open(path, "w") as f:
f.write(contents)
og_file = OriginalFile()
og_file.source_filename = path
og_file.filename = os.path.basename(path)
og_file.absolute_file_path = os.... | def _make_original_file_with_contents(contents: str) -> OriginalFile:
| _, path = tempfile.mkstemp(suffix=".txt")
with open(path, "w") as f:
f.write(contents)
og_file = OriginalFile()
og_file.source_filename = path
og_file.filename = os.path.basename(path)
og_file.absolute_file_path = os.path.realpath(path)
og_file.is_downloaded = True
og_file.save(... | [title]}
sa.is_ccdl = False
sa.save()
sample_assoc = OriginalFileSampleAssociation()
sample_assoc.original_file = og_file
sample_assoc.sample = sample
sample_assoc.save()
return pj
def _make_original_file_with_contents(contents: str) -> OriginalFile:
| 64 | 64 | 101 | 15 | 48 | AlexsLemonade/refinebio | workers/data_refinery_workers/processors/test_illumina.py | Python | _make_original_file_with_contents | _make_original_file_with_contents | 75 | 87 | 75 | 75 | 74d4e128b05387b6f8be20edb0fdda726672231e | bigcode/the-stack | train |
5ac9ef9988a31d1c5eecf6a3 | train | function | def _try_sanitizing_file(file: str) -> str:
pj = ProcessorJob()
pj.pipeline_applied = "ILLUMINA_TO_PCL"
pj.save()
og_file = _make_original_file_with_contents(file)
job_context = illumina._prepare_files({"job_id": pj.pk, "original_files": [og_file], "job": pj})
job_context = illumina._detect_en... | def _try_sanitizing_file(file: str) -> str:
| pj = ProcessorJob()
pj.pipeline_applied = "ILLUMINA_TO_PCL"
pj.save()
og_file = _make_original_file_with_contents(file)
job_context = illumina._prepare_files({"job_id": pj.pk, "original_files": [og_file], "job": pj})
job_context = illumina._detect_encoding(job_context)
return illumina._san... | og_file.source_filename = path
og_file.filename = os.path.basename(path)
og_file.absolute_file_path = os.path.realpath(path)
og_file.is_downloaded = True
og_file.save()
return og_file
def _try_sanitizing_file(file: str) -> str:
| 64 | 64 | 102 | 14 | 49 | AlexsLemonade/refinebio | workers/data_refinery_workers/processors/test_illumina.py | Python | _try_sanitizing_file | _try_sanitizing_file | 90 | 99 | 90 | 90 | 414d8006f3071cf2578fa6e4848608ab43a9fb11 | bigcode/the-stack | train |
bbf2f38fbbc5b529caa20e8e | train | class | class LongitudinalController:
"""
Longitudinal Controller using PID.
"""
def __init__(self):
self.error_history = []
def __call__(self, target_speed, speed, dist):
a = longitudinal_pid_P_gain * (target_speed - speed)
if dist < 10.0:
if speed > 3.0:
... | class LongitudinalController:
| """
Longitudinal Controller using PID.
"""
def __init__(self):
self.error_history = []
def __call__(self, target_speed, speed, dist):
a = longitudinal_pid_P_gain * (target_speed - speed)
if dist < 10.0:
if speed > 3.0:
a = -2.5
elif ... | import numpy as np
from fcutils.maths import derivative
from control_fc.config import (
longitudinal_pid_P_gain,
longitudinal_pid_D_gain,
longitudinal_pid_I_gain,
)
"""
Trajectory analyzer and longitudinal PID controller for LQR based
control scripts
"""
class LongitudinalController:
| 63 | 92 | 308 | 6 | 57 | FedeClaudi/LocomotionControl | archive/control/_control.py | Python | LongitudinalController | LongitudinalController | 19 | 62 | 19 | 19 | 6fd84c67ddd71fd3acc42286878be16f842f2911 | bigcode/the-stack | train |
076397b00e6081ccc2e30af6 | train | function | @trace()
def plot_timestep_accuracy(directory: str, accumulator: Accumulator, timestep_labels: list = None):
"""Plots the average accuracy for each timestep as a bar chart.
Params:
- directory (str): The directory in which to save the plot
- timestep_accuracy (list): The average accuracy of predi... | @trace()
def plot_timestep_accuracy(directory: str, accumulator: Accumulator, timestep_labels: list = None):
| """Plots the average accuracy for each timestep as a bar chart.
Params:
- directory (str): The directory in which to save the plot
- timestep_accuracy (list): The average accuracy of predictions for each timestep
- timestep_labels (list): The labels for the timesteps
"""
if not accum... | .plot(x_range, precisions, label="Precision (final=%.2f)" % precisions[-1])
axes.plot(x_range, recalls, label="Recall(final=%.2f)" % recalls[-1])
axes.legend(loc='lower right')
figure.savefig(directory + constants.PLT_F1_SCORE)
# End of plot_f1_score()
@trace()
def plot_timestep_accuracy(directory: str... | 97 | 97 | 324 | 24 | 73 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | plot_timestep_accuracy | plot_timestep_accuracy | 126 | 156 | 126 | 127 | 6bdc1b719d5cb544705da354c0b4297f20da6bbc | bigcode/the-stack | train |
ac408d67c12b5796a01c207a | train | function | @trace()
def plot_training_accuracy(directory: str, training_accuracy: list, validation_accuracy: list):
"""Plots the training and validation prediction accuracy on a sublot.
Params:
- directory (str): The directory in which to save the plot
- training_accuracy (list): The list of training accura... | @trace()
def plot_training_accuracy(directory: str, training_accuracy: list, validation_accuracy: list):
| """Plots the training and validation prediction accuracy on a sublot.
Params:
- directory (str): The directory in which to save the plot
- training_accuracy (list): The list of training accuracies
- validation_accuracy (list): The list of validation accuracies
"""
figure, axes = setu... | Validation Loss (final=%.2f)" % validation_loss[-1])
axes.legend(loc='upper right')
figure.savefig(directory + constants.PLT_TRAIN_LOSS)
# End of plot_training_loss()
@trace()
def plot_training_accuracy(directory: str, training_accuracy: list, validation_accuracy: list):
| 64 | 64 | 188 | 21 | 43 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | plot_training_accuracy | plot_training_accuracy | 87 | 101 | 87 | 88 | 9ea319591367adb00dffea7ebffc103f96eed988 | bigcode/the-stack | train |
7b5a782f160881ea3a235723 | train | function | @trace()
def plot_f1_score(directory: str, valid_accumulator: Accumulator):
"""Plots the f1_score (together with precision and recall) for the validation partition.
Params:
- directory (str): The directory in which to save the plot
- valid_accumulator (Accumulator): The accumulator that contains ... | @trace()
def plot_f1_score(directory: str, valid_accumulator: Accumulator):
| """Plots the f1_score (together with precision and recall) for the validation partition.
Params:
- directory (str): The directory in which to save the plot
- valid_accumulator (Accumulator): The accumulator that contains the f1_score metrics
"""
figure, axes = setup_plot('F1 Score During ... | (x_range, validation_accuracy, label="Validation Accuracy (final=%.2f)" % validation_accuracy[-1])
axes.legend(loc='lower right')
figure.savefig(directory + constants.PLT_TRAIN_ACCURACY)
# End of plot_training_accuracy()
@trace()
def plot_f1_score(directory: str, valid_accumulator: Accumulator):
| 71 | 71 | 239 | 19 | 52 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | plot_f1_score | plot_f1_score | 105 | 122 | 105 | 106 | 29e7f2661708622cba759778a03577545c76a725 | bigcode/the-stack | train |
9258a432dc87d402eff69a79 | train | function | @trace()
def setup_plot(title: str, x_label: str, y_label: str) -> tuple:
"""Sets up the plot with the given parameters.
Params:
- title (str): The title of the plot
- x_label (str): The x-axis label
- y_label (str): The y-axis label
Returns:
- figure (matplotlib.figure.Figure): ... | @trace()
def setup_plot(title: str, x_label: str, y_label: str) -> tuple:
| """Sets up the plot with the given parameters.
Params:
- title (str): The title of the plot
- x_label (str): The x-axis label
- y_label (str): The y-axis label
Returns:
- figure (matplotlib.figure.Figure): The figure containing the plot
- axes (matplotlib.axes.Axes): The plot ... | , valid_accumulator)
plot_timestep_accuracy(directory, test_accumulator)
plot_confusion_matrix(directory, test_accumulator.latest_confusion_matrix, model.dataset.indexer)
# End of plot()
@trace()
def setup_plot(title: str, x_label: str, y_label: str) -> tuple:
| 64 | 64 | 148 | 23 | 41 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | setup_plot | setup_plot | 47 | 65 | 47 | 48 | 6196f5f581148694c50f1c67a9459fa7830dd683 | bigcode/the-stack | train |
fb339c3d0c354974a7c939e1 | train | function | @trace()
def plot_confusion_matrix(directory: str, confusion_matrix: ConfusionMatrix, indexer: Indexer = None):
"""Plots a confusion matrix a more accurate breakdown of the predictions made.
Params:
- directory (str): The directory in which to save the plot
- confusion_matrix (layers.utils.Confus... | @trace()
def plot_confusion_matrix(directory: str, confusion_matrix: ConfusionMatrix, indexer: Indexer = None):
| """Plots a confusion matrix a more accurate breakdown of the predictions made.
Params:
- directory (str): The directory in which to save the plot
- confusion_matrix (layers.utils.ConfusionMatrix): The confusion matrix
- indexer (indexer.Indexer): Converts the label indexes to tokens
"""
... | + 5
axes.text(x_pos, y_pos, "%.1f" % height, ha='center', va='bottom', rotation=90)
# Replace default labels with timestep_labels
if timestep_labels is not None:
axes.xaxis.set(ticklabels=timestep_labels)
figure.savefig(directory + constants.PLT_TIMESTEP_ACCURACY)
# End of plot_ti... | 110 | 110 | 368 | 27 | 83 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | plot_confusion_matrix | plot_confusion_matrix | 160 | 195 | 160 | 161 | 1c7e207518de7a4916cc5230e507fc39e54a28d8 | bigcode/the-stack | train |
80a2ef2351c00e4182012431 | train | function | @trace()
def plot_training_loss(directory: str, training_loss: list, validation_loss: list):
"""Plots the training and validation losses on a sublot.
Params:
- directory (str): The directory in which to save the plot
- training_loss (list): The list of training losses
- validation_loss (list... | @trace()
def plot_training_loss(directory: str, training_loss: list, validation_loss: list):
| """Plots the training and validation losses on a sublot.
Params:
- directory (str): The directory in which to save the plot
- training_loss (list): The list of training losses
- validation_loss (list): The list of validation losses
"""
figure, axes = setup_plot('Training Loss Over Ti... | ('all')
figure, axes = plt.subplots()
axes.set_title(title)
axes.set_xlabel(x_label)
axes.set_ylabel(y_label)
return figure, axes
# End of setup_plot()
@trace()
def plot_training_loss(directory: str, training_loss: list, validation_loss: list):
| 64 | 64 | 184 | 21 | 43 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | plot_training_loss | plot_training_loss | 69 | 83 | 69 | 70 | 05d5e42abe6684605ca954d725aec7fc82903e19 | bigcode/the-stack | train |
1f15d3975d6abd1d767cf7c2 | train | function | @debug('Plotting training results')
def plot(model: RNNBase, train_accumulator: Accumulator, valid_accumulator: Accumulator,
test_accumulator: Accumulator):
"""Plots a graphical representation of the model's training performance over time. Saves the plot to file in
<model_path>/run_<run_number>/gra... | @debug('Plotting training results')
def plot(model: RNNBase, train_accumulator: Accumulator, valid_accumulator: Accumulator,
test_accumulator: Accumulator):
| """Plots a graphical representation of the model's training performance over time. Saves the plot to file in
<model_path>/run_<run_number>/graph.png.
Params:
- model (model.RNNModel): The model containing the path where the figure will be saved
- train_accumulator (layers.utils.Accumulator): T... | import Accumulator # noqa
from .layers.utils import ConfusionMatrix # noqa
from .indexer import Indexer # noqa
plt.style.use('ggplot')
@debug('Plotting training results')
def plot(model: RNNBase, train_accumulator: Accumulator, valid_accumulator: Accumulator,
test_accumulator: Accumulator):
| 75 | 76 | 254 | 38 | 37 | ffrankies/tf-rnn | tf_rnn/plotter.py | Python | plot | plot | 25 | 43 | 25 | 27 | b175a30ba6d0a45898bb81036ac7daab9ba7f459 | bigcode/the-stack | train |
7be39b3db6672d6aa6a69e63 | train | function | def checkout(driver):
checkout_xpath = "(//button[@data-automation-id='pac-pos-proceed-to-checkout'])[1]"
smart_clicker(driver, checkout_xpath)
| def checkout(driver):
| checkout_xpath = "(//button[@data-automation-id='pac-pos-proceed-to-checkout'])[1]"
smart_clicker(driver, checkout_xpath)
| ated((By.XPATH, xpath)))
find_element.click()
break
except:
driver.refresh()
continue
def add_to_cart(driver):
add_to_cart_xpath = "(//*[@class='spin-button-children'])"
smart_clicker(driver,add_to_cart_xpath)
def checkout(driver):
| 63 | 64 | 36 | 4 | 59 | jameslivulpi/wallybot | checkout.py | Python | checkout | checkout | 48 | 50 | 48 | 48 | c8d471ab7ef160d6c6f228a90f6e262b202cf4c1 | bigcode/the-stack | train |
2e58a1bf98c059dc2b6053b1 | train | function | def smart_clicker(driver, xpath):
while True:
try:
find_element = WebDriverWait(driver, 2).until(EC.visibility_of_element_located((By.XPATH, xpath)))
find_element.click()
break
except:
driver.refresh()
continue
| def smart_clicker(driver, xpath):
| while True:
try:
find_element = WebDriverWait(driver, 2).until(EC.visibility_of_element_located((By.XPATH, xpath)))
find_element.click()
break
except:
driver.refresh()
continue
| ("permissions.default.stylesheet", 2)
#firefox_profile.set_preference("permissions.default.image", 2)
driver = webdriver.Firefox(firefox_profile=firefox_profile)
driver.get(TEST_URL)
driver.maximize_window()
return driver
def smart_clicker(driver, xpath):
| 64 | 64 | 59 | 8 | 55 | jameslivulpi/wallybot | checkout.py | Python | smart_clicker | smart_clicker | 34 | 42 | 34 | 34 | db57a475588f3fd4ac0fb1f4c34cd283f7dd06ac | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.