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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1e681a0b9ee4ff5b056decf5 | train | class | class FormFieldDefinition(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map... | class FormFieldDefinition(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | # coding: utf-8
"""
ocrapi
The powerful Optical Character Recognition (OCR) APIs let you convert scanned images of pages into recognized text. # noqa: E501
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
impo... | 87 | 256 | 5,117 | 6 | 80 | Cloudmersive/Cloudmersive.APIClient.Python.OCR | cloudmersive_ocr_api_client/models/form_field_definition.py | Python | FormFieldDefinition | FormFieldDefinition | 20 | 593 | 20 | 20 | 9ec31369cd3056a4248b4cc59833fd04e4f61afe | bigcode/the-stack | train |
cafed6c5daa83436dd828d2d | train | function | def bboxes_iou(bboxes_a, bboxes_b, xyxy=True):
if bboxes_a.shape[1] != 4 or bboxes_b.shape[1] != 4:
raise IndexError
if xyxy:
tl = torch.max(bboxes_a[:, None, :2], bboxes_b[:, :2])
br = torch.min(bboxes_a[:, None, 2:], bboxes_b[:, 2:])
area_a = torch.prod(bboxes_a[:, 2:] - bboxe... | def bboxes_iou(bboxes_a, bboxes_b, xyxy=True):
| if bboxes_a.shape[1] != 4 or bboxes_b.shape[1] != 4:
raise IndexError
if xyxy:
tl = torch.max(bboxes_a[:, None, :2], bboxes_b[:, :2])
br = torch.min(bboxes_a[:, None, 2:], bboxes_b[:, 2:])
area_a = torch.prod(bboxes_a[:, 2:] - bboxes_a[:, :2], 1)
area_b = torch.prod(bbox... | ms(
detections[:, :4],
detections[:, 4] * detections[:, 5],
detections[:, 6],
nms_thre,
)
detections = detections[nms_out_index]
if output[i] is None:
output[i] = detections
else:
output[i] = tor... | 103 | 103 | 345 | 17 | 85 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | bboxes_iou | bboxes_iou | 82 | 105 | 82 | 82 | a661056addc261df62a28751e58cea19b8fa2be1 | bigcode/the-stack | train |
926b8722ad575ca31c114245 | train | function | def matrix_iou(a, b):
"""
return iou of a and b, numpy version for data augenmentation
"""
lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
... | def matrix_iou(a, b):
| """
return iou of a and b, numpy version for data augenmentation
"""
lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
area_b = np.prod(b... | < br).type(tl.type()).prod(dim=2)
area_i = torch.prod(br - tl, 2) * en # * ((tl < br).all())
return area_i / (area_a[:, None] + area_b - area_i)
def matrix_iou(a, b):
| 64 | 64 | 161 | 8 | 56 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | matrix_iou | matrix_iou | 108 | 118 | 108 | 108 | 43e8b1730d614b2b0813f1a5df20057d798b4eea | bigcode/the-stack | train |
ad8fa0c2b70c301c99120e68 | train | function | def xyxy2xywh(bboxes):
bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
return bboxes
| def xyxy2xywh(bboxes):
| bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
return bboxes
| [:, 0::2] * scale_ratio + padw, 0, w_max)
bbox[:, 1::2] = np.clip(bbox[:, 1::2] * scale_ratio + padh, 0, h_max)
return bbox
def xyxy2xywh(bboxes):
| 64 | 64 | 56 | 9 | 54 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | xyxy2xywh | xyxy2xywh | 127 | 130 | 127 | 127 | 9c61ec89ea8a1ad817f5bcfae74717fa3fe4cb8e | bigcode/the-stack | train |
b7ca94b1c63900193544ea28 | train | function | def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45, class_agnostic=False):
box_corner = prediction.new(prediction.shape)
box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2
box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2
box_corner[:, :, 2] = predic... | def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45, class_agnostic=False):
| box_corner = prediction.new(prediction.shape)
box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2
box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2
box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2
box_corner[:, :, 3] = prediction[:, :, 1] + predic... | _anns",
"xyxy2xywh",
"xyxy2cxcywh",
]
def filter_box(output, scale_range):
"""
output: (N, 5+class) shape
"""
min_scale, max_scale = scale_range
w = output[:, 2] - output[:, 0]
h = output[:, 3] - output[:, 1]
keep = (w * h > min_scale * min_scale) & (w * h < max_scale * max_scale)
... | 148 | 148 | 496 | 32 | 116 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | postprocess | postprocess | 32 | 79 | 32 | 32 | 3197db3e46edfa4a0ee99a7d498bb545c9270554 | bigcode/the-stack | train |
a036ab28c06d81f90184550a | train | function | def filter_box(output, scale_range):
"""
output: (N, 5+class) shape
"""
min_scale, max_scale = scale_range
w = output[:, 2] - output[:, 0]
h = output[:, 3] - output[:, 1]
keep = (w * h > min_scale * min_scale) & (w * h < max_scale * max_scale)
return output[keep]
| def filter_box(output, scale_range):
| """
output: (N, 5+class) shape
"""
min_scale, max_scale = scale_range
w = output[:, 2] - output[:, 0]
h = output[:, 3] - output[:, 1]
keep = (w * h > min_scale * min_scale) & (w * h < max_scale * max_scale)
return output[keep]
| import torchvision
__all__ = [
"filter_box",
"postprocess",
"bboxes_iou",
"matrix_iou",
"adjust_box_anns",
"xyxy2xywh",
"xyxy2cxcywh",
]
def filter_box(output, scale_range):
| 64 | 64 | 95 | 8 | 56 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | filter_box | filter_box | 21 | 29 | 21 | 21 | 6a67c33cbe5bb5830bc2b06064948ed7caf0ffbd | bigcode/the-stack | train |
b9cd66c453bf0f90b5ddf162 | train | function | def xyxy2cxcywh(bboxes):
bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
bboxes[:, 0] = bboxes[:, 0] + bboxes[:, 2] * 0.5
bboxes[:, 1] = bboxes[:, 1] + bboxes[:, 3] * 0.5
return bboxes
| def xyxy2cxcywh(bboxes):
| bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
bboxes[:, 0] = bboxes[:, 0] + bboxes[:, 2] * 0.5
bboxes[:, 1] = bboxes[:, 1] + bboxes[:, 3] * 0.5
return bboxes
| xy2xywh(bboxes):
bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
return bboxes
def xyxy2cxcywh(bboxes):
| 64 | 64 | 111 | 10 | 53 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | xyxy2cxcywh | xyxy2cxcywh | 133 | 138 | 133 | 133 | 3c5a8e7410a3bc810a4a8feb329848358c3cb601 | bigcode/the-stack | train |
02e96df8853b28358454dc50 | train | function | def adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max):
bbox[:, 0::2] = np.clip(bbox[:, 0::2] * scale_ratio + padw, 0, w_max)
bbox[:, 1::2] = np.clip(bbox[:, 1::2] * scale_ratio + padh, 0, h_max)
return bbox
| def adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max):
| bbox[:, 0::2] = np.clip(bbox[:, 0::2] * scale_ratio + padw, 0, w_max)
bbox[:, 1::2] = np.clip(bbox[:, 1::2] * scale_ratio + padh, 0, h_max)
return bbox
| (b[:, 2:] - b[:, :2], axis=1)
return area_i / (area_a[:, np.newaxis] + area_b - area_i + 1e-12)
def adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max):
| 64 | 64 | 91 | 23 | 41 | XavierGeerinck/PublicProjects | AI/ONNX/yolox/src/yolox_files/boxes.py | Python | adjust_box_anns | adjust_box_anns | 121 | 124 | 121 | 121 | 71299c32777804828ae28ff899383a653b545a9d | bigcode/the-stack | train |
edb7eedb113f3c25db9f67ed | train | function | async def tug_collected(client: commands.Bot, ctx: commands.Context, users: list) -> list:
length = len(users)
if length == 1:
await ctx.send("You need at least 2 people to play tug of war")
return []
bye = None
players = users
if length % 2 == 1:
bye = users[-1]
pl... | async def tug_collected(client: commands.Bot, ctx: commands.Context, users: list) -> list:
| length = len(users)
if length == 1:
await ctx.send("You need at least 2 people to play tug of war")
return []
bye = None
players = users
if length % 2 == 1:
bye = users[-1]
players.pop(-1)
team_one = users[:int(length / 2)]
# team_two = users[int(length / 2... | [i].disabled = True
await org_msg.edit(embed=embed, components=ActionRow(buttons))
time_interval = time.time() - start
points = 1 if click.custom_id == "green" else -1
if click.custom_id == "green":
await click.respond(type=4, content=f"You got the point!, Time Taken : `{r... | 170 | 170 | 568 | 22 | 148 | Cooldude069/skwid-game-bot | src/cogs/games/tugofwar.py | Python | tug_collected | tug_collected | 86 | 137 | 86 | 86 | ba99473d20cad8ce8499521d1446add08e152b8a | bigcode/the-stack | train |
f709256d580f9f038001db4b | train | function | async def tug(client: commands.Bot, ctx: commands.Context, user: discord.User):
"""
Tug of War
"""
await user.create_dm()
buttons = [
Button(label="Click!", style=ButtonStyle.grey, custom_id="b1", disabled=True),
Button(label="Click!", style=ButtonStyle.grey, custom_id="b2", disabled... | async def tug(client: commands.Bot, ctx: commands.Context, user: discord.User):
| """
Tug of War
"""
await user.create_dm()
buttons = [
Button(label="Click!", style=ButtonStyle.grey, custom_id="b1", disabled=True),
Button(label="Click!", style=ButtonStyle.grey, custom_id="b2", disabled=True)
]
embed = discord.Embed(
title="Tug of War",
des... | import time
import discord
from discord.ext import commands
from discord_components import *
import asyncio
import random
async def tug(client: commands.Bot, ctx: commands.Context, user: discord.User):
| 41 | 186 | 622 | 18 | 22 | Cooldude069/skwid-game-bot | src/cogs/games/tugofwar.py | Python | tug | tug | 9 | 83 | 9 | 9 | b80ca3a7807108f9576ed20f0b4ce8fa7347b311 | bigcode/the-stack | train |
18553576c819e8da55d7fe14 | train | function | def template_dict(dictionnary, **kwargs):
""" Recurses into dictionnary and replace template {{keys}} with the matching values present in the kwargs dictionnary"""
ret = dict.copy(dictionnary)
for key in ret:
if isinstance(ret[key], dict):
ret[key] = template_dict(ret[key], **kwargs)
... | def template_dict(dictionnary, **kwargs):
| """ Recurses into dictionnary and replace template {{keys}} with the matching values present in the kwargs dictionnary"""
ret = dict.copy(dictionnary)
for key in ret:
if isinstance(ret[key], dict):
ret[key] = template_dict(ret[key], **kwargs)
if isinstance(ret[key], str):
... | from safe_logger import SafeLogger
from loop_detector import LoopDetector
from dku_utils import get_dku_key_values
from dku_constants import DKUConstants
logger = SafeLogger("api-connect plugin", forbiden_keys=["token", "password"])
def template_dict(dictionnary, **kwargs):
| 63 | 64 | 103 | 11 | 52 | dataiku/dss-plugin-api-connect | python-lib/rest_api_client.py | Python | template_dict | template_dict | 13 | 22 | 13 | 13 | 4f0a94b91dcdf0bd5d939785fd16b22f078bce53 | bigcode/the-stack | train |
a16aa4270d29cc8e630f8371 | train | class | class RestAPIClient(object):
def __init__(self, credential, endpoint, custom_key_values={}):
logger.info("Initialising RestAPIClient, credential={}, endpoint={}".format(logger.filter_secrets(credential), endpoint))
# presets_variables contains all variables available in templates using the {{vari... | class RestAPIClient(object):
| def __init__(self, credential, endpoint, custom_key_values={}):
logger.info("Initialising RestAPIClient, credential={}, endpoint={}".format(logger.filter_secrets(credential), endpoint))
# presets_variables contains all variables available in templates using the {{variable_name}} notation
s... | safe_logger import SafeLogger
from loop_detector import LoopDetector
from dku_utils import get_dku_key_values
from dku_constants import DKUConstants
logger = SafeLogger("api-connect plugin", forbiden_keys=["token", "password"])
def template_dict(dictionnary, **kwargs):
""" Recurses into dictionnary and replace... | 256 | 256 | 1,672 | 6 | 249 | dataiku/dss-plugin-api-connect | python-lib/rest_api_client.py | Python | RestAPIClient | RestAPIClient | 40 | 211 | 40 | 41 | 2da4509696a15c556eb1f289df9af874d138c43a | bigcode/the-stack | train |
935eb17e3b885f450848bff0 | train | class | class RestAPIClientError(ValueError):
pass
| class RestAPIClientError(ValueError):
| pass
| if template is None:
return None
formated = template
for key in kwargs:
replacement = kwargs.get(key, "")
formated = formated.replace("{{{{{}}}}}".format(key), str(replacement))
return formated
class RestAPIClientError(ValueError):
| 64 | 64 | 11 | 8 | 55 | dataiku/dss-plugin-api-connect | python-lib/rest_api_client.py | Python | RestAPIClientError | RestAPIClientError | 36 | 37 | 36 | 36 | e2dfd273c07114d8865978dea9df380bcde56e4b | bigcode/the-stack | train |
bdbfad9bd2527c560c50d5bd | train | function | def format_template(template, **kwargs):
""" Replace {{keys}} elements in template with the matching value in the kwargs dictionnary"""
if template is None:
return None
formated = template
for key in kwargs:
replacement = kwargs.get(key, "")
formated = formated.replace("{{{{{}}}}... | def format_template(template, **kwargs):
| """ Replace {{keys}} elements in template with the matching value in the kwargs dictionnary"""
if template is None:
return None
formated = template
for key in kwargs:
replacement = kwargs.get(key, "")
formated = formated.replace("{{{{{}}}}}".format(key), str(replacement))
ret... | for key in ret:
if isinstance(ret[key], dict):
ret[key] = template_dict(ret[key], **kwargs)
if isinstance(ret[key], str):
ret[key] = format_template(ret[key], **kwargs)
return ret
return ret
def format_template(template, **kwargs):
| 64 | 64 | 84 | 8 | 55 | dataiku/dss-plugin-api-connect | python-lib/rest_api_client.py | Python | format_template | format_template | 25 | 33 | 25 | 25 | 1c2fcee3af4e5ad8390cc542003ceb9bba9ae04b | bigcode/the-stack | train |
d61753fa3dce7524c136f769 | train | class | class BasicEnsembleModel(torch.nn.Module):
"""A wrapper around an ensemble of models."""
def __init__(self, models):
super().__init__()
self.models = torch.nn.ModuleList(models)
self.bos = self.models[0].decoder.dictionary.bos()
self.eos = self.models[0].decoder.dictionary.eos()... | class BasicEnsembleModel(torch.nn.Module):
| """A wrapper around an ensemble of models."""
def __init__(self, models):
super().__init__()
self.models = torch.nn.ModuleList(models)
self.bos = self.models[0].decoder.dictionary.bos()
self.eos = self.models[0].decoder.dictionary.eos()
self.pad = self.models[0].decoder.... | = models
def reorder_encoder_out(self, encoder_outs, new_order):
encoder_outs = [
model.encoder.reorder_encoder_out(encoder_out, new_order)
for model, encoder_out in zip(self.models, encoder_outs)
]
return encoder_outs
class BasicEnsembleModel(torch.nn.Module):
| 69 | 69 | 230 | 9 | 59 | zhengzx-nlp/REDER | fairseq/models/nat/nonautoregressive_ensembles.py | Python | BasicEnsembleModel | BasicEnsembleModel | 33 | 62 | 33 | 33 | 9956def6e52814e6fe89bd36c9467f112e856208 | bigcode/the-stack | train |
dcd5c6ffbeaf7e30623e3ec0 | train | class | class _EnsembleModelEncoder(object):
def __init__(self, models):
self.models = models
def reorder_encoder_out(self, encoder_outs, new_order):
encoder_outs = [
model.encoder.reorder_encoder_out(encoder_out, new_order)
for model, encoder_out in zip(self.models, encoder_out... | class _EnsembleModelEncoder(object):
| def __init__(self, models):
self.models = models
def reorder_encoder_out(self, encoder_outs, new_order):
encoder_outs = [
model.encoder.reorder_encoder_out(encoder_out, new_order)
for model, encoder_out in zip(self.models, encoder_outs)
]
return encoder_o... | tree.
import math
import torch
import torch.nn.functional as F
from fairseq.models.nat import (
_fill,
_skip,
_skip_encoder_out,
_apply_ins_masks,
_apply_ins_words,
_apply_del_words,
)
class _EnsembleModelEncoder(object):
| 64 | 64 | 80 | 8 | 56 | zhengzx-nlp/REDER | fairseq/models/nat/nonautoregressive_ensembles.py | Python | _EnsembleModelEncoder | _EnsembleModelEncoder | 21 | 30 | 21 | 21 | fe11ea3c6e6aecd9192bf1c9c53a0d98e8375e93 | bigcode/the-stack | train |
2a9a47836f9595766c0169d7 | train | class | class EnsembleLevT(BasicEnsembleModel):
"""A wrapper around an ensemble of models."""
def __init__(self, models):
super().__init__(models)
@torch.no_grad()
def forward_decoder(self, decoder_out, encoder_outs, eos_penalty=0.0, max_ratio=None, **kwargs):
# LevT ensembling
# A pip... | class EnsembleLevT(BasicEnsembleModel):
| """A wrapper around an ensemble of models."""
def __init__(self, models):
super().__init__(models)
@torch.no_grad()
def forward_decoder(self, decoder_out, encoder_outs, eos_penalty=0.0, max_ratio=None, **kwargs):
# LevT ensembling
# A pipeline of three steps: deletion, placehol... | zip(self.models, encoder_outs)
]
return encoder_outs
class BasicEnsembleModel(torch.nn.Module):
"""A wrapper around an ensemble of models."""
def __init__(self, models):
super().__init__()
self.models = torch.nn.ModuleList(models)
self.bos = self.models[0].decoder.dic... | 256 | 256 | 1,686 | 10 | 245 | zhengzx-nlp/REDER | fairseq/models/nat/nonautoregressive_ensembles.py | Python | EnsembleLevT | EnsembleLevT | 65 | 231 | 65 | 65 | 72fe75a6f2c59cd9f16888e2fc743bed79f41e34 | bigcode/the-stack | train |
2464d537dec8edc6a3bbf1de | train | class | class Solution:
def repeatedStringMatch(self, A, B):
t = int(math.ceil(len(B)/len(A)))
for i in range(0, 2):
extend = A*(t+i)
if B in extend:
return t +i
return -1
| class Solution:
| def repeatedStringMatch(self, A, B):
t = int(math.ceil(len(B)/len(A)))
for i in range(0, 2):
extend = A*(t+i)
if B in extend:
return t +i
return -1
| import math
class Solution:
| 6 | 64 | 62 | 3 | 2 | EdwaRen/Competitve_Programming | Leetcode/Interview/RepeatedStringMatch.py | Python | Solution | Solution | 4 | 11 | 4 | 4 | 36deb17d52ae8bd69e7d15c2c48fa9dd225e192f | bigcode/the-stack | train |
bcf375b77a1efc62927acc6e | train | function | def can_rotate(word):
for char in word:
if not char in letters:
return False
return True
| def can_rotate(word):
| for char in word:
if not char in letters:
return False
return True
| letters = ['I', 'O', 'S', 'H', 'Z', 'X', 'N']
def can_rotate(word):
| 28 | 64 | 26 | 5 | 23 | Joon7891/Competitive-Programming | CCC/CCC '13 J2 - Rotating letters.py | Python | can_rotate | can_rotate | 3 | 9 | 3 | 3 | b4f8f733794f1953935461e56a428ea9d0ef9988 | bigcode/the-stack | train |
0bace72f7cb8248cf6cd9139 | train | class | class NoNameBoundField(forms.forms.BoundField):
"A Field plus data, with no name"
def __init__(self, form, field, name):
super(NoNameBoundField, self).__init__(form, field, name)
self.name = ''
self.html_name = ''
self.html_initial_name = ''
| class NoNameBoundField(forms.forms.BoundField):
| "A Field plus data, with no name"
def __init__(self, form, field, name):
super(NoNameBoundField, self).__init__(form, field, name)
self.name = ''
self.html_name = ''
self.html_initial_name = ''
| ship_street2',
'shipping__locality': 'ship_city',
'shipping__region': 'ship_state',
'shipping__postal_code': 'ship_postal_code',
'shipping__country_code_alpha2': 'ship_country'
}
class NoNameBoundField(forms.forms.BoundField):
| 64 | 64 | 70 | 11 | 53 | hiidef/hiicart | hiicart/gateway/stripe/forms.py | Python | NoNameBoundField | NoNameBoundField | 29 | 35 | 29 | 29 | a068c31068b0706c5c229946f8e8806e3d277338 | bigcode/the-stack | train |
affc31e67459cec08531ded1 | train | class | class PaymentForm(forms.Form):
"""
Stripe payment form.
"""
# Credit card details are rendered without the html name= attribute.
# This keeps them from hitting the server when the form is submitted.
credit_card__number = forms.CharField(required=False, max_length=16)
credit_card__cvv = form... | class PaymentForm(forms.Form):
| """
Stripe payment form.
"""
# Credit card details are rendered without the html name= attribute.
# This keeps them from hitting the server when the form is submitted.
credit_card__number = forms.CharField(required=False, max_length=16)
credit_card__cvv = forms.CharField(required=False, min... | postal_code': 'bill_postal_code',
'billing__country_code_alpha2': 'bill_country',
'customer__phone': 'bill_phone',
'shipping__first_name': 'ship_first_name',
'shipping__last_name': 'ship_last_name',
'shipping__street_address': 'ship_street1',
'shipping__extended_address': 'ship_street2',
'sh... | 206 | 207 | 693 | 6 | 200 | hiidef/hiicart | hiicart/gateway/stripe/forms.py | Python | PaymentForm | PaymentForm | 38 | 114 | 38 | 38 | b7ac927752804d2f2a8845313b37145cc18e189f | bigcode/the-stack | train |
57273d7eeabace039aeced90 | train | class | class RunModuleCodeTest(unittest.TestCase):
"""Unit tests for runpy._run_code and runpy._run_module_code"""
expected_result = ["Top level assignment", "Lower level reference"]
test_source = (
"# Check basic code execution\n"
"result = ['Top level assignment']\n"
"def f():\n"
... | class RunModuleCodeTest(unittest.TestCase):
| """Unit tests for runpy._run_code and runpy._run_module_code"""
expected_result = ["Top level assignment", "Lower level reference"]
test_source = (
"# Check basic code execution\n"
"result = ['Top level assignment']\n"
"def f():\n"
" result.append('Lower level reference')... | # Test the runpy module
import unittest
import os
import os.path
import sys
import re
import tempfile
import importlib
import py_compile
from test.support import (
forget, make_legacy_pyc, run_unittest, unload, verbose, no_tracing,
create_empty_file)
from test.script_helper import (
make_pkg, make_script, m... | 186 | 189 | 631 | 9 | 176 | certik/python-3.3 | Lib/test/test_runpy.py | Python | RunModuleCodeTest | RunModuleCodeTest | 25 | 86 | 25 | 25 | 3256eeec9b63345fcc61229248f0d789dd4f9bab | bigcode/the-stack | train |
124e67c155066f55eb50e3d8 | train | class | class RunPathTest(unittest.TestCase):
"""Unit tests for runpy.run_path"""
# Based on corresponding tests in test_cmd_line_script
test_source = """\
# Script may be run with optimisation enabled, so don't rely on assert
# statements being executed
def assertEqual(lhs, rhs):
if lhs != rhs:
raise ... | class RunPathTest(unittest.TestCase):
| """Unit tests for runpy.run_path"""
# Based on corresponding tests in test_cmd_line_script
test_source = """\
# Script may be run with optimisation enabled, so don't rely on assert
# statements being executed
def assertEqual(lhs, rhs):
if lhs != rhs:
raise AssertionError('%r != %r' % (lhs, rhs)... | .assertIn("__package__", d2)
self.assertTrue(d2["__package__"] == pkg_name)
self.assertIn("sibling", d2)
self.assertIn("nephew", d2)
del d2 # Ensure __loader__ entry doesn't keep file open
finally:
self._del_pkg(pkg_dir, depth, mod_name)
if ver... | 256 | 256 | 1,219 | 8 | 248 | certik/python-3.3 | Lib/test/test_runpy.py | Python | RunPathTest | RunPathTest | 296 | 424 | 296 | 296 | 8501690a5cbfb2132c406ca8405a2d2f1cecdfcd | bigcode/the-stack | train |
a7bb0fee98ceef261f25fd1f | train | function | def test_main():
run_unittest(
RunModuleCodeTest,
RunModuleTest,
RunPathTest
)
| def test_main():
| run_unittest(
RunModuleCodeTest,
RunModuleTest,
RunPathTest
)
| (filename, 'w', encoding='latin1') as f:
f.write("""
#coding:latin1
"non-ASCII: h\xe9"
""")
result = run_path(filename)
self.assertEqual(result['__doc__'], "non-ASCII: h\xe9")
def test_main():
| 64 | 64 | 27 | 4 | 60 | certik/python-3.3 | Lib/test/test_runpy.py | Python | test_main | test_main | 427 | 432 | 427 | 427 | f773a862de1a51e3777841eb560724840170c838 | bigcode/the-stack | train |
9ff3558b6e974d6463d34b98 | train | class | class RunModuleTest(unittest.TestCase):
"""Unit tests for runpy.run_module"""
def expect_import_error(self, mod_name):
try:
run_module(mod_name)
except ImportError:
pass
else:
self.fail("Expected import error for " + mod_name)
def test_invalid_na... | class RunModuleTest(unittest.TestCase):
| """Unit tests for runpy.run_module"""
def expect_import_error(self, mod_name):
try:
run_module(mod_name)
except ImportError:
pass
else:
self.fail("Expected import error for " + mod_name)
def test_invalid_names(self):
# Builtin module
... | "
loader = "Now you're just being silly"
package = '' # Treat as a top level module
d1 = dict(initial=initial)
saved_argv0 = sys.argv[0]
d2 = _run_module_code(self.test_source,
d1,
name,
fil... | 256 | 256 | 1,932 | 8 | 248 | certik/python-3.3 | Lib/test/test_runpy.py | Python | RunModuleTest | RunModuleTest | 89 | 293 | 89 | 89 | acefa332dfb5d97392fbf14578e80a6eef76c770 | bigcode/the-stack | train |
a5599f1d00f869b34902a987 | train | class | class MitoDataset(BaseDataset):
"""Pytorch dataset class for mitochondira segmentation.
Args:
volume: input image stacks.
label: synapse masks.
sample_input_size (tuple, int): model input size.
sample_label_size (tuple, int): model output size.
sample_stride (tuple, int)... | class MitoDataset(BaseDataset):
| """Pytorch dataset class for mitochondira segmentation.
Args:
volume: input image stacks.
label: synapse masks.
sample_input_size (tuple, int): model input size.
sample_label_size (tuple, int): model output size.
sample_stride (tuple, int): stride size for sampling.
... | from __future__ import print_function, division
import numpy as np
import random
import torch
import torch.utils.data
from .dataset import BaseDataset
from .misc import crop_volume, rebalance_binary_class
from torch_connectomics.data.utils.functional_transform import skeleton_transform_volume
class MitoDataset(Ba... | 65 | 245 | 819 | 7 | 57 | al093/pytorch_connectomics | torch_connectomics/data/dataset/dataset_mito.py | Python | MitoDataset | MitoDataset | 13 | 110 | 13 | 13 | cdb8637258a45c362b2b30d0c4d0cb5712f27356 | bigcode/the-stack | train |
4b4ad09f71b57957db5388ab | train | class | class MitoSkeletonDataset(BaseDataset):
"""Pytorch dataset class for mitochondira segmentation.
Args:
volume: input image stacks.
label: synapse masks.
sample_input_size (tuple, int): model input size.
sample_label_size (tuple, int): model output size.
sample_stride (tup... | class MitoSkeletonDataset(BaseDataset):
| """Pytorch dataset class for mitochondira segmentation.
Args:
volume: input image stacks.
label: synapse masks.
sample_input_size (tuple, int): model input size.
sample_label_size (tuple, int): model output size.
sample_stride (tuple, int): stride size for sampling.
... | label']
out_input = out_input.astype(np.float32)
out_label = out_label.astype(np.float32)
# Test Mode Specific Operations:
elif self.mode == 'test':
# test mode
pos = self.get_pos_test(index)
out_input = crop_volume(self.input[pos[0]],... | 256 | 256 | 900 | 8 | 247 | al093/pytorch_connectomics | torch_connectomics/data/dataset/dataset_mito.py | Python | MitoSkeletonDataset | MitoSkeletonDataset | 112 | 214 | 112 | 112 | babe0072b996036a02be3aae49f18d4c9ee50be6 | bigcode/the-stack | train |
7a9d187add700fef0d855f13 | train | function | def _check_error(return_code):
if return_code == ErrorCode.Success:
return
if return_code == ErrorCode.NullPointerProvided:
raise TypeError("Provided null pointer(s)")
if return_code == ErrorCode.InvalidArgument:
raise TypeError("An invalid argument was provided")
if return_code ... | def _check_error(return_code):
| if return_code == ErrorCode.Success:
return
if return_code == ErrorCode.NullPointerProvided:
raise TypeError("Provided null pointer(s)")
if return_code == ErrorCode.InvalidArgument:
raise TypeError("An invalid argument was provided")
if return_code == ErrorCode.DatabaseError:
... | # Input errors
NullPointerProvided = ffi.CommonErrorCode.NullPointerProvided
InvalidArgument = 2
# # output errors
DatabaseError = 0x10
NotFound = 0x11
StopIteration = 0x20
def _check_error(return_code):
| 64 | 64 | 132 | 7 | 56 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | _check_error | _check_error | 41 | 55 | 41 | 41 | 1ca9ff932f91f3592376d4f620879db2256ac811 | bigcode/the-stack | train |
3acf5f365bc85b1f4043c6d5 | train | function | def _pylibexec(name, *args):
_check_error(ffi.PY_LIBRARY.call(name, *args))
| def _pylibexec(name, *args):
| _check_error(ffi.PY_LIBRARY.call(name, *args))
| if return_code == ErrorCode.StopIteration:
raise StopIteration()
raise RuntimeError("An unknown error occurred: {}".format(return_code))
def _libexec(name, *args):
_check_error(ffi.LIBRARY.call(name, *args))
def _pylibexec(name, *args):
| 64 | 64 | 26 | 11 | 53 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | _pylibexec | _pylibexec | 62 | 63 | 62 | 62 | 3e409788f9655bacb1b154a70c34d095841e6cf0 | bigcode/the-stack | train |
94bbcfdbd5969391a302db7b | train | class | class BlockStore(ffi.OwnedPointer):
"""
A dict like interface wrapper around the block store to guarantee,
objects are correctly wrapped and unwrapped as they are stored and
retrieved.
"""
def __init__(self, database):
super().__init__('commit_store_drop')
_libexec(
... | class BlockStore(ffi.OwnedPointer):
| """
A dict like interface wrapper around the block store to guarantee,
objects are correctly wrapped and unwrapped as they are stored and
retrieved.
"""
def __init__(self, database):
super().__init__('commit_store_drop')
_libexec(
'commit_store_new',
data... | x20
def _check_error(return_code):
if return_code == ErrorCode.Success:
return
if return_code == ErrorCode.NullPointerProvided:
raise TypeError("Provided null pointer(s)")
if return_code == ErrorCode.InvalidArgument:
raise TypeError("An invalid argument was provided")
if return... | 256 | 256 | 2,335 | 10 | 246 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | BlockStore | BlockStore | 78 | 433 | 78 | 78 | c6c22b7712b902ac87b67a1b2ddf88fe5d909c41 | bigcode/the-stack | train |
800117c30646aad776881f0d | train | class | class _PutEntry(ctypes.Structure):
_fields_ = [('block_bytes', ctypes.c_char_p),
('block_bytes_len', ctypes.c_size_t)]
@staticmethod
def new(block_bytes):
return _PutEntry(
block_bytes,
len(block_bytes)
)
| class _PutEntry(ctypes.Structure):
| _fields_ = [('block_bytes', ctypes.c_char_p),
('block_bytes_len', ctypes.c_size_t)]
@staticmethod
def new(block_bytes):
return _PutEntry(
block_bytes,
len(block_bytes)
)
| {}".format(return_code))
def _libexec(name, *args):
_check_error(ffi.LIBRARY.call(name, *args))
def _pylibexec(name, *args):
_check_error(ffi.PY_LIBRARY.call(name, *args))
class _PutEntry(ctypes.Structure):
| 64 | 64 | 61 | 9 | 55 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | _PutEntry | _PutEntry | 66 | 75 | 66 | 66 | 85ba62d1ab02aeaf370532fe5953093390b0b692 | bigcode/the-stack | train |
676deb9b0047893eea72f21c | train | function | def _libexec(name, *args):
_check_error(ffi.LIBRARY.call(name, *args))
| def _libexec(name, *args):
| _check_error(ffi.LIBRARY.call(name, *args))
| database error occurred")
if return_code == ErrorCode.NotFound:
raise ValueError("Unable to find requested item")
if return_code == ErrorCode.StopIteration:
raise StopIteration()
raise RuntimeError("An unknown error occurred: {}".format(return_code))
def _libexec(name, *args):
| 64 | 64 | 24 | 9 | 55 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | _libexec | _libexec | 58 | 59 | 58 | 58 | 83e7480a9c848b4302573652245d563583eebfed | bigcode/the-stack | train |
701cef02dcd4183dc4436ce4 | train | class | class _BlockStoreIter(ffi.BlockIterator):
"""
A dict like interface wrapper around the block store to guarantee,
objects are correctly wrapped and unwrapped as they are stored and
retrieved.
"""
name = "commit_store_block_by_height_iter"
def __init__(self, commit_store_ptr, start=None, dec... | class _BlockStoreIter(ffi.BlockIterator):
| """
A dict like interface wrapper around the block store to guarantee,
objects are correctly wrapped and unwrapped as they are stored and
retrieved.
"""
name = "commit_store_block_by_height_iter"
def __init__(self, commit_store_ptr, start=None, decreasing=True):
super().__init__(_c... | get_count('commit_store_get_batch_count')
def get_block_count(self):
"""Returns the count of blocks in the block store.
Returns:
Integer: The count of blocks
"""
return self._get_count('commit_store_get_block_count')
class _BlockStoreIter(ffi.BlockIterator):
| 64 | 64 | 177 | 10 | 54 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | _BlockStoreIter | _BlockStoreIter | 436 | 463 | 436 | 436 | 1741407a33603a39f2b4ccbd7d95c92b3941cd5a | bigcode/the-stack | train |
9c975b0c7b2f5ee7215857f7 | train | class | class ErrorCode(IntEnum):
Success = ffi.CommonErrorCode.Success
# Input errors
NullPointerProvided = ffi.CommonErrorCode.NullPointerProvided
InvalidArgument = 2
# # output errors
DatabaseError = 0x10
NotFound = 0x11
StopIteration = 0x20
| class ErrorCode(IntEnum):
| Success = ffi.CommonErrorCode.Success
# Input errors
NullPointerProvided = ffi.CommonErrorCode.NullPointerProvided
InvalidArgument = 2
# # output errors
DatabaseError = 0x10
NotFound = 0x11
StopIteration = 0x20
| from sawtooth_validator.protobuf.block_pb2 import Block
from sawtooth_validator.protobuf.batch_pb2 import Batch
from sawtooth_validator.protobuf.transaction_pb2 import Transaction
from sawtooth_validator.state.merkle import INIT_ROOT_KEY
from sawtooth_validator import ffi
class ErrorCode(IntEnum):
| 64 | 64 | 73 | 6 | 57 | EddyKIL/sawtooth-core | validator/sawtooth_validator/journal/block_store.py | Python | ErrorCode | ErrorCode | 27 | 38 | 27 | 27 | e8d84a4de47bf0c0ec401dfe09be72dc6c006771 | bigcode/the-stack | train |
fb04da9502f3d0ee59ca08c6 | train | function | def extract_pandas_matrix(data):
"""Extracts numpy matrix from pandas DataFrame.
Args:
data: `pandas.DataFrame` containing the data to be extracted.
Returns:
A numpy `ndarray` of the DataFrame's values.
"""
if not isinstance(data, pd.DataFrame):
return data
return data.as_matrix()
| def extract_pandas_matrix(data):
| """Extracts numpy matrix from pandas DataFrame.
Args:
data: `pandas.DataFrame` containing the data to be extracted.
Returns:
A numpy `ndarray` of the DataFrame's values.
"""
if not isinstance(data, pd.DataFrame):
return data
return data.as_matrix()
| , pd.DataFrame):
return data
if all(dtype.name in PANDAS_DTYPES for dtype in data.dtypes):
return data.values.astype('float')
else:
raise ValueError('Data types for data must be int, float, or bool.')
def extract_pandas_matrix(data):
| 63 | 64 | 76 | 7 | 56 | rcelebi/android-elfali | jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py | Python | extract_pandas_matrix | extract_pandas_matrix | 69 | 81 | 69 | 69 | 84658308ca1c9a814a1c48bb41b7c739d4cf6acb | bigcode/the-stack | train |
4169f375b6b25ed118b2ae9e | train | function | def extract_pandas_data(data):
"""Extract data from pandas.DataFrame for predictors.
Given a DataFrame, will extract the values and cast them to float. The
DataFrame is expected to contain values of type int, float or bool.
Args:
data: `pandas.DataFrame` containing the data to be extracted.
Returns:
... | def extract_pandas_data(data):
| """Extract data from pandas.DataFrame for predictors.
Given a DataFrame, will extract the values and cast them to float. The
DataFrame is expected to contain values of type int, float or bool.
Args:
data: `pandas.DataFrame` containing the data to be extracted.
Returns:
A numpy `ndarray` of the Data... | ',
'uint16': 'int',
'uint32': 'int',
'uint64': 'int',
'float16': 'float',
'float32': 'float',
'float64': 'float',
'bool': 'i'
}
def extract_pandas_data(data):
| 64 | 64 | 172 | 7 | 57 | rcelebi/android-elfali | jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py | Python | extract_pandas_data | extract_pandas_data | 45 | 66 | 45 | 45 | 5b1fdd52ce7ccb1e6b240df9082019fd4e0c8056 | bigcode/the-stack | train |
01119aedf4af36cbf9831ffc | train | function | def extract_pandas_labels(labels):
"""Extract data from pandas.DataFrame for labels.
Args:
labels: `pandas.DataFrame` or `pandas.Series` containing one column of
labels to be extracted.
Returns:
A numpy `ndarray` of labels from the DataFrame.
Raises:
ValueError: if more than one column is f... | def extract_pandas_labels(labels):
| """Extract data from pandas.DataFrame for labels.
Args:
labels: `pandas.DataFrame` or `pandas.Series` containing one column of
labels to be extracted.
Returns:
A numpy `ndarray` of labels from the DataFrame.
Raises:
ValueError: if more than one column is found or type is not int, float or
... | Args:
data: `pandas.DataFrame` containing the data to be extracted.
Returns:
A numpy `ndarray` of the DataFrame's values.
"""
if not isinstance(data, pd.DataFrame):
return data
return data.as_matrix()
def extract_pandas_labels(labels):
| 64 | 64 | 186 | 7 | 57 | rcelebi/android-elfali | jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py | Python | extract_pandas_labels | extract_pandas_labels | 84 | 108 | 84 | 84 | e3867da4cda9c189d7d557b6a7d51dc07752c3eb | bigcode/the-stack | train |
9046a74f40b97e5aeafb990d | train | function | def voc_ap(rec, prec):
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre... | def voc_ap(rec, prec):
# correct AP calculation
# first append sentinel values at the end
| mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes v... | _curve[i, 1] / pr_curve[i, 0]
_pr_curve[i, 1] = pr_curve[i, 1] / count_face
return _pr_curve
def voc_ap(rec, prec):
# correct AP calculation
# first append sentinel values at the end
| 64 | 64 | 186 | 23 | 40 | senfu/YOLOX | widerface/evaluation.py | Python | voc_ap | voc_ap | 196 | 213 | 196 | 199 | 9867a1a59d1ae06c5727a7605fe9c65d8b9866d3 | bigcode/the-stack | train |
6438d07da68f996de87463c8 | train | function | def get_preds(pred_dir):
events = os.listdir(pred_dir)
boxes = dict()
pbar = tqdm.tqdm(events)
for event in pbar:
pbar.set_description('Reading Predictions ')
event_dir = os.path.join(pred_dir, event)
event_images = os.listdir(event_dir)
current_event = dict()
fo... | def get_preds(pred_dir):
| events = os.listdir(pred_dir)
boxes = dict()
pbar = tqdm.tqdm(events)
for event in pbar:
pbar.set_description('Reading Predictions ')
event_dir = os.path.join(pred_dir, event)
event_images = os.listdir(event_dir)
current_event = dict()
for imgtxt in event_images:... | 0].rstrip('\n\r')
lines = lines[2:]
boxes = np.array(list(map(lambda x: [float(a) for a in x.rstrip('\r\n').split(' ')], lines))).astype('float')
return img_file.split('/')[-1], boxes
def get_preds(pred_dir):
| 64 | 64 | 127 | 6 | 57 | senfu/YOLOX | widerface/evaluation.py | Python | get_preds | get_preds | 93 | 107 | 93 | 93 | ef1f7945cf723a8f9cb0f32ea3d57e759ae5fab7 | bigcode/the-stack | train |
4e806108c220e9177a01e6cb | train | function | def norm_score(pred):
""" norm score
pred {key: [[x1,y1,x2,y2,s]]}
"""
max_score = 0
min_score = 1
for _, k in pred.items():
for _, v in k.items():
if len(v) == 0:
continue
_min = np.min(v[:, -1])
_max = np.max(v[:, -1])
m... | def norm_score(pred):
| """ norm score
pred {key: [[x1,y1,x2,y2,s]]}
"""
max_score = 0
min_score = 1
for _, k in pred.items():
for _, v in k.items():
if len(v) == 0:
continue
_min = np.min(v[:, -1])
_max = np.max(v[:, -1])
max_score = max(_max, m... | _event = dict()
for imgtxt in event_images:
imgname, _boxes = read_pred_file(os.path.join(event_dir, imgtxt))
current_event[imgname.rstrip('.jpg')] = _boxes
boxes[event] = current_event
return boxes
def norm_score(pred):
| 64 | 64 | 171 | 5 | 58 | senfu/YOLOX | widerface/evaluation.py | Python | norm_score | norm_score | 110 | 132 | 110 | 110 | e893d71c36f693cd966ef7927ba916e6f1ba28bb | bigcode/the-stack | train |
c927912e0f54f1e3d75b0b51 | train | function | def read_pred_file(filepath):
with open(filepath, 'r') as f:
lines = f.readlines()
img_file = lines[0].rstrip('\n\r')
lines = lines[2:]
boxes = np.array(list(map(lambda x: [float(a) for a in x.rstrip('\r\n').split(' ')], lines))).astype('float')
return img_file.split('/')[-1], boxe... | def read_pred_file(filepath):
| with open(filepath, 'r') as f:
lines = f.readlines()
img_file = lines[0].rstrip('\n\r')
lines = lines[2:]
boxes = np.array(list(map(lambda x: [float(a) for a in x.rstrip('\r\n').split(' ')], lines))).astype('float')
return img_file.split('/')[-1], boxes
| if state == 2:
box = [float(x) for x in line.split(' ')[:4]]
current_boxes.append(box)
continue
f = open(cache_file, 'wb')
pickle.dump(boxes, f)
f.close()
return boxes
def read_pred_file(filepath):
| 64 | 64 | 87 | 6 | 57 | senfu/YOLOX | widerface/evaluation.py | Python | read_pred_file | read_pred_file | 82 | 90 | 82 | 83 | 30eb0dc6ba1e7b2279336c78ba5c02be75e2dce8 | bigcode/the-stack | train |
2b753c0968d5f6906d972cab | train | function | def dataset_pr_info(thresh_num, pr_curve, count_face):
_pr_curve = np.zeros((thresh_num, 2))
for i in range(thresh_num):
_pr_curve[i, 0] = pr_curve[i, 1] / pr_curve[i, 0]
_pr_curve[i, 1] = pr_curve[i, 1] / count_face
return _pr_curve
| def dataset_pr_info(thresh_num, pr_curve, count_face):
| _pr_curve = np.zeros((thresh_num, 2))
for i in range(thresh_num):
_pr_curve[i, 0] = pr_curve[i, 1] / pr_curve[i, 0]
_pr_curve[i, 1] = pr_curve[i, 1] / count_face
return _pr_curve
| np.where(proposal_list[:r_index+1] == 1)[0]
pr_info[t, 0] = len(p_index)
pr_info[t, 1] = pred_recall[r_index]
return pr_info
def dataset_pr_info(thresh_num, pr_curve, count_face):
| 64 | 64 | 90 | 14 | 49 | senfu/YOLOX | widerface/evaluation.py | Python | dataset_pr_info | dataset_pr_info | 188 | 193 | 188 | 188 | fe5adb086c39f5d15c8bc1456a9cfcab2daaa7c2 | bigcode/the-stack | train |
9ade7025821b1207aa2b3a5b | train | function | def evaluation(pred, gt_path, iou_thresh=0.5):
pred = get_preds(pred)
norm_score(pred)
facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list = get_gt_boxes(gt_path)
event_num = len(event_list)
thresh_num = 1000
settings = ['easy', 'medium', 'hard']
setting_gts = [ea... | def evaluation(pred, gt_path, iou_thresh=0.5):
| pred = get_preds(pred)
norm_score(pred)
facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list = get_gt_boxes(gt_path)
event_num = len(event_list)
thresh_num = 1000
settings = ['easy', 'medium', 'hard']
setting_gts = [easy_gt_list, medium_gt_list, hard_gt_list]
a... | = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
... | 175 | 175 | 586 | 15 | 159 | senfu/YOLOX | widerface/evaluation.py | Python | evaluation | evaluation | 216 | 271 | 216 | 216 | 46523a1f08abf32ef07cef8b02432d98fddeb7c5 | bigcode/the-stack | train |
7c09e772b24aaff03b5e00d4 | train | function | def img_pr_info(thresh_num, pred_info, proposal_list, pred_recall):
pr_info = np.zeros((thresh_num, 2)).astype('float')
for t in range(thresh_num):
thresh = 1 - (t+1)/thresh_num
r_index = np.where(pred_info[:, 4] >= thresh)[0]
if len(r_index) == 0:
pr_info[t, 0] = 0
... | def img_pr_info(thresh_num, pred_info, proposal_list, pred_recall):
| pr_info = np.zeros((thresh_num, 2)).astype('float')
for t in range(thresh_num):
thresh = 1 - (t+1)/thresh_num
r_index = np.where(pred_info[:, 4] >= thresh)[0]
if len(r_index) == 0:
pr_info[t, 0] = 0
pr_info[t, 1] = 0
else:
r_index = r_index[-1... | recall_list[max_idx] = 1
r_keep_index = np.where(recall_list == 1)[0]
pred_recall[h] = len(r_keep_index)
return pred_recall, proposal_list
def img_pr_info(thresh_num, pred_info, proposal_list, pred_recall):
| 64 | 64 | 177 | 18 | 45 | senfu/YOLOX | widerface/evaluation.py | Python | img_pr_info | img_pr_info | 171 | 185 | 171 | 171 | d592745836a3f5bdfb2fabac4c791d02030b9586 | bigcode/the-stack | train |
2914aa14aa3c7663352ded44 | train | function | def image_eval(pred, gt, ignore, iou_thresh):
""" single image evaluation
pred: Nx5
gt: Nx4
ignore:
"""
_pred = pred.copy()
_gt = gt.copy()
pred_recall = np.zeros(_pred.shape[0])
recall_list = np.zeros(_gt.shape[0])
proposal_list = np.ones(_pred.shape[0])
_pred[:, 2] = _pre... | def image_eval(pred, gt, ignore, iou_thresh):
| """ single image evaluation
pred: Nx5
gt: Nx4
ignore:
"""
_pred = pred.copy()
_gt = gt.copy()
pred_recall = np.zeros(_pred.shape[0])
recall_list = np.zeros(_gt.shape[0])
proposal_list = np.ones(_pred.shape[0])
_pred[:, 2] = _pred[:, 2] + _pred[:, 0]
_pred[:, 3] = _pred[... | -1])
max_score = max(_max, max_score)
min_score = min(_min, min_score)
diff = max_score - min_score
for _, k in pred.items():
for _, v in k.items():
if len(v) == 0:
continue
v[:, -1] = (v[:, -1] - min_score)/diff
def image_eval(pred, gt, ... | 94 | 94 | 316 | 13 | 80 | senfu/YOLOX | widerface/evaluation.py | Python | image_eval | image_eval | 135 | 168 | 135 | 135 | 3f1fb08f3069e633d326d9d5a55a2c6980c41153 | bigcode/the-stack | train |
370245d3edf87655c6c08060 | train | function | def get_gt_boxes_from_txt(gt_path, cache_dir):
cache_file = os.path.join(cache_dir, 'gt_cache.pkl')
if os.path.exists(cache_file):
f = open(cache_file, 'rb')
boxes = pickle.load(f)
f.close()
return boxes
f = open(gt_path, 'r')
state = 0
lines = f.readlines()
lin... | def get_gt_boxes_from_txt(gt_path, cache_dir):
| cache_file = os.path.join(cache_dir, 'gt_cache.pkl')
if os.path.exists(cache_file):
f = open(cache_file, 'rb')
boxes = pickle.load(f)
f.close()
return boxes
f = open(gt_path, 'r')
state = 0
lines = f.readlines()
lines = list(map(lambda x: x.rstrip('\r\n'), lines)... | ['event_list']
file_list = gt_mat['file_list']
hard_gt_list = hard_mat['gt_list']
medium_gt_list = medium_mat['gt_list']
easy_gt_list = easy_mat['gt_list']
return facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list
def get_gt_boxes_from_txt(gt_path, cache_dir):
| 83 | 83 | 278 | 12 | 70 | senfu/YOLOX | widerface/evaluation.py | Python | get_gt_boxes_from_txt | get_gt_boxes_from_txt | 37 | 79 | 37 | 38 | 3ef1c4c04d22a695aa7f82eea58518b673aebb2b | bigcode/the-stack | train |
2c31358bd1f7170f42928bcd | train | function | def get_gt_boxes(gt_dir):
""" gt dir: (wider_face_val.mat, wider_easy_val.mat, wider_medium_val.mat, wider_hard_val.mat)"""
gt_mat = loadmat(os.path.join(gt_dir, 'wider_face_val.mat'))
hard_mat = loadmat(os.path.join(gt_dir, 'wider_hard_val.mat'))
medium_mat = loadmat(os.path.join(gt_dir, 'wider_medium... | def get_gt_boxes(gt_dir):
| """ gt dir: (wider_face_val.mat, wider_easy_val.mat, wider_medium_val.mat, wider_hard_val.mat)"""
gt_mat = loadmat(os.path.join(gt_dir, 'wider_face_val.mat'))
hard_mat = loadmat(os.path.join(gt_dir, 'wider_hard_val.mat'))
medium_mat = loadmat(os.path.join(gt_dir, 'wider_medium_val.mat'))
easy_mat =... | wondervictor
mail: tianhengcheng@gmail.com
copyright@wondervictor
"""
import os
import tqdm
import pickle
import argparse
import numpy as np
from scipy.io import loadmat
from bbox import bbox_overlaps
from IPython import embed
def get_gt_boxes(gt_dir):
| 64 | 64 | 203 | 7 | 56 | senfu/YOLOX | widerface/evaluation.py | Python | get_gt_boxes | get_gt_boxes | 18 | 34 | 18 | 18 | 9e3db20b769b138a72be4fe94b4e9ef97cfb2be5 | bigcode/the-stack | train |
2e9e6ef460293843358742a6 | train | class | class AccountsConfig(AppConfig):
name = 'Accounts'
| class AccountsConfig(AppConfig):
| name = 'Accounts'
| from django.apps import AppConfig
class AccountsConfig(AppConfig):
| 13 | 64 | 12 | 6 | 6 | SonKatarina23/react-django-playground | Playground/Accounts/apps.py | Python | AccountsConfig | AccountsConfig | 4 | 5 | 4 | 4 | 457c492ea307dd72c16c26a2cacf85bfd4f7c1c6 | bigcode/the-stack | train |
37b8de4a5e93dca24ac48738 | train | class | class C(A):
# Metodo constructor
def __init__(self, c, **kwargs):
super().__init__(**kwargs)
self.c = c # Nuevo atributo para la subclase
| class C(A):
# Metodo constructor
| def __init__(self, c, **kwargs):
super().__init__(**kwargs)
self.c = c # Nuevo atributo para la subclase
| self, b, **kwargs):
# Super nos permite acceder desde la subclase a metodos o atributos de la clase base.
super().__init__(**kwargs)
self.b = b
# Subclase que hereda de clase A
class C(A):
# Metodo constructor
| 64 | 64 | 43 | 9 | 54 | acasasaez/Ejercicios_POO1 | ejercicio_c.py | Python | C | C | 34 | 38 | 34 | 35 | 318db84382b595820443145aa276eda1b296386f | bigcode/the-stack | train |
36bda3416e20d48b452e635a | train | class | class A:
# Metodo Constructor
def __init__(self, a):
self.a = a
| class A:
# Metodo Constructor
| def __init__(self, a):
self.a = a
| se buscan de izquierda a derecha y de abajo a arriba y luego elimina todas
# las apariciones de una clase repetida menos la última.
#
# Ejercicio resuelto con el método super
### C L A S E S
# Clase superior o base
class A:
# Metodo Constructor
| 64 | 64 | 23 | 8 | 55 | acasasaez/Ejercicios_POO1 | ejercicio_c.py | Python | A | A | 18 | 21 | 18 | 19 | 45a7e30edebec93428cdea79582cd4116b40ed7d | bigcode/the-stack | train |
f1c3504adabd7790791ad8e0 | train | class | class D(B, C):
# Metodo constructor
def __init__(self, a1, b1, c1):
super().__init__(a = a1, b= b1, c = c1)
| class D(B, C):
# Metodo constructor
| def __init__(self, a1, b1, c1):
super().__init__(a = a1, b= b1, c = c1)
| ):
# Metodo constructor
def __init__(self, c, **kwargs):
super().__init__(**kwargs)
self.c = c # Nuevo atributo para la subclase
## Subclase inferior que hereda de B y C
class D(B, C):
# Metodo constructor
| 64 | 64 | 47 | 11 | 52 | acasasaez/Ejercicios_POO1 | ejercicio_c.py | Python | D | D | 41 | 44 | 41 | 42 | bc3b8169d5b0dff1993693be9105f34e8169b6b2 | bigcode/the-stack | train |
423cc9b95119dd10e6a8e5a0 | train | class | class B(A):
# Uso de **kwargs en una función se usa para pasar, de forma opcional, un número variable de argumentos
# con nombre. El parámetro recibe los argumentos como un diccionario.
# Metodo Constructor
def __init__(self, b, **kwargs):
# Super nos permite acceder desde la subclase a metodo... | class B(A):
# Uso de **kwargs en una función se usa para pasar, de forma opcional, un número variable de argumentos
# con nombre. El parámetro recibe los argumentos como un diccionario.
# Metodo Constructor
| def __init__(self, b, **kwargs):
# Super nos permite acceder desde la subclase a metodos o atributos de la clase base.
super().__init__(**kwargs)
self.b = b
| = a
# Subclase que hereda de clase A
class B(A):
# Uso de **kwargs en una función se usa para pasar, de forma opcional, un número variable de argumentos
# con nombre. El parámetro recibe los argumentos como un diccionario.
# Metodo Constructor
| 64 | 64 | 99 | 50 | 13 | acasasaez/Ejercicios_POO1 | ejercicio_c.py | Python | B | B | 24 | 31 | 24 | 27 | 3635c4239d29c8f297f5e07118cf660464ee04fd | bigcode/the-stack | train |
f451dc74f40ec8530ea6da9c | train | function | def commands():
import os
librosa_libs_path = os.path.join(getenv("PYTHON_LIBS_PATH"), "librosa", "%s"%version)
# env.PATH.append(os.path.join(librosa_libs_path, 'lib'))
env.PYTHONPATH.append(os.path.join(librosa_libs_path, 'lib'))
env.PATH.append(os.path.join(librosa_libs_path, 'Scripts'))
| def commands():
| import os
librosa_libs_path = os.path.join(getenv("PYTHON_LIBS_PATH"), "librosa", "%s"%version)
# env.PATH.append(os.path.join(librosa_libs_path, 'lib'))
env.PYTHONPATH.append(os.path.join(librosa_libs_path, 'lib'))
env.PATH.append(os.path.join(librosa_libs_path, 'Scripts'))
| librosa libraries
"""
requires = ["scipy",
"audioread",
"numpy",
"llvmlite",
"google",
"resampy",
"joblib",
"decorator",
"sklearn"
]
variants = []
def commands():
| 64 | 64 | 89 | 3 | 61 | cashmerepipeline/CashmereRez | PythonLibraries/librosa/0.6.0/package.py | Python | commands | commands | 25 | 33 | 25 | 25 | 65188dca0b30940d712ea2ac130ac23ccf4221cc | bigcode/the-stack | train |
b9fb49329aa037265ac45251 | train | class | class MyInstall(DistutilsInstall):
def run(self):
subprocess.call(['make', '-C', 'roi_pooling', 'build'])
DistutilsInstall.run(self)
| class MyInstall(DistutilsInstall):
| def run(self):
subprocess.call(['make', '-C', 'roi_pooling', 'build'])
DistutilsInstall.run(self)
|
from distutils.core import setup
from distutils.command.install import install as DistutilsInstall
import sys
import subprocess
try:
import tensorflow
except ImportError:
print("Please install tensorflow 0.12.0 or later")
sys.exit()
class MyInstall(DistutilsInstall):
| 63 | 64 | 37 | 8 | 55 | lemoner20/tensorlayer | tensorlayer/third_party/roi_pooling/setup.py | Python | MyInstall | MyInstall | 16 | 19 | 16 | 16 | 072b0bf7ad7c9f1ca82c2bb8895c4150dd83a820 | bigcode/the-stack | train |
e7437429154395fe9fb139f2 | train | function | def get_model(dataset, net_type, depth, n_classes):
"""
Available model
cifar:
preresnet
vgg
imagenet:
resnet
"""
if dataset in ["cifar10", "cifar100"]:
test_input = torch.randn(1, 3, 32, 32).cuda()
if net_type == "preresnet":
mod... | def get_model(dataset, net_type, depth, n_classes):
| """
Available model
cifar:
preresnet
vgg
imagenet:
resnet
"""
if dataset in ["cifar10", "cifar100"]:
test_input = torch.randn(1, 3, 32, 32).cuda()
if net_type == "preresnet":
model = md.PreResNet(depth=depth, num_classes=n_classes)... | import dcp.models as md
import torch
def get_model(dataset, net_type, depth, n_classes):
| 23 | 68 | 228 | 13 | 9 | liuyixin-louis/DCP_py3 | model_builder.py | Python | get_model | get_model | 5 | 31 | 5 | 5 | 521cf0b0a36c8db35d6b3614eaee39aad2250fa8 | bigcode/the-stack | train |
d747f096db1da84bc078db19 | train | class | class LossItemsLogCallback(EvaluationCallback):
def __init__(self, log_every, mode='mean'):
super(LossItemsLogCallback, self).__init__(pause_timers=False,
evaluate_every=log_every,
log_end=True,
... | class LossItemsLogCallback(EvaluationCallback):
| def __init__(self, log_every, mode='mean'):
super(LossItemsLogCallback, self).__init__(pause_timers=False,
evaluate_every=log_every,
log_end=True,
log_begi... | _module.counters.items():
setattr(self, name, value)
counters = self.get_counters(pl_module)
if self.timer.is_time(counters):
self.timer.update(counters)
self.evaluate(pl_module)
def on_train_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule) -> Non... | 90 | 90 | 302 | 9 | 81 | mfederici/dsit | framework/callbacks/evaluation_callbacks.py | Python | LossItemsLogCallback | LossItemsLogCallback | 76 | 115 | 76 | 76 | 78eeabe575e129bdfad31348909b6fb66c90b823 | bigcode/the-stack | train |
0a8dcee7ee98c77ce3bbc9ab | train | class | class EvaluationCallback(TimedCallback):
# Only one unit is currently supported: `10 minutes 10 seconds` is not a valid value
def __init__(self, name, evaluator, evaluate_every, log_end=True, log_beginning=True, pause_timers=True,
log_evaluation_time=True):
super(EvaluationCallback, sel... | class EvaluationCallback(TimedCallback):
# Only one unit is currently supported: `10 minutes 10 seconds` is not a valid value
| def __init__(self, name, evaluator, evaluate_every, log_end=True, log_beginning=True, pause_timers=True,
log_evaluation_time=True):
super(EvaluationCallback, self).__init__(time=evaluate_every)
self.evaluator = evaluator
self.name = name
self.timer_active = False
... | import time
import pytorch_lightning as pl
import numpy as np
from framework.callbacks.timed_callback import TimedCallback
from framework.logging.log_entry import SCALARS_ENTRY, LogEntry, SCALAR_ENTRY
class EvaluationCallback(TimedCallback):
# Only one unit is currently supported: `10 minutes 10 seconds` is not a... | 74 | 153 | 512 | 29 | 44 | mfederici/dsit | framework/callbacks/evaluation_callbacks.py | Python | EvaluationCallback | EvaluationCallback | 10 | 73 | 10 | 11 | 96156b4ec0e38e386ad15f2a9837a78dc32aa045 | bigcode/the-stack | train |
c753dd2289ab25210cbec608 | train | function | @pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
| @pytest.fixture
def entity_reg(hass):
| """Return an empty, loaded, registry."""
return mock_registry(hass)
| assert_lists_same,
async_get_device_automations,
async_mock_service,
mock_device_registry,
mock_registry,
)
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
| 64 | 64 | 26 | 9 | 55 | erogleva/core | tests/components/kodi/test_device_trigger.py | Python | entity_reg | entity_reg | 27 | 30 | 27 | 28 | d806a15212573047809638576bbbf402c2920c89 | bigcode/the-stack | train |
16abb6aa339d4e150f0c6540 | train | function | @pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
| @pytest.fixture
def device_reg(hass):
| """Return an empty, loaded, registry."""
return mock_device_registry(hass)
|
from homeassistant.setup import async_setup_component
from . import init_integration
from tests.common import (
MockConfigEntry,
assert_lists_same,
async_get_device_automations,
async_mock_service,
mock_device_registry,
mock_registry,
)
@pytest.fixture
def device_reg(hass):
| 64 | 64 | 27 | 9 | 55 | erogleva/core | tests/components/kodi/test_device_trigger.py | Python | device_reg | device_reg | 21 | 24 | 21 | 22 | d2640c18c71ad5960f8371d6015cd846c0148b2c | bigcode/the-stack | train |
92947e888dde781fb66f09cb | train | function | async def test_if_fires_on_state_change(hass, calls, kodi_media_player):
"""Test for turn_on and turn_off triggers firing."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
... | async def test_if_fires_on_state_change(hass, calls, kodi_media_player):
| """Test for turn_on and turn_off triggers firing."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
... | f"{MP_DOMAIN}.kodi_5678",
},
{
"platform": "device",
"domain": DOMAIN,
"type": "turn_on",
"device_id": device_entry.id,
"entity_id": f"{MP_DOMAIN}.kodi_5678",
},
]
triggers = await async_get_device_automations(hass, "trigger", ... | 114 | 114 | 382 | 18 | 96 | erogleva/core | tests/components/kodi/test_device_trigger.py | Python | test_if_fires_on_state_change | test_if_fires_on_state_change | 75 | 137 | 75 | 75 | 0392630430f7af2ec446bd8e466574368eff81e1 | bigcode/the-stack | train |
d801dfaae7d1793d48219217 | train | function | @pytest.fixture
async def kodi_media_player(hass):
"""Get a kodi media player."""
await init_integration(hass)
return f"{MP_DOMAIN}.name"
| @pytest.fixture
async def kodi_media_player(hass):
| """Get a kodi media player."""
await init_integration(hass)
return f"{MP_DOMAIN}.name"
| entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture
async def kodi_media_player(hass):
| 64 | 64 | 36 | 11 | 53 | erogleva/core | tests/components/kodi/test_device_trigger.py | Python | kodi_media_player | kodi_media_player | 39 | 43 | 39 | 40 | 327a081c07b56833ad19d623638c94111985d712 | bigcode/the-stack | train |
8aa48bda2ee90be077cb33ac | train | function | async def test_get_triggers(hass, device_reg, entity_reg):
"""Test we get the expected triggers from a kodi."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
iden... | async def test_get_triggers(hass, device_reg, entity_reg):
| """Test we get the expected triggers from a kodi."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={(DOMAIN, "host", 1234)},
)
entity_reg.asyn... | """Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture
async def kodi_media_player(hass):
"""Get a kodi media player."""
await init_integration(hass)
return f"{MP_DOMAIN}.name"
async def test_get_triggers(hass, device_reg, entity_reg):
| 74 | 74 | 247 | 15 | 59 | erogleva/core | tests/components/kodi/test_device_trigger.py | Python | test_get_triggers | test_get_triggers | 46 | 72 | 46 | 46 | f121dc4a18251d99a36c5e2dd89194950ba5b259 | bigcode/the-stack | train |
5c9a8d7a899ca6f97882b039 | train | function | @pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
| @pytest.fixture
def calls(hass):
| """Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
| _registry,
)
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture
def calls(hass):
| 64 | 64 | 31 | 8 | 56 | erogleva/core | tests/components/kodi/test_device_trigger.py | Python | calls | calls | 33 | 36 | 33 | 34 | b7f416106e10ac548681ca4dee417a5161181aae | bigcode/the-stack | train |
60109f34a643f5bf6f176de0 | train | class | class Flow(object):
"""Flow object extracted from pcap file that can be used for fingerprinting
Attributes
----------
src : string
Source IP
sport : int
Source port
dst : string
Destination IP
dport : int
Destination... | class Flow(object):
| """Flow object extracted from pcap file that can be used for fingerprinting
Attributes
----------
src : string
Source IP
sport : int
Source port
dst : string
Destination IP
dport : int
Destination port
sourc... | from datetime import datetime
import ipaddress
################################################################################
# Single Flow object #
################################################################################
class Flow(object):
| 24 | 256 | 1,623 | 4 | 19 | jmhIcoding/flowcontainer | build/lib/flowcontainer/flows.py | Python | Flow | Flow | 8 | 206 | 8 | 8 | b738267b0f4a89ecbae29851173519c1c9b9a52b | bigcode/the-stack | train |
d3358c451e5f79fc6ac954df | train | class | class ExpressRouteGatewaysOperations:
"""ExpressRouteGatewaysOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operati... | class ExpressRouteGatewaysOperations:
| """ExpressRouteGatewaysOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgm... | # 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 may ... | 234 | 256 | 4,547 | 7 | 227 | praveenkuttappan/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_11_01/aio/operations/_express_route_gateways_operations.py | Python | ExpressRouteGatewaysOperations | ExpressRouteGatewaysOperations | 23 | 443 | 23 | 23 | a4f2c7d02e3703fdd7069b77ea230046518362bd | bigcode/the-stack | train |
51f7e0714d12e7d73b83e492 | train | class | class UnexpectedRelationshipState(Exception):
pass
| class UnexpectedRelationshipState(Exception):
| pass
| class UnexpectedRelationshipState(Exception):
| 6 | 64 | 9 | 6 | 0 | restato/bunnybook | backend/profiles/exceptions.py | Python | UnexpectedRelationshipState | UnexpectedRelationshipState | 1 | 2 | 1 | 1 | 60e174885475e67b191e9b56643b12f520dd9755 | bigcode/the-stack | train |
9a57d06e8758e500602142da | train | class | class ConfigFileNotFoundException(Exception):
pass
| class ConfigFileNotFoundException(Exception):
| pass
| _configs(more_general_config, more_specific_config) -> dict:
"""
:return: merge more general config with more specific configs.
More specific config values take precedence over more general ones.
"""
return dict(merge({}, more_general_config, more_specific_config))
class... | 64 | 64 | 11 | 8 | 56 | egnyte/gitlabform | gitlabform/configuration/core.py | Python | ConfigFileNotFoundException | ConfigFileNotFoundException | 148 | 149 | 148 | 148 | 9583d177a1753df94d154dee5c0df19e7949cf22 | bigcode/the-stack | train |
e1a8feeb5f1a9deb82ec59ab | train | class | class KeyNotFoundException(Exception):
pass
| class KeyNotFoundException(Exception):
| pass
| over more general ones.
"""
return dict(merge({}, more_general_config, more_specific_config))
class ConfigFileNotFoundException(Exception):
pass
class ConfigInvalidException(Exception):
def __init__(self, underlying: Exception):
self.underlying = underlying
class KeyNotFoundExceptio... | 64 | 64 | 10 | 7 | 56 | egnyte/gitlabform | gitlabform/configuration/core.py | Python | KeyNotFoundException | KeyNotFoundException | 157 | 158 | 157 | 157 | ce9a4143d1cf8b73d0f78a0f07146adfd2e2a4b7 | bigcode/the-stack | train |
fb2e3df8c4f517cb370c1747 | train | class | class ConfigInvalidException(Exception):
def __init__(self, underlying: Exception):
self.underlying = underlying
| class ConfigInvalidException(Exception):
| def __init__(self, underlying: Exception):
self.underlying = underlying
| ) -> dict:
"""
:return: merge more general config with more specific configs.
More specific config values take precedence over more general ones.
"""
return dict(merge({}, more_general_config, more_specific_config))
class ConfigFileNotFoundException(Exception):
pas... | 64 | 64 | 25 | 6 | 57 | egnyte/gitlabform | gitlabform/configuration/core.py | Python | ConfigInvalidException | ConfigInvalidException | 152 | 154 | 152 | 152 | f8f20477d613205819a7d56363d37cfb107c4b2c | bigcode/the-stack | train |
8b9d06350c8ecb08993ac5d6 | train | class | class ConfigurationCore(ABC):
config = None
config_dir = None
def __init__(self, config_path=None, config_string=None):
if config_path and config_string:
fatal(
"Please initialize with either config_path or config_string, not both.",
exit_code=EXIT_INVA... | class ConfigurationCore(ABC):
| config = None
config_dir = None
def __init__(self, config_path=None, config_string=None):
if config_path and config_string:
fatal(
"Please initialize with either config_path or config_string, not both.",
exit_code=EXIT_INVALID_INPUT,
)
... | import os
import textwrap
from logging import debug
from abc import ABC
from cli_ui import debug as verbose
from cli_ui import fatal
import yaml
from pathlib import Path
from mergedeep import merge
from gitlabform import EXIT_INVALID_INPUT
class ConfigurationCore(ABC):
| 61 | 256 | 1,003 | 6 | 54 | egnyte/gitlabform | gitlabform/configuration/core.py | Python | ConfigurationCore | ConfigurationCore | 16 | 145 | 16 | 17 | 421e5e24d2772509eadb013923382cdf0e61ca77 | bigcode/the-stack | train |
27ba8faf38539ce83660b38f | train | class | class SaveVecNormalizeCallback(BaseCallback):
"""
Callback for saving a VecNormalize wrapper every ``save_freq`` steps
:param save_freq: (int)
:param save_path: (str) Path to the folder where ``VecNormalize`` will be saved, as ``vecnormalize.pkl``
:param name_prefix: (str) Common prefix to the save... | class SaveVecNormalizeCallback(BaseCallback):
| """
Callback for saving a VecNormalize wrapper every ``save_freq`` steps
:param save_freq: (int)
:param save_path: (str) Path to the folder where ``VecNormalize`` will be saved, as ``vecnormalize.pkl``
:param name_prefix: (str) Common prefix to the saved ``VecNormalize``, if None (default)
... | _freq == 0:
super(TrialEvalCallback, self)._on_step()
self.eval_idx += 1
# report best or report current ?
# report num_timesteps or elasped time ?
self.trial.report(self.last_mean_reward, self.eval_idx)
# Prune trial if need
if self.tr... | 100 | 100 | 335 | 8 | 91 | mcx-lab/rl-baselines3-zoo | utils/callbacks.py | Python | SaveVecNormalizeCallback | SaveVecNormalizeCallback | 62 | 99 | 62 | 62 | b27883249665724e1b6365c6b83cb1b27e856d95 | bigcode/the-stack | train |
e7d2d136c4e2613358cf32c3 | train | class | class ParallelTrainCallback(BaseCallback):
"""
Callback to explore (collect experience) and train (do gradient steps)
at the same time using two separate threads.
Normally used with off-policy algorithms and `train_freq=(1, "episode")`.
TODO:
- blocking mode: wait for the model to finish updati... | class ParallelTrainCallback(BaseCallback):
| """
Callback to explore (collect experience) and train (do gradient steps)
at the same time using two separate threads.
Normally used with off-policy algorithms and `train_freq=(1, "episode")`.
TODO:
- blocking mode: wait for the model to finish updating the policy before collecting new experie... | save_path: str,
name_prefix: Optional[str] = None,
verbose: int = 0,
):
super(SaveVecNormalizeCallback, self).__init__(verbose)
self.save_freq = save_freq
self.save_path = save_path
self.name_prefix = name_prefix
def _init_callback(self) -> None:
... | 231 | 231 | 773 | 7 | 223 | mcx-lab/rl-baselines3-zoo | utils/callbacks.py | Python | ParallelTrainCallback | ParallelTrainCallback | 102 | 203 | 102 | 102 | 39648639f37ec0ad1981cc851d77912204b75d26 | bigcode/the-stack | train |
8a28c0626aa7883a68df8860 | train | class | class A1GymEnvLoggingCallback(BaseCallback):
"""
Callback for A1GymEnv to log relevant quantities, such as reward components values
"""
def _on_step(self) -> bool:
# For VecEnv envs, infos will be a list of info dicts
infos = self.locals["infos"]
# Flatten rewards into single bu... | class A1GymEnvLoggingCallback(BaseCallback):
| """
Callback for A1GymEnv to log relevant quantities, such as reward components values
"""
def _on_step(self) -> bool:
# For VecEnv envs, infos will be a list of info dicts
infos = self.locals["infos"]
# Flatten rewards into single buffer
reward_buffer = defaultdict(list... | .process.join()
def _on_training_end(self) -> None:
# Wait for the thread to terminate
if self.process is not None:
if self.verbose > 0:
print("Waiting for training thread to terminate")
self.process.join()
class A1GymEnvLoggingCallback(BaseCallback):
| 64 | 64 | 186 | 10 | 54 | mcx-lab/rl-baselines3-zoo | utils/callbacks.py | Python | A1GymEnvLoggingCallback | A1GymEnvLoggingCallback | 206 | 223 | 206 | 206 | 8fa24a4f75af353185b58d91b885f193b20ce625 | bigcode/the-stack | train |
f1ecb5bb02b4a0d1845c4a5a | train | class | class TrialEvalCallback(EvalCallback):
"""
Callback used for evaluating and reporting a trial.
"""
def __init__(
self,
eval_env: VecEnv,
trial: optuna.Trial,
n_eval_episodes: int = 5,
eval_freq: int = 10000,
deterministic: bool = True,
verbose: in... | class TrialEvalCallback(EvalCallback):
| """
Callback used for evaluating and reporting a trial.
"""
def __init__(
self,
eval_env: VecEnv,
trial: optuna.Trial,
n_eval_episodes: int = 5,
eval_freq: int = 10000,
deterministic: bool = True,
verbose: int = 0,
best_model_save_path: Op... | os
import tempfile
import time
from copy import deepcopy
from functools import wraps
from threading import Thread
from typing import Optional
import optuna
from sb3_contrib import TQC
from stable_baselines3 import SAC
from stable_baselines3.common.callbacks import BaseCallback, EvalCallback
from stable_baselines3.com... | 93 | 93 | 313 | 8 | 84 | mcx-lab/rl-baselines3-zoo | utils/callbacks.py | Python | TrialEvalCallback | TrialEvalCallback | 18 | 59 | 18 | 18 | 8af232597fbc6b1910fa8ae72d507ed9af60afe0 | bigcode/the-stack | train |
bd37e65b27a07eefd160d5ec | train | class | class SuiteRunner:
def __init__(self, run_config, these_entries):
# initialize callbacks
self.print_callback = None
self.starting_callback = None
self.case_completed_callback = None
self.simulations_complete_callback = None
self.diff_completed_callback = None
... | class SuiteRunner:
| def __init__(self, run_config, these_entries):
# initialize callbacks
self.print_callback = None
self.starting_callback = None
self.case_completed_callback = None
self.simulations_complete_callback = None
self.diff_completed_callback = None
self.all_done_call... | ressions import energyplus
from epregressions.structures import (
ForceRunType,
TextDifferences,
EndErrSummary,
MathDifferences,
TableDifferences,
CompletedStructure,
ReportingFreq,
TestEntry
)
# get the current file path for convenience
path = os.path.dirname(__file__)
script_dir = os... | 256 | 256 | 7,520 | 4 | 251 | rraustad/EnergyPlusRegressionTool | epregressions/runtests.py | Python | SuiteRunner | SuiteRunner | 56 | 758 | 56 | 57 | 7fe7e1d462e477d1864d6c54f73f6a4d18dbd3c7 | bigcode/the-stack | train |
a29413e43ef54c8f8381ed0e | train | class | class TestCaseCompleted:
def __init__(self, run_directory, case_name, run_status, error_msg_reported_already, name_of_thread):
self.run_directory = run_directory
self.case_name = case_name
self.run_success = run_status
self.name_of_thread = name_of_thread
self.muffle_err_msg ... | class TestCaseCompleted:
| def __init__(self, run_directory, case_name, run_status, error_msg_reported_already, name_of_thread):
self.run_directory = run_directory
self.case_name = case_name
self.run_success = run_status
self.name_of_thread = name_of_thread
self.muffle_err_msg = error_msg_reported_alre... | _b, single_test_run=False):
self.force_run_type = force_run_type
self.TestOneFile = single_test_run
self.num_threads = num_threads
self.buildA = build_a
self.buildB = build_b
self.report_freq = report_freq
class TestCaseCompleted:
| 64 | 64 | 80 | 5 | 58 | rraustad/EnergyPlusRegressionTool | epregressions/runtests.py | Python | TestCaseCompleted | TestCaseCompleted | 46 | 52 | 46 | 46 | f3c4f2601bbe5174bd69baf621c77cd813790e68 | bigcode/the-stack | train |
b850f37f3a53725082199f55 | train | class | class TestRunConfiguration:
def __init__(self, force_run_type, num_threads, report_freq, build_a, build_b, single_test_run=False):
self.force_run_type = force_run_type
self.TestOneFile = single_test_run
self.num_threads = num_threads
self.buildA = build_a
self.buildB = build_... | class TestRunConfiguration:
| def __init__(self, force_run_type, num_threads, report_freq, build_a, build_b, single_test_run=False):
self.force_run_type = force_run_type
self.TestOneFile = single_test_run
self.num_threads = num_threads
self.buildA = build_a
self.buildB = build_b
self.report_freq =... | ,
TextDifferences,
EndErrSummary,
MathDifferences,
TableDifferences,
CompletedStructure,
ReportingFreq,
TestEntry
)
# get the current file path for convenience
path = os.path.dirname(__file__)
script_dir = os.path.abspath(path)
class TestRunConfiguration:
| 64 | 64 | 85 | 5 | 59 | rraustad/EnergyPlusRegressionTool | epregressions/runtests.py | Python | TestRunConfiguration | TestRunConfiguration | 36 | 43 | 36 | 36 | 2a4516ad5c107ecbdf6fe107b1e930fb0e111207 | bigcode/the-stack | train |
24b03c3e97340dc5a7f022a8 | train | class | class VariableMgr(object):
def __init__(self, DefaultStoreMap,SkuIdMap):
self.VarInfo = []
self.DefaultStoreMap = DefaultStoreMap
self.SkuIdMap = SkuIdMap
self.VpdRegionSize = 0
self.VpdRegionOffset = 0
self.NVHeaderBuff = None
self.VarDefaultBuff = None
... | class VariableMgr(object):
| def __init__(self, DefaultStoreMap,SkuIdMap):
self.VarInfo = []
self.DefaultStoreMap = DefaultStoreMap
self.SkuIdMap = SkuIdMap
self.VpdRegionSize = 0
self.VpdRegionOffset = 0
self.NVHeaderBuff = None
self.VarDefaultBuff = None
self.VarDeltaBuff = None... | var_info = collections.namedtuple("uefi_var", "pcdindex,pcdname,defaultstoragename,skuname,var_name, var_guid, var_offset,var_attribute,pcd_default_value, default_value, data_type")
NvStorageHeaderSize = 28
VariableHeaderSize = 32
def StringArrayToList(StringArray):
StringArray = StringArray[1:-1]
StringArray ... | 256 | 256 | 3,421 | 5 | 250 | d9930239/EDK2 | BaseTools/Source/Python/AutoGen/GenVar.py | Python | VariableMgr | VariableMgr | 49 | 391 | 49 | 49 | 55790b2f3d9eb6ed875f298a915f18d6f5fe552d | bigcode/the-stack | train |
4a1b0379a99c243c945a6002 | train | function | def PackGUID(Guid):
GuidBuffer = pack('=LHHBBBBBBBB',
int(Guid[0], 16),
int(Guid[1], 16),
int(Guid[2], 16),
int(Guid[3][-4:-2], 16),
int(Guid[3][-2:], 16),
int(Guid[4][-12:-10], 16),
int(Guid[4][-10:-8], ... | def PackGUID(Guid):
| GuidBuffer = pack('=LHHBBBBBBBB',
int(Guid[0], 16),
int(Guid[1], 16),
int(Guid[2], 16),
int(Guid[3][-4:-2], 16),
int(Guid[3][-2:], 16),
int(Guid[4][-12:-10], 16),
int(Guid[4][-10:-8], 16),
... | _value, default_value, data_type")
NvStorageHeaderSize = 28
VariableHeaderSize = 32
def StringArrayToList(StringArray):
StringArray = StringArray[1:-1]
StringArray = '[' + StringArray + ']'
return eval(StringArray)
def PackGUID(Guid):
| 64 | 64 | 151 | 5 | 59 | d9930239/EDK2 | BaseTools/Source/Python/AutoGen/GenVar.py | Python | PackGUID | PackGUID | 33 | 47 | 33 | 33 | 176bc74a6e248a9b2accd7cb5ea29233daa191b8 | bigcode/the-stack | train |
a3afe69debcb512b6d061f47 | train | function | def StringArrayToList(StringArray):
StringArray = StringArray[1:-1]
StringArray = '[' + StringArray + ']'
return eval(StringArray)
| def StringArrayToList(StringArray):
| StringArray = StringArray[1:-1]
StringArray = '[' + StringArray + ']'
return eval(StringArray)
| fi_var", "pcdindex,pcdname,defaultstoragename,skuname,var_name, var_guid, var_offset,var_attribute,pcd_default_value, default_value, data_type")
NvStorageHeaderSize = 28
VariableHeaderSize = 32
def StringArrayToList(StringArray):
| 64 | 64 | 36 | 8 | 55 | d9930239/EDK2 | BaseTools/Source/Python/AutoGen/GenVar.py | Python | StringArrayToList | StringArrayToList | 28 | 31 | 28 | 28 | ede7c4c425fdc1aef6c0a3a97680b3a6ac138331 | bigcode/the-stack | train |
7175d0fdfc6e1869a6150d48 | train | class | class PolarShapelets(LensProfileBase):
"""
this class contains the function and the derivatives of the Singular Isothermal Sphere
"""
param_names = ['coeffs', 'beta', 'center_x', 'center_y']
lower_limit_default = {'coeffs': [0], 'beta': 0, 'center_x': -100, 'center_y': -100}
upper_limit_default ... | class PolarShapelets(LensProfileBase):
| """
this class contains the function and the derivatives of the Singular Isothermal Sphere
"""
param_names = ['coeffs', 'beta', 'center_x', 'center_y']
lower_limit_default = {'coeffs': [0], 'beta': 0, 'center_x': -100, 'center_y': -100}
upper_limit_default = {'coeffs': [100], 'beta': 100, 'cente... | __author__ = 'sibirrer'
# description of the polar shapelets in potential space
import numpy as np
import scipy.special
import math
import lenstronomy.Util.param_util as param_util
from lenstronomy.LensModel.Profiles.base_profile import LensProfileBase
class PolarShapelets(LensProfileBase):
| 68 | 256 | 2,694 | 9 | 58 | tvelagapudi/lenstronomy | lenstronomy/LensModel/Profiles/shapelet_pot_polar.py | Python | PolarShapelets | PolarShapelets | 13 | 233 | 13 | 13 | 0f502c2a5e22c0c8f3e9ab7b02738b8e0ec01d6c | bigcode/the-stack | train |
81f50c3665c2e87cfd850262 | train | class | class CaldaiemuraliItSpider(BaseSpider):
name = "caldaiemurali.it"
allowed_domains = ["caldaiemurali.it"]
start_urls = (
'http://www.caldaiemurali.it/',
)
def parse(self, response):
hxs = HtmlXPathSelector(response)
categories = hxs.select("//ul[@id='nav']//a/@href").ex... | class CaldaiemuraliItSpider(BaseSpider):
| name = "caldaiemurali.it"
allowed_domains = ["caldaiemurali.it"]
start_urls = (
'http://www.caldaiemurali.it/',
)
def parse(self, response):
hxs = HtmlXPathSelector(response)
categories = hxs.select("//ul[@id='nav']//a/@href").extract()
for category in categorie... | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from product_spiders.items import Product, ProductLoader
from decimal import Decimal
import logging
class CaldaiemuraliItSpider(BaseSpider):
| 52 | 146 | 488 | 11 | 40 | 0--key/lib | portfolio/Python/scrapy/rosarioweb/caldaiemurali_it.py | Python | CaldaiemuraliItSpider | CaldaiemuraliItSpider | 11 | 61 | 11 | 11 | 395037b94bf920ad60f5f55f86259a8fb82d00ff | bigcode/the-stack | train |
be31f13a02509ece6220be86 | train | class | class Classifier(object):
def __init__(self, config):
self.omdb = Omdb(config)
self.config = config
def get_types(self, path):
types = []
if os.path.isdir(path):
for folder, _, files in os.walk(path):
for filename in files:
types.... | class Classifier(object):
| def __init__(self, config):
self.omdb = Omdb(config)
self.config = config
def get_types(self, path):
types = []
if os.path.isdir(path):
for folder, _, files in os.walk(path):
for filename in files:
types.append(mimetypes.guess_type... | import operator
import os
import mimetypes
from mediasort.classify.omdb import Omdb
from mediasort.classify.imdb import (
find_nfos,
extract_imdb_id,
)
from mediasort.classify.tv import detect_tv
from mediasort.classify.movies import detect_movie
from mediasort.classify.music import detect_music
from medias... | 106 | 128 | 427 | 5 | 101 | aroberts/mediasort | mediasort/classify/__init__.py | Python | Classifier | Classifier | 24 | 89 | 24 | 25 | f105c514da90dde01571150b21eb438cda7829c6 | bigcode/the-stack | train |
3dbfe09bc738879953263cee | train | function | def new_rectilinear(**kwds):
from pymt.grids import RectilinearField
ndims = kwds.pop("ndims", 1)
shape = np.random.randint(3, 101 + 1, ndims)
args = []
for size in shape:
args.append(np.cumsum((1.0 - np.random.random(size))))
return RectilinearField(*args, **kwds)
| def new_rectilinear(**kwds):
| from pymt.grids import RectilinearField
ndims = kwds.pop("ndims", 1)
shape = np.random.randint(3, 101 + 1, ndims)
args = []
for size in shape:
args.append(np.cumsum((1.0 - np.random.random(size))))
return RectilinearField(*args, **kwds)
| import os
import numpy as np
import pytest
from pymt.printers.nc.ugrid import (
NetcdfRectilinearField,
NetcdfStructuredField,
NetcdfUnstructuredField,
)
def new_rectilinear(**kwds):
| 54 | 64 | 92 | 9 | 45 | mwtoews/pymt | tests/printers/nc/test_ugrid.py | Python | new_rectilinear | new_rectilinear | 13 | 22 | 13 | 13 | 268f594fdf2d2396268ce7c6e760e75fbec62dc7 | bigcode/the-stack | train |
61242cb20ddae398a10d76bd | train | function | @pytest.mark.parametrize("ndims", (1, 2, 3))
@pytest.mark.parametrize("grid", ("rectilinear", "structured", "unstructured"))
def test_rectilinear_points(tmpdir, grid, ndims):
field = new_rectilinear(
ndims=ndims,
coordinate_names=("elevation", "latitude", "longitude"),
units=("m", "degrees_n... | @pytest.mark.parametrize("ndims", (1, 2, 3))
@pytest.mark.parametrize("grid", ("rectilinear", "structured", "unstructured"))
def test_rectilinear_points(tmpdir, grid, ndims):
| field = new_rectilinear(
ndims=ndims,
coordinate_names=("elevation", "latitude", "longitude"),
units=("m", "degrees_north", "degrees_east"),
)
data = np.arange(field.get_point_count())
field.add_field("air_temperature", data, centering="point", units="F")
with tmpdir.as_cwd(... | cdfStructuredField,
"unstructured": NetcdfUnstructuredField,
}
@pytest.mark.parametrize("ndims", (1, 2, 3))
@pytest.mark.parametrize("grid", ("rectilinear", "structured", "unstructured"))
def test_rectilinear_points(tmpdir, grid, ndims):
| 64 | 64 | 156 | 48 | 16 | mwtoews/pymt | tests/printers/nc/test_ugrid.py | Python | test_rectilinear_points | test_rectilinear_points | 32 | 45 | 32 | 34 | 6f223abf692eec2f80eb7505b366fa76d1d0a932 | bigcode/the-stack | train |
4862707c2c834b51cd7db8c6 | train | class | class FeudalBatch(object):
def __init__(self):
self.obs = []
self.a = []
self.returns = []
self.s_diff = []
self.ri = []
self.gsum = []
self.features = None
def add(self, obs, a, returns, s_diff, ri, gsum, features):
self.obs += [obs]
self... | class FeudalBatch(object):
| def __init__(self):
self.obs = []
self.a = []
self.returns = []
self.s_diff = []
self.ri = []
self.gsum = []
self.features = None
def add(self, obs, a, returns, s_diff, ri, gsum, features):
self.obs += [obs]
self.a += [a]
self.retu... | as np
from collections import namedtuple
def cosine_similarity(u, v):
return np.dot(np.squeeze(u), np.squeeze(v)) / (np.linalg.norm(u) * np.linalg.norm(v))
Batch = namedtuple("Batch", ["obs", "a", "returns", "s_diff", "ri", "gsum", "features"])
class FeudalBatch(object):
| 77 | 78 | 260 | 6 | 71 | jasonplato/RL_for_AutonomousGreenhouse | FeudalBatchProcessor.py | Python | FeudalBatch | FeudalBatch | 12 | 41 | 12 | 12 | 060bde1a35a2df1fea48d74091188d27cec4425c | bigcode/the-stack | train |
bbc3e2a2a852fa8832937df1 | train | function | def cosine_similarity(u, v):
return np.dot(np.squeeze(u), np.squeeze(v)) / (np.linalg.norm(u) * np.linalg.norm(v))
| def cosine_similarity(u, v):
| return np.dot(np.squeeze(u), np.squeeze(v)) / (np.linalg.norm(u) * np.linalg.norm(v))
| import numpy as np
from collections import namedtuple
def cosine_similarity(u, v):
| 18 | 64 | 32 | 7 | 10 | jasonplato/RL_for_AutonomousGreenhouse | FeudalBatchProcessor.py | Python | cosine_similarity | cosine_similarity | 5 | 6 | 5 | 5 | 08c3f51767527a64c1acc9959e8a3f61e5e716bc | bigcode/the-stack | train |
ccd09cb2482ae8034050ed99 | train | class | class FeudalBatchProcessor(object):
"""
This class adapts the batch of PolicyOptimizer to a batch useable by
the FeudalPolicy.
"""
def __init__(self, c):
self.c = c
self.last_terminal = True
def _extend(self, batch):
if self.last_terminal:
self.last_terminal... | class FeudalBatchProcessor(object):
| """
This class adapts the batch of PolicyOptimizer to a batch useable by
the FeudalPolicy.
"""
def __init__(self, c):
self.c = c
self.last_terminal = True
def _extend(self, batch):
if self.last_terminal:
self.last_terminal = False
self.s = [batch... | self):
self.obs = []
self.a = []
self.returns = []
self.s_diff = []
self.ri = []
self.gsum = []
self.features = None
def add(self, obs, a, returns, s_diff, ri, gsum, features):
self.obs += [obs]
self.a += [a]
self.returns += [returns]
... | 256 | 256 | 870 | 7 | 249 | jasonplato/RL_for_AutonomousGreenhouse | FeudalBatchProcessor.py | Python | FeudalBatchProcessor | FeudalBatchProcessor | 44 | 143 | 44 | 44 | 48b8b22a1d1d5d3235bc24aa629fc14cc71c45cd | bigcode/the-stack | train |
cf50b7902f731d0c0acb7a44 | train | class | class AcmeDnsChallenge(AcmeChallenge):
challengeType = challenges.DNS01
def create_certificate(self, csr, issuer_options):
"""
Creates an ACME certificate.
:param csr:
:param issuer_options:
:return: :raise Exception:
"""
self.acme = AcmeDnsHandler()
... | class AcmeDnsChallenge(AcmeChallenge):
| challengeType = challenges.DNS01
def create_certificate(self, csr, issuer_options):
"""
Creates an ACME certificate.
:param csr:
:param issuer_options:
:return: :raise Exception:
"""
self.acme = AcmeDnsHandler()
authority = issuer_options.get("au... | , challenges.HTTP01):
raise AcmeChallengeMissmatchError(
'The provided challenge is not of type HTTP01, but instead of type {}'.format(
challenge.__class__.__name__))
destination = destination_service.get(validation_target)
if destination is None:
... | 246 | 247 | 825 | 10 | 236 | bobmshannon/lemur | lemur/plugins/lemur_acme/challenge_types.py | Python | AcmeDnsChallenge | AcmeDnsChallenge | 187 | 290 | 187 | 187 | a3d5c44509032ae0a90c171e7c318a940ab9f9cc | bigcode/the-stack | train |
8299fb4824b412681d846501 | train | class | class AcmeChallenge(object):
"""
This is the base class, all ACME challenges will need to extend, allowing for future extendability
"""
def create_certificate(self, csr, issuer_options):
"""
Create the new certificate, using the provided CSR and issuer_options.
Right now this is... | class AcmeChallenge(object):
| """
This is the base class, all ACME challenges will need to extend, allowing for future extendability
"""
def create_certificate(self, csr, issuer_options):
"""
Create the new certificate, using the provided CSR and issuer_options.
Right now this is basically a copy of the crea... | ACME_ADDITIONAL_ATTEMPTS
from lemur.exceptions import LemurException, InvalidConfiguration
from lemur.extensions import metrics
from lemur.plugins.base import plugins
from lemur.destinations import service as destination_service
from lemur.plugins.lemur_acme.acme_handlers import AcmeHandler, AcmeDnsHandler
from retry... | 96 | 96 | 321 | 6 | 89 | bobmshannon/lemur | lemur/plugins/lemur_acme/challenge_types.py | Python | AcmeChallenge | AcmeChallenge | 35 | 70 | 35 | 35 | ddcb91190d3d9a92a32c0883005c236e78e9f563 | bigcode/the-stack | train |
da6ac5be5d0f4880de3b4d2b | train | class | class AcmeChallengeMissmatchError(LemurException):
pass
| class AcmeChallengeMissmatchError(LemurException):
| pass
| ur.extensions import metrics
from lemur.plugins.base import plugins
from lemur.destinations import service as destination_service
from lemur.plugins.lemur_acme.acme_handlers import AcmeHandler, AcmeDnsHandler
from retrying import retry
class AcmeChallengeMissmatchError(LemurException):
| 64 | 64 | 15 | 12 | 51 | bobmshannon/lemur | lemur/plugins/lemur_acme/challenge_types.py | Python | AcmeChallengeMissmatchError | AcmeChallengeMissmatchError | 31 | 32 | 31 | 31 | c1de4dcf96d9919381a022ba9bf68153e6b656ca | bigcode/the-stack | train |
5507e3ed5ed7459851198f24 | train | class | class AcmeHttpChallenge(AcmeChallenge):
challengeType = challenges.HTTP01
def create_certificate(self, csr, issuer_options):
"""
Creates an ACME certificate using the HTTP-01 challenge.
:param csr:
:param issuer_options:
:return: :raise Exception:
"""
se... | class AcmeHttpChallenge(AcmeChallenge):
| challengeType = challenges.HTTP01
def create_certificate(self, csr, issuer_options):
"""
Creates an ACME certificate using the HTTP-01 challenge.
:param csr:
:param issuer_options:
:return: :raise Exception:
"""
self.acme = AcmeHandler()
authorit... | meHandlers, but should be cleaned
and tried to make use of the deploy and cleanup methods
:param csr:
:param issuer_options:
:return:
"""
pass
def deploy(self, challenge, acme_client, validation_target):
"""
In here the challenge validation is fetche... | 256 | 256 | 959 | 10 | 245 | bobmshannon/lemur | lemur/plugins/lemur_acme/challenge_types.py | Python | AcmeHttpChallenge | AcmeHttpChallenge | 73 | 184 | 73 | 73 | 22c5b835fc46ed7d027794efaf903d265a110c27 | bigcode/the-stack | train |
dcc5ad5e03e46967bf8743a8 | train | function | @torch.no_grad()
def main(args):
env = BlockPushing(render_type="shapes", background=BlockPushing.BACKGROUND_DETERMINISTIC)
bisim_model = make_pairwise_encoder()
bisim_model.load_state_dict(torch.load(args.model_path))
bisim_model.to(args.device)
for _ in range(10):
env.reset()
b... | @torch.no_grad()
def main(args):
| env = BlockPushing(render_type="shapes", background=BlockPushing.BACKGROUND_DETERMINISTIC)
bisim_model = make_pairwise_encoder()
bisim_model.load_state_dict(torch.load(args.model_path))
bisim_model.to(args.device)
for _ in range(10):
env.reset()
base_image = env.render()
... | else:
tmp_image = np.concatenate([image, base_image], axis=0)
ret.append(tmp_image)
return ret
def stack_to_pt(images, device):
images = np.stack(images, axis=0)
return torch.tensor(images, dtype=torch.float32, device=device)
def plot_all_images(images):
for idx, image in en... | 117 | 117 | 392 | 9 | 108 | dmcinerney/c-swm | scr/envs/block_pushing_model_show.py | Python | main | main | 43 | 90 | 43 | 45 | a4fe3504d3eca3f16b9dd205d33376439faa5305 | bigcode/the-stack | train |
a0604cf32455cc7ce487705a | train | function | def stack_to_pt(images, device):
images = np.stack(images, axis=0)
return torch.tensor(images, dtype=torch.float32, device=device)
| def stack_to_pt(images, device):
| images = np.stack(images, axis=0)
return torch.tensor(images, dtype=torch.float32, device=device)
| for image in other_images:
if base_first:
tmp_image = np.concatenate([base_image, image], axis=0)
else:
tmp_image = np.concatenate([image, base_image], axis=0)
ret.append(tmp_image)
return ret
def stack_to_pt(images, device):
| 64 | 64 | 33 | 8 | 55 | dmcinerney/c-swm | scr/envs/block_pushing_model_show.py | Python | stack_to_pt | stack_to_pt | 27 | 30 | 27 | 28 | cad635d09ea5898630ed2e9281fc6a1697aa2d0b | bigcode/the-stack | train |
7bb33d85131b22f881f95e85 | train | function | def pair(base_image, other_images, base_first=True):
ret = []
for image in other_images:
if base_first:
tmp_image = np.concatenate([base_image, image], axis=0)
else:
tmp_image = np.concatenate([image, base_image], axis=0)
ret.append(tmp_image)
return ret
| def pair(base_image, other_images, base_first=True):
| ret = []
for image in other_images:
if base_first:
tmp_image = np.concatenate([base_image, image], axis=0)
else:
tmp_image = np.concatenate([image, base_image], axis=0)
ret.append(tmp_image)
return ret
| import argparse
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import torch
from envs.block_pushing import BlockPushing
from train_sim import make_pairwise_encoder
matplotlib.use("TkAgg")
def pair(base_image, other_images, base_first=True):
| 59 | 64 | 73 | 12 | 47 | dmcinerney/c-swm | scr/envs/block_pushing_model_show.py | Python | pair | pair | 11 | 24 | 11 | 12 | 2c06462ce9f131faeed07cc56be869103df3548f | bigcode/the-stack | train |
8890ad98a1008ecedd8a22b1 | train | function | def plot_all_images(images):
for idx, image in enumerate(images):
plt.subplot(1, len(images), 1 + idx)
plt.imshow(image.transpose((1, 2, 0)))
plt.show()
| def plot_all_images(images):
| for idx, image in enumerate(images):
plt.subplot(1, len(images), 1 + idx)
plt.imshow(image.transpose((1, 2, 0)))
plt.show()
| tmp_image = np.concatenate([image, base_image], axis=0)
ret.append(tmp_image)
return ret
def stack_to_pt(images, device):
images = np.stack(images, axis=0)
return torch.tensor(images, dtype=torch.float32, device=device)
def plot_all_images(images):
| 64 | 64 | 47 | 6 | 58 | dmcinerney/c-swm | scr/envs/block_pushing_model_show.py | Python | plot_all_images | plot_all_images | 33 | 40 | 33 | 34 | b422a4d0d7213e20bb4612eff83b20ab2144c8bc | bigcode/the-stack | train |
176f228040e5c2f72d253f51 | train | function | def _zig_cc_toolchain_config_impl(ctx):
default_compiler_flags = feature(
name = "default_compiler_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = [
flag_group(
... | def _zig_cc_toolchain_config_impl(ctx):
| default_compiler_flags = feature(
name = "default_compiler_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = [
flag_group(
flags = [
... | _defs/cc:action_names.bzl", "ACTION_NAMES")
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"tool",
"tool_path",
"feature_set",
)
all_link_actions = [
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTIO... | 187 | 187 | 624 | 10 | 177 | pompon0/bazel-zig-cc | toolchain/zig_toolchain.bzl | Python | _zig_cc_toolchain_config_impl | _zig_cc_toolchain_config_impl | 32 | 132 | 32 | 32 | 6632cc6c2a0e1ae53b24938940e04c4ad6f6509b | bigcode/the-stack | train |
404f96e9a468dee7b62b627c | train | function | def graph(file):
Data = pd.read_table(file, sep='deliminator', engine='python', header=None)
Data.dropna(inplace = True)
Data = Data[0].str.split("\t", expand = True)
# This means we cut the data when the time is zero. To look at full data,
# use d_row = list(D[0]).index('#') + 1
d_row = list(... | def graph(file):
| Data = pd.read_table(file, sep='deliminator', engine='python', header=None)
Data.dropna(inplace = True)
Data = Data[0].str.split("\t", expand = True)
# This means we cut the data when the time is zero. To look at full data,
# use d_row = list(D[0]).index('#') + 1
d_row = list(Data[1]).index('0... | = 'C:/Users/Mels/Code/Labdata/Toprocess' #change this to file directory
# Set equal to 1 to see a graph, 0 to hide it:
flag_charge_discharge = 1
flag_voltage_gap = 0
# Number of cycles you are plotting: #change this to number of files
n_cycles = 9
first_cycle = 1
# Plot file name preamble: #change this to desired ... | 190 | 190 | 636 | 4 | 186 | mglasser16/data-analysis | batteries/Li2o2_Data_Processing.py | Python | graph | graph | 46 | 97 | 46 | 46 | 58c6c2dae497e85dde604f27bca8f095b07cd163 | bigcode/the-stack | train |
21f29e9d1091201c049f72c7 | train | class | @admin.register(ImageUploadModel)
class FaceAdmin(admin.ModelAdmin):
pass
| @admin.register(ImageUploadModel)
class FaceAdmin(admin.ModelAdmin):
| pass
| from django.contrib import admin
from .models import ImageUploadModel
@admin.register(ImageUploadModel)
class FaceAdmin(admin.ModelAdmin):
| 28 | 64 | 17 | 14 | 13 | amamov/face_detection | face/admin.py | Python | FaceAdmin | FaceAdmin | 5 | 7 | 5 | 6 | 56e578c5f415b764a2ef51e4492ed6489cb6c740 | bigcode/the-stack | train |
6840efb578b522062ad599b4 | train | class | class SanityState(object):
ImageNotFound = ImageNotFound
_public_key = '~/.ssh/id_rsa.pub'
_ignored_availability_zones = set(['internal', 'nova'])
_availability_zone = None
__availability_zone = None
_keypair_name = 'qaspankey'
__keypair = {}
_security_group_name = 'qaspansecg-{0}'
... | class SanityState(object):
| ImageNotFound = ImageNotFound
_public_key = '~/.ssh/id_rsa.pub'
_ignored_availability_zones = set(['internal', 'nova'])
_availability_zone = None
__availability_zone = None
_keypair_name = 'qaspankey'
__keypair = {}
_security_group_name = 'qaspansecg-{0}'
__security_group = {}
... | ."),
cfg.BoolOpt('filter-enabled', default=True,
help='Only list hosts with an enabled Nova compute.'),
cfg.BoolOpt('floating', default=True,
help="Don't test using floating networks."),
cfg.IntOpt('build-timeout', default=60,
help="Maximum time to wait for a s... | 256 | 256 | 3,479 | 6 | 249 | CiscoCloud/sdu-test-sanity | sanity/controller.py | Python | SanityState | SanityState | 134 | 639 | 134 | 134 | 9529003bcb9a93ac585e5c4400639a4a03e566bc | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.