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
ea8623ec093a6068164c6a3f
train
class
class FpingTestV21(test.TestCase): controller_cls = fping_v21.FpingController def setUp(self): super(FpingTestV21, self).setUp() self.flags(verbose=True, use_ipv6=False) return_server = fakes.fake_instance_get() return_servers = fakes.fake_instance_get_all_by_filters() s...
class FpingTestV21(test.TestCase):
controller_cls = fping_v21.FpingController def setUp(self): super(FpingTestV21, self).setUp() self.flags(verbose=True, use_ipv6=False) return_server = fakes.fake_instance_get() return_servers = fakes.fake_instance_get_all_by_filters() self.stubs.Set(nova.db, "instance_ge...
Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distrib...
233
234
783
10
223
mmnelemane/nova_stable_juno
nova/tests/unit/api/openstack/compute/test_fping.py
Python
FpingTestV21
FpingTestV21
35
111
35
35
c43dd65b028c16efe5afa3a27dc61d461dea8c7a
bigcode/the-stack
train
49a24fb129995a6bba2b7fbc
train
function
def execute(*cmd, **args): return "".join(["%s is alive" % ip for ip in cmd[1:]])
def execute(*cmd, **args):
return "".join(["%s is alive" % ip for ip in cmd[1:]])
as fping_v21 from nova.api.openstack.compute.legacy_v2.contrib import fping from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes import nova.utils FAKE_UUID = fakes.FAKE_UUID def execute(*cmd, **args):
64
64
28
8
55
mmnelemane/nova_stable_juno
nova/tests/unit/api/openstack/compute/test_fping.py
Python
execute
execute
31
32
31
31
1054388498279cd21e89befdee2affa33258fdf4
bigcode/the-stack
train
3127a704926f11a389a26460
train
class
class ProductImage(models.Model): product = models.ForeignKey( Product, related_name='images', on_delete=models.CASCADE) image = VersatileImageField( upload_to='products', ppoi_field='ppoi', blank=False) ppoi = PPOIField() alt = models.CharField(max_length=128, blank=True) order = mo...
class ProductImage(models.Model):
product = models.ForeignKey( Product, related_name='images', on_delete=models.CASCADE) image = VersatileImageField( upload_to='products', ppoi_field='ppoi', blank=False) ppoi = PPOIField() alt = models.CharField(max_length=128, blank=True) order = models.PositiveIntegerField(editable...
9]{6}|[A-Fa-f0-9]{3})$')]) attribute = models.ForeignKey( ProductAttribute, related_name='values', on_delete=models.CASCADE) class Meta: unique_together = ('name', 'attribute') def __str__(self): return self.name class ProductImage(models.Model):
72
72
243
6
65
LivinSam/saleor
saleor/product/models.py
Python
ProductImage
ProductImage
342
369
342
342
b4f5269cc5573a5d4a0e49c5fe456a65d3e26ba1
bigcode/the-stack
train
52f399114befe6b22087018d
train
class
class VariantImage(models.Model): variant = models.ForeignKey( 'ProductVariant', related_name='variant_images', on_delete=models.CASCADE) image = models.ForeignKey( ProductImage, related_name='variant_images', on_delete=models.CASCADE)
class VariantImage(models.Model):
variant = models.ForeignKey( 'ProductVariant', related_name='variant_images', on_delete=models.CASCADE) image = models.ForeignKey( ProductImage, related_name='variant_images', on_delete=models.CASCADE)
().save(*args, **kwargs) def delete(self, *args, **kwargs): qs = self.get_ordering_queryset() qs.filter(order__gt=self.order).update(order=F('order') - 1) super().delete(*args, **kwargs) class VariantImage(models.Model):
64
64
53
6
58
LivinSam/saleor
saleor/product/models.py
Python
VariantImage
VariantImage
372
378
372
372
16693ed5d5c4c6e0ae19f3017946cdf6f87c8d31
bigcode/the-stack
train
3c8aeb1ad6286e1184d0bc39
train
class
class ProductAttribute(models.Model): slug = models.SlugField(max_length=50, unique=True) name = models.CharField(max_length=100) class Meta: ordering = ('slug', ) def __str__(self): return self.name def get_formfield_name(self): return slugify('attribute-%s' % self.slug, ...
class ProductAttribute(models.Model):
slug = models.SlugField(max_length=50, unique=True) name = models.CharField(max_length=100) class Meta: ordering = ('slug', ) def __str__(self): return self.name def get_formfield_name(self): return slugify('attribute-%s' % self.slug, allow_unicode=True) def has_value...
unique_together = ('variant', 'location') def __str__(self): return '%s - %s' % (self.variant.name, self.location) @property def quantity_available(self): return max(self.quantity - self.quantity_allocated, 0) class ProductAttribute(models.Model):
64
64
92
6
58
LivinSam/saleor
saleor/product/models.py
Python
ProductAttribute
ProductAttribute
309
323
309
309
23f28d80dd2c32aceaea349eb078258f0118b568
bigcode/the-stack
train
f51b14e5525eb32a0392a04c
train
class
class StockLocation(models.Model): name = models.CharField(max_length=100) class Meta: permissions = ( ('view_stock_location', pgettext_lazy('Permission description', 'Can view stock location')), ('edit_stock_location', pgette...
class StockLocation(models.Model):
name = models.CharField(max_length=100) class Meta: permissions = ( ('view_stock_location', pgettext_lazy('Permission description', 'Can view stock location')), ('edit_stock_location', pgettext_lazy('Permission description', ...
stock = sorted( stock, key=(lambda s: s.cost_price or zero_price), reverse=False) if stock: return stock[0] def get_cost_price(self): stock = self.select_stockrecord() if stock: return stock.cost_price class StockLocation(models.Model):
64
64
80
6
57
LivinSam/saleor
saleor/product/models.py
Python
StockLocation
StockLocation
268
281
268
268
2020659306a80f78d201ecd46fa6caf2b1304554
bigcode/the-stack
train
33ed3d0b1b74e460d83e1cf0
train
class
class ProductQuerySet(models.QuerySet): def available_products(self): today = datetime.date.today() return self.filter( Q(available_on__lte=today) | Q(available_on__isnull=True), Q(is_published=True))
class ProductQuerySet(models.QuerySet):
def available_products(self): today = datetime.date.today() return self.filter( Q(available_on__lte=today) | Q(available_on__isnull=True), Q(is_published=True))
self): return self.name def __repr__(self): class_ = type(self) return '<%s.%s(pk=%r, name=%r)>' % ( class_.__module__, class_.__name__, self.pk, self.name) class ProductQuerySet(models.QuerySet):
64
64
53
8
56
LivinSam/saleor
saleor/product/models.py
Python
ProductQuerySet
ProductQuerySet
82
87
82
82
cdb92638a17a4a0ff201db884cb7b60d12401616
bigcode/the-stack
train
7ae3f153b2fa5201bce2560b
train
class
class ProductVariant(models.Model, Item): sku = models.CharField(max_length=32, unique=True) name = models.CharField(max_length=100, blank=True) price_override = PriceField( currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2, blank=True, null=True) product = models.Forei...
class ProductVariant(models.Model, Item):
sku = models.CharField(max_length=32, unique=True) name = models.CharField(max_length=100, blank=True) price_override = PriceField( currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2, blank=True, null=True) product = models.ForeignKey( Product, related_name='vari...
first_image = self.images.first() return first_image.image if first_image else None def get_attribute(self, pk): return self.attributes.get(smart_text(pk)) def set_attribute(self, pk, value_pk): self.attributes[smart_text(pk)] = smart_text(value_pk) def get_price_range(sel...
207
207
690
8
199
LivinSam/saleor
saleor/product/models.py
Python
ProductVariant
ProductVariant
175
265
175
175
588c27403365f42495b5b89d43ed3ee444cce24e
bigcode/the-stack
train
8a045db27387b734584e8fdc
train
class
class Stock(models.Model): variant = models.ForeignKey( ProductVariant, related_name='stock', on_delete=models.CASCADE) location = models.ForeignKey( StockLocation, null=True, on_delete=models.CASCADE) quantity = models.IntegerField( validators=[MinValueValidator(0)], default=Decimal...
class Stock(models.Model):
variant = models.ForeignKey( ProductVariant, related_name='stock', on_delete=models.CASCADE) location = models.ForeignKey( StockLocation, null=True, on_delete=models.CASCADE) quantity = models.IntegerField( validators=[MinValueValidator(0)], default=Decimal(1)) quantity_allocated...
permissions = ( ('view_stock_location', pgettext_lazy('Permission description', 'Can view stock location')), ('edit_stock_location', pgettext_lazy('Permission description', 'Can edit stock location'))) d...
64
64
192
5
58
LivinSam/saleor
saleor/product/models.py
Python
Stock
Stock
284
306
284
284
52231ef64fb2c91462e0ecb9ea5e5d0192963e0a
bigcode/the-stack
train
f6812593b5f8ce520ff4ae79
train
class
class Product(models.Model, ItemRange): product_type = models.ForeignKey( ProductType, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=128) description = models.TextField() category = models.ForeignKey(Category, related_name='products') price = PriceFiel...
class Product(models.Model, ItemRange):
product_type = models.ForeignKey( ProductType, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=128) description = models.TextField() category = models.ForeignKey(Category, related_name='products') price = PriceField( currency=settings.DEFAULT_CUR...
=True) product_attributes = models.ManyToManyField( 'ProductAttribute', related_name='product_types', blank=True) variant_attributes = models.ManyToManyField( 'ProductAttribute', related_name='product_variant_types', blank=True) is_shipping_required = models.BooleanField(default=False) ...
195
195
651
8
187
LivinSam/saleor
saleor/product/models.py
Python
Product
Product
90
172
90
90
3db7ed1cbeb2a6f3ffeb004c7e64b372b4858c49
bigcode/the-stack
train
c5e8286d4eecf4f1d8e2360f
train
class
class ProductType(models.Model): name = models.CharField(max_length=128) has_variants = models.BooleanField(default=True) product_attributes = models.ManyToManyField( 'ProductAttribute', related_name='product_types', blank=True) variant_attributes = models.ManyToManyField( 'ProductAttrib...
class ProductType(models.Model):
name = models.CharField(max_length=128) has_variants = models.BooleanField(default=True) product_attributes = models.ManyToManyField( 'ProductAttribute', related_name='product_types', blank=True) variant_attributes = models.ManyToManyField( 'ProductAttribute', related_name='product_varia...
(self, ancestors=None): if not self.parent_id: return self.slug if not ancestors: ancestors = self.get_ancestors() nodes = [node for node in ancestors] + [self] return '/'.join([node.slug for node in nodes]) class ProductType(models.Model):
64
64
160
6
58
LivinSam/saleor
saleor/product/models.py
Python
ProductType
ProductType
61
79
61
61
96b741dd0534a57a9adec674f4a37a5d85e143c5
bigcode/the-stack
train
a338bdc52f91d2f4681808fe
train
class
class AttributeChoiceValue(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() color = models.CharField( max_length=7, blank=True, validators=[RegexValidator('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')]) attribute = models.ForeignKey( ProductAttribute, rela...
class AttributeChoiceValue(models.Model):
name = models.CharField(max_length=100) slug = models.SlugField() color = models.CharField( max_length=7, blank=True, validators=[RegexValidator('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')]) attribute = models.ForeignKey( ProductAttribute, related_name='values', on_delete=models.CASCAD...
: ordering = ('slug', ) def __str__(self): return self.name def get_formfield_name(self): return slugify('attribute-%s' % self.slug, allow_unicode=True) def has_values(self): return self.values.exists() class AttributeChoiceValue(models.Model):
64
64
123
7
57
LivinSam/saleor
saleor/product/models.py
Python
AttributeChoiceValue
AttributeChoiceValue
326
339
326
326
53b7d98adb5ae095a2515f3bbe6496747f335679
bigcode/the-stack
train
86686c06c63e539a3d8f7e3e
train
class
class Category(MPTTModel): name = models.CharField(max_length=128) slug = models.SlugField(max_length=50) description = models.TextField(blank=True) parent = models.ForeignKey( 'self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) objects = models.Manager...
class Category(MPTTModel):
name = models.CharField(max_length=128) slug = models.SlugField(max_length=50) description = models.TextField(blank=True) parent = models.ForeignKey( 'self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) objects = models.Manager() tree = TreeManager()...
from prices import PriceRange from satchless.item import InsufficientStock, Item, ItemRange from text_unidecode import unidecode from versatileimagefield.fields import PPOIField, VersatileImageField from ..discount.utils import calculate_discounted_price from .utils import get_attributes_display_map class Category(MP...
73
73
245
7
65
LivinSam/saleor
saleor/product/models.py
Python
Category
Category
25
58
25
25
38b65eb24f226105c81874310b4a6909cd284507
bigcode/the-stack
train
27ecfb35a63094256441fce6
train
class
class SecurityIncidenceFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = SecurityIncidence fields = "__all__"
class SecurityIncidenceFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = SecurityIncidence fields = "__all__"
Filter() class Meta: model = FacilityDevice fields = "__all__" class FacilityDeviceRequestFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilityDeviceRequest fields = "__all__" class SecurityIncidenceFilter(CommonFieldsFilterset):
64
64
35
10
54
savannahghi/mle
fahari/ops/filters.py
Python
SecurityIncidenceFilter
SecurityIncidenceFilter
174
181
174
175
94f4e11ddb8f0442ef74f538dc40a30131c3f4c0
bigcode/the-stack
train
d66e84f0e2a29e998821cdba
train
class
class FacilitySystemTicketFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilitySystemTicket fields = "__all__"
class FacilitySystemTicketFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = FacilitySystemTicket fields = "__all__"
, WeeklyProgramUpdate, WeeklyProgramUpdateComment, ) class FacilitySystemFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilitySystem exclude = ( "attachment", "trainees", ) class FacilitySystemTicketFilter(CommonF...
64
64
35
10
54
savannahghi/mle
fahari/ops/filters.py
Python
FacilitySystemTicketFilter
FacilitySystemTicketFilter
37
44
37
38
7e0515557dd2c8d356d50802a34c230a80ac6d79
bigcode/the-stack
train
2b678b7d91232f38d4d2f3f2
train
class
class CommodityFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = Commodity fields = ( "name", "code", "description", )
class CommodityFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = Commodity fields = ( "name", "code", "description", )
ProgramUpdate exclude = ( "attachment", "assigned_persons", ) class WeeklyProgramUpdateCommentsFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = WeeklyProgramUpdateComment fields = "__all__" class CommodityFilter(Commo...
64
64
42
8
56
savannahghi/mle
fahari/ops/filters.py
Python
CommodityFilter
CommodityFilter
110
121
110
111
01e29a7c2f3b11f032f2f4cdcb1f781ae7d9d4d8
bigcode/the-stack
train
833e6b45ac07fcf368336704
train
class
class FacilityDeviceFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilityDevice fields = "__all__"
class FacilityDeviceFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = FacilityDevice fields = "__all__"
() class Meta: model = UoMCategory fields = "__all__" class FacilityNetworkStatusFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilityNetworkStatus fields = "__all__" class FacilityDeviceFilter(CommonFieldsFilterset):
64
64
33
9
55
savannahghi/mle
fahari/ops/filters.py
Python
FacilityDeviceFilter
FacilityDeviceFilter
154
161
154
155
0b9bdf8c58d544ab2fb52446d159517ad0b508f0
bigcode/the-stack
train
8342dd4f05251fdd6dca8ff8
train
class
class FacilityDeviceRequestFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilityDeviceRequest fields = "__all__"
class FacilityDeviceRequestFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = FacilityDeviceRequest fields = "__all__"
.SearchFilter() class Meta: model = FacilityNetworkStatus fields = "__all__" class FacilityDeviceFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilityDevice fields = "__all__" class FacilityDeviceRequestFilter(CommonFieldsFilterset...
64
64
35
10
54
savannahghi/mle
fahari/ops/filters.py
Python
FacilityDeviceRequestFilter
FacilityDeviceRequestFilter
164
171
164
165
96670fdfe6a56321cfb2c47fdcc007987059320b
bigcode/the-stack
train
98751b603cf8be627f5a71ea
train
class
class WeeklyProgramUpdateCommentsFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = WeeklyProgramUpdateComment fields = "__all__"
class WeeklyProgramUpdateCommentsFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = WeeklyProgramUpdateComment fields = "__all__"
Sheet fields = "__all__" class WeeklyProgramUpdateFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = WeeklyProgramUpdate exclude = ( "attachment", "assigned_persons", ) class WeeklyProgramUpdateCommentsFilter(CommonFiel...
64
64
37
11
53
savannahghi/mle
fahari/ops/filters.py
Python
WeeklyProgramUpdateCommentsFilter
WeeklyProgramUpdateCommentsFilter
100
107
100
101
e06fa1cca51a325230c2713efa934c31349669d2
bigcode/the-stack
train
83b86e87da21347869c74279
train
class
class FacilitySystemFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilitySystem exclude = ( "attachment", "trainees", )
class FacilitySystemFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = FacilitySystem exclude = ( "attachment", "trainees", )
FacilityDeviceRequest, FacilityNetworkStatus, FacilitySystem, FacilitySystemTicket, SecurityIncidence, StockReceiptVerification, TimeSheet, UoM, UoMCategory, WeeklyProgramUpdate, WeeklyProgramUpdateComment, ) class FacilitySystemFilter(CommonFieldsFilterset):
64
64
41
9
55
savannahghi/mle
fahari/ops/filters.py
Python
FacilitySystemFilter
FacilitySystemFilter
24
34
24
25
6d1d22b5acb4fd02a34db69ded71d3d36f0872e2
bigcode/the-stack
train
d329c952cdd7ca715ad66c6e
train
class
class StockReceiptVerificationFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = StockReceiptVerification exclude = ("delivery_note_image",)
class StockReceiptVerificationFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = StockReceiptVerification exclude = ("delivery_note_image",)
= FacilitySystem exclude = ( "attachment", "trainees", ) class FacilitySystemTicketFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilitySystemTicket fields = "__all__" class StockReceiptVerificationFilter(CommonF...
64
64
37
10
54
savannahghi/mle
fahari/ops/filters.py
Python
StockReceiptVerificationFilter
StockReceiptVerificationFilter
47
54
47
48
82b1cf7d661d4ae56b2e4a41480d81cd90839de9
bigcode/the-stack
train
44fe41063404303612f75817
train
class
class ActivityLogFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = ActivityLog fields = "__all__"
class ActivityLogFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = ActivityLog fields = "__all__"
class Meta: model = FacilitySystemTicket fields = "__all__" class StockReceiptVerificationFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = StockReceiptVerification exclude = ("delivery_note_image",) class ActivityLogFilter(CommonFieldsF...
64
64
33
9
55
savannahghi/mle
fahari/ops/filters.py
Python
ActivityLogFilter
ActivityLogFilter
57
64
57
58
cf4fd74a825a46cb230996314db26a277de95499
bigcode/the-stack
train
d9eb8afeaa2093663ef73328
train
class
class FacilityNetworkStatusFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = FacilityNetworkStatus fields = "__all__"
class FacilityNetworkStatusFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = FacilityNetworkStatus fields = "__all__"
class Meta: model = UoM fields = "__all__" class UoMCategoryFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = UoMCategory fields = "__all__" class FacilityNetworkStatusFilter(CommonFieldsFilterset):
64
64
35
10
54
savannahghi/mle
fahari/ops/filters.py
Python
FacilityNetworkStatusFilter
FacilityNetworkStatusFilter
144
151
144
145
8d2bd1fde9639aab81a1a736a9eaa1db352284bf
bigcode/the-stack
train
2a37028088ee00fe97d2f273
train
class
class UoMFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = UoM fields = "__all__"
class UoMFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = UoM fields = "__all__"
WeeklyProgramUpdateComment fields = "__all__" class CommodityFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = Commodity fields = ( "name", "code", "description", ) class UoMFilter(CommonFieldsFilterset): ...
64
64
35
10
54
savannahghi/mle
fahari/ops/filters.py
Python
UoMFilter
UoMFilter
124
131
124
125
27a227c06db4049611cb3a3ecdcd22ecaaf1586c
bigcode/the-stack
train
81d0b5f493d08d494ce3b885
train
class
class DailyUpdateFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = DailyUpdate fields = "__all__"
class DailyUpdateFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = DailyUpdate fields = "__all__"
Filter() class Meta: model = StockReceiptVerification exclude = ("delivery_note_image",) class ActivityLogFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = ActivityLog fields = "__all__" class DailyUpdateFilter(CommonFieldsFilterset):
64
64
33
9
55
savannahghi/mle
fahari/ops/filters.py
Python
DailyUpdateFilter
DailyUpdateFilter
67
74
67
68
b967752a5e43391fb71e0a25317078e95886782f
bigcode/the-stack
train
d17abde65c6c6fb8945af810
train
class
class UoMCategoryFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = UoMCategory fields = "__all__"
class UoMCategoryFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = UoMCategory fields = "__all__"
fields = ( "name", "code", "description", ) class UoMFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = UoM fields = "__all__" class UoMCategoryFilter(CommonFieldsFilterset):
64
64
37
11
53
savannahghi/mle
fahari/ops/filters.py
Python
UoMCategoryFilter
UoMCategoryFilter
134
141
134
135
8c91655650ab8f12a93b8ef4ada1209a039c2b49
bigcode/the-stack
train
27ff8805561789171fcebf78
train
class
class WeeklyProgramUpdateFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = WeeklyProgramUpdate exclude = ( "attachment", "assigned_persons", )
class WeeklyProgramUpdateFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = WeeklyProgramUpdate exclude = ( "attachment", "assigned_persons", )
filters.SearchFilter() class Meta: model = DailyUpdate fields = "__all__" class TimeSheetFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = TimeSheet fields = "__all__" class WeeklyProgramUpdateFilter(CommonFieldsFilterset):
64
64
44
10
54
savannahghi/mle
fahari/ops/filters.py
Python
WeeklyProgramUpdateFilter
WeeklyProgramUpdateFilter
87
97
87
88
649c9762709b9cfef0a3ac2eadbc891c51d8abad
bigcode/the-stack
train
b2203151c9434fdd91ae3d86
train
class
class TimeSheetFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = TimeSheet fields = "__all__"
class TimeSheetFilter(CommonFieldsFilterset):
search = filters.SearchFilter() class Meta: model = TimeSheet fields = "__all__"
= filters.SearchFilter() class Meta: model = ActivityLog fields = "__all__" class DailyUpdateFilter(CommonFieldsFilterset): search = filters.SearchFilter() class Meta: model = DailyUpdate fields = "__all__" class TimeSheetFilter(CommonFieldsFilterset):
64
64
33
9
55
savannahghi/mle
fahari/ops/filters.py
Python
TimeSheetFilter
TimeSheetFilter
77
84
77
78
7dc1f47732bf01f2de31269150a296fb6bb62acf
bigcode/the-stack
train
565a43f6a2713fe7903a1087
train
class
class GraphData(object): """ GraphData Provides: Methods: o __init__(self, id=None, data=None, name=None, style='bar', color=colors.lightgreen, altcolor=colors.darkseagreen) Called on instantiation o set_data(self, data) Load the object with data...
class GraphData(object):
""" GraphData Provides: Methods: o __init__(self, id=None, data=None, name=None, style='bar', color=colors.lightgreen, altcolor=colors.darkseagreen) Called on instantiation o set_data(self, data) Load the object with data to be plotted o...
# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. # Revisions copyright 2008-2009 by Peter Cock. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. # # Contact: Leighton Pritchard,...
236
256
1,769
5
230
lennax/biopython
Bio/Graphics/GenomeDiagram/_Graph.py
Python
GraphData
GraphData
38
257
38
38
a8f25e3d938f57dfe45e8c74feaf735e27614fee
bigcode/the-stack
train
c1203212decc6e674d4586e2
train
class
class EBMUtils: @staticmethod def weighted_std(a, axis, weights): average = np.average(a, axis , weights) variance = np.average((a - average)**2, axis , weights) return np.sqrt(variance) @staticmethod def merge_models(models): """ Merging multiple EBM mod...
class EBMUtils: @staticmethod
def weighted_std(a, axis, weights): average = np.average(a, axis , weights) variance = np.average((a - average)**2, axis , weights) return np.sqrt(variance) @staticmethod def merge_models(models): """ Merging multiple EBM models trained on the same dataset. ...
# Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license # TODO: Test EBMUtils from math import ceil, isnan from .internal import Native, Booster, InteractionDetector # from scipy.special import expit from sklearn.utils.extmath import softmax from sklearn.model_selection import train_t...
137
256
4,653
10
126
eddy-geek/interpret
python/interpret-core/interpret/glassbox/ebm/utils.py
Python
EBMUtils
EBMUtils
27
558
27
29
ebf49bf3fb80de07bdd92a8983607283a5ba89fa
bigcode/the-stack
train
0ed03469c620ff32385e88c8
train
class
class DPUtils: @staticmethod def calc_classic_noise_multi(total_queries, target_epsilon, delta, sensitivity): variance = (8*total_queries*sensitivity**2 * np.log(np.exp(1) + target_epsilon / delta)) / target_epsilon ** 2 return np.sqrt(variance) @staticmethod def calc_gdp_noise_multi(t...
class DPUtils: @staticmethod
def calc_classic_noise_multi(total_queries, target_epsilon, delta, sensitivity): variance = (8*total_queries*sensitivity**2 * np.log(np.exp(1) + target_epsilon / delta)) / target_epsilon ** 2 return np.sqrt(variance) @staticmethod def calc_gdp_noise_multi(total_queries, target_epsilon, delt...
model_update = booster.get_current_model() else: model_update = booster.get_best_model() return model_update, min_metric, episode_index @staticmethod def get_interactions( iter_feature_groups, model_type, n_classes, features_categorical, ...
256
256
1,292
8
247
eddy-geek/interpret
python/interpret-core/interpret/glassbox/ebm/utils.py
Python
DPUtils
DPUtils
561
680
561
563
a6a7368351250e49093063c79b4f269255ea6b39
bigcode/the-stack
train
0818d3289a1809112e87344d
train
function
def glInitCopyBufferARB(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( EXTENSION_NAME )
def glInitCopyBufferARB():
'''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( EXTENSION_NAME )
()) @_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLintptr,_cs.GLintptr,_cs.GLsizeiptr) def glCopyBufferSubData( readTarget,writeTarget,readOffset,writeOffset,size ):pass def glInitCopyBufferARB():
64
64
37
7
56
frederica07/Dragon_Programming_Process
PyOpenGL-3.0.2/OpenGL/raw/GL/ARB/copy_buffer.py
Python
glInitCopyBufferARB
glInitCopyBufferARB
15
18
15
15
71e77df341e931cdff31fd34b2ea3e8d267f08d3
bigcode/the-stack
train
7549ad6e9b8d6e7959ac78c8
train
function
@_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLintptr,_cs.GLintptr,_cs.GLsizeiptr) def glCopyBufferSubData( readTarget,writeTarget,readOffset,writeOffset,size ):pass
@_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLintptr,_cs.GLintptr,_cs.GLsizeiptr) def glCopyBufferSubData( readTarget,writeTarget,readOffset,writeOffset,size ):
pass
0x8F37""", globals()) @_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLintptr,_cs.GLintptr,_cs.GLsizeiptr) def glCopyBufferSubData( readTarget,writeTarget,readOffset,writeOffset,size ):
64
64
56
54
10
frederica07/Dragon_Programming_Process
PyOpenGL-3.0.2/OpenGL/raw/GL/ARB/copy_buffer.py
Python
glCopyBufferSubData
glCopyBufferSubData
10
12
10
12
1be269aa18f3c601241be3e0e725d80cb4267ffc
bigcode/the-stack
train
4653486da3955711c1538c94
train
function
def _f( function ): return _p.createFunction( function,_p.GL,'GL_ARB_copy_buffer',False)
def _f( function ):
return _p.createFunction( function,_p.GL,'GL_ARB_copy_buffer',False)
'''Autogenerated by get_gl_extensions script, do not edit!''' from OpenGL import platform as _p, constants as _cs, arrays from OpenGL.GL import glget import ctypes EXTENSION_NAME = 'GL_ARB_copy_buffer' def _f( function ):
57
64
25
6
51
frederica07/Dragon_Programming_Process
PyOpenGL-3.0.2/OpenGL/raw/GL/ARB/copy_buffer.py
Python
_f
_f
6
7
6
6
f76ea401606fe41f4fb744fc6bc93228970c23b8
bigcode/the-stack
train
06fd46354a064c390be57e69
train
function
def name_scope_stack_push(name): job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName() sess = session_context.GetDefaultSession() if job_name not in sess.job_name2name_scope_stack: sess.job_name2name_scope_stack[job_name] = [] sess.job_name2name_scope_stack[job_name].append(name)
def name_scope_stack_push(name):
job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName() sess = session_context.GetDefaultSession() if job_name not in sess.job_name2name_scope_stack: sess.job_name2name_scope_stack[job_name] = [] sess.job_name2name_scope_stack[job_name].append(name)
def BuildScope(old_scope, builder): return old_scope.BuildWithNewScopeName(builder, name) sess = session_context.GetDefaultSession() try: with sess.NewCurrentScope(sess.MakeScope(BuildScope)): yield finally: name_scope_stack_pop() def name_scope_stack_push(name):
64
64
76
7
57
xxg1413/oneflow
oneflow/python/experimental/name_scope.py
Python
name_scope_stack_push
name_scope_stack_push
71
76
71
71
f60951ebed181ff647a32bfc68edf4e91bbfae45
bigcode/the-stack
train
296cbc69861434012878fd71
train
function
def GetJobNameScopePrefix(job_name): sess = session_context.GetDefaultSession() if job_name not in sess.job_name2name_scope_stack: return "" if len(sess.job_name2name_scope_stack[job_name]) == 0: return "" return "-".join(sess.job_name2name_scope_stack[job_name]) + "-"
def GetJobNameScopePrefix(job_name):
sess = session_context.GetDefaultSession() if job_name not in sess.job_name2name_scope_stack: return "" if len(sess.job_name2name_scope_stack[job_name]) == 0: return "" return "-".join(sess.job_name2name_scope_stack[job_name]) + "-"
sess = session_context.GetDefaultSession() assert job_name in sess.job_name2name_scope_stack assert len(sess.job_name2name_scope_stack[job_name]) > 0 return sess.job_name2name_scope_stack[job_name].pop() def GetJobNameScopePrefix(job_name):
64
64
74
9
55
xxg1413/oneflow
oneflow/python/experimental/name_scope.py
Python
GetJobNameScopePrefix
GetJobNameScopePrefix
87
93
87
87
5b80c5e5a20e3fa2b202e016b7895ffeaac3f3c8
bigcode/the-stack
train
b10aaf9f3de04229fe3b0a32
train
function
def PrependOpNamePrefixIfNeed(op_conf): if op_conf.HasField("variable_conf"): return if op_conf.HasField("decode_ofrecord_conf"): return if op_conf.HasField("user_conf"): return job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName() op_conf.name = GetJobNameScopePre...
def PrependOpNamePrefixIfNeed(op_conf):
if op_conf.HasField("variable_conf"): return if op_conf.HasField("decode_ofrecord_conf"): return if op_conf.HasField("user_conf"): return job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName() op_conf.name = GetJobNameScopePrefix(job_name) + op_conf.name
not in sess.job_name2name_scope_stack: return "" if len(sess.job_name2name_scope_stack[job_name]) == 0: return "" return "-".join(sess.job_name2name_scope_stack[job_name]) + "-" def PrependOpNamePrefixIfNeed(op_conf):
63
64
87
11
52
xxg1413/oneflow
oneflow/python/experimental/name_scope.py
Python
PrependOpNamePrefixIfNeed
PrependOpNamePrefixIfNeed
96
107
96
96
44dd3bab04c4012605be5512fe66b256172e9a08
bigcode/the-stack
train
e3bf8950eb7102061733365a
train
function
def name_scope_stack_pop(): job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName() sess = session_context.GetDefaultSession() assert job_name in sess.job_name2name_scope_stack assert len(sess.job_name2name_scope_stack[job_name]) > 0 return sess.job_name2name_scope_stack[job_name].pop()
def name_scope_stack_pop():
job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName() sess = session_context.GetDefaultSession() assert job_name in sess.job_name2name_scope_stack assert len(sess.job_name2name_scope_stack[job_name]) > 0 return sess.job_name2name_scope_stack[job_name].pop()
Ctx_GetCurrentJobName() sess = session_context.GetDefaultSession() if job_name not in sess.job_name2name_scope_stack: sess.job_name2name_scope_stack[job_name] = [] sess.job_name2name_scope_stack[job_name].append(name) def name_scope_stack_pop():
64
64
78
6
58
xxg1413/oneflow
oneflow/python/experimental/name_scope.py
Python
name_scope_stack_pop
name_scope_stack_pop
79
84
79
79
9d7e88f7800501bbe830a000949922a5e486ee19
bigcode/the-stack
train
06c27a39ad3bdfb434591086
train
function
@oneflow_export("scope.namespace") @contextmanager def name_scope(name: str) -> None: r"""Create a namespace. All variables within the namespace will have a prefix `[SCOPE NAME]-`. This is for convenience only and has no other effect on the system. Usage:: with oneflow.scope.namespace("scope1"): ...
@oneflow_export("scope.namespace") @contextmanager def name_scope(name: str) -> None:
r"""Create a namespace. All variables within the namespace will have a prefix `[SCOPE NAME]-`. This is for convenience only and has no other effect on the system. Usage:: with oneflow.scope.namespace("scope1"): ... with oneflow.scope.namespace("scope2"): ... ...
removed in the future, use {} instead.".format( "oneflow.scope.namespace" ), ) print(traceback.format_stack()[-2]) return name_scope(*args, **kwargs) @oneflow_export("scope.namespace") @contextmanager def name_scope(name: str) -> None:
64
64
171
22
42
xxg1413/oneflow
oneflow/python/experimental/name_scope.py
Python
name_scope
name_scope
42
68
42
44
8cf5b99e4f83b3f1323092cbe2c201ada1fbdfdb
bigcode/the-stack
train
bc00ecb3fe8c661302bc7c6d
train
function
@oneflow_export( "name_scope", "experimental.name_scope", "deprecated.variable_scope", ) @oneflow_deprecate() def deprecated_name_scope(*args, **kwargs): print( "WARNING:", "oneflow.name_scope/oneflow.experimental.name_scope/deprecated.variable_scope", "will be removed in the future, use...
@oneflow_export( "name_scope", "experimental.name_scope", "deprecated.variable_scope", ) @oneflow_deprecate() def deprecated_name_scope(*args, **kwargs):
print( "WARNING:", "oneflow.name_scope/oneflow.experimental.name_scope/deprecated.variable_scope", "will be removed in the future, use {} instead.".format( "oneflow.scope.namespace" ), ) print(traceback.format_stack()[-2]) return name_scope(*args, **kwargs)
_context as session_context from oneflow.python.oneflow_export import oneflow_export, oneflow_deprecate import traceback @oneflow_export( "name_scope", "experimental.name_scope", "deprecated.variable_scope", ) @oneflow_deprecate() def deprecated_name_scope(*args, **kwargs):
64
64
108
38
25
xxg1413/oneflow
oneflow/python/experimental/name_scope.py
Python
deprecated_name_scope
deprecated_name_scope
26
39
26
30
c87f0cdfce4e885b25b931f3f7be2591da6e0a3a
bigcode/the-stack
train
814067070f002ea12dcfcd4f
train
function
@login_required @app.route('/<int:bid_id>/update/bid', methods=["GET","POST"]) def update_bid(bid_id): form = BidForm(request.form) bid = Bids.query.filter_by(bid_id = bid_id).first() min_bid = Tasks.query.filter_by(task_id = bid.task_id).first().min_bid if(request.method == "POST"): if not (for...
@login_required @app.route('/<int:bid_id>/update/bid', methods=["GET","POST"]) def update_bid(bid_id):
form = BidForm(request.form) bid = Bids.query.filter_by(bid_id = bid_id).first() min_bid = Tasks.query.filter_by(task_id = bid.task_id).first().min_bid if(request.method == "POST"): if not (form.validate_on_submit()): flash('Bid info is invalid. Try again') return render_...
db.session.commit() flash('Bid successfully deleted') return redirect(url_for('home')) else: return render_template('pages/placeholder.delete.bid.html') @login_required @app.route('/<int:bid_id>/update/bid', methods=["GET","POST"]) def update_bid(bid_id):
64
64
197
29
35
software-1234/cs2102_project
app.py
Python
update_bid
update_bid
152
167
152
154
a722a30b2df85245986518410a72e55097301934
bigcode/the-stack
train
65f88e4b734fe9915f1f7bf3
train
function
@app.route('/logout') def logout(): logout_user() return redirect(url_for('home'))
@app.route('/logout') def logout():
logout_user() return redirect(url_for('home'))
flash('User successfully registered') return redirect(url_for('login')) return render_template('forms/register.html', form=form) @app.route('/forgot') def forgot(): form = ForgotForm(request.form) return render_template('forms/forgot.html', form=form) @app.route('/logout') def logout():
64
64
20
8
56
software-1234/cs2102_project
app.py
Python
logout
logout
295
298
295
296
55fe0ec63a789bf50c801b917d3de4c7b89839e2
bigcode/the-stack
train
831c0f4011bca6ad1a9d54bb
train
function
@app.route('/register', methods=["GET","POST"]) def register(): form = RegisterForm(request.form) if(request.method == "POST"): if not (form.validate_on_submit()): flash('User info is invalid. Try again') return render_template('forms/register.html', form=form) user = db....
@app.route('/register', methods=["GET","POST"]) def register():
form = RegisterForm(request.form) if(request.method == "POST"): if not (form.validate_on_submit()): flash('User info is invalid. Try again') return render_template('forms/register.html', form=form) user = db.session.query(Users).filter_by(user_id = form.user_id.data).firs...
flash('Password is invalid','error') return redirect(url_for('login')) login_user(registered_user, remember = False) flash('Logged in successfully') return redirect(request.args.get('next') or url_for('home')) @app.route('/register', methods=["GET","POST"]) def register():
63
64
177
14
49
software-1234/cs2102_project
app.py
Python
register
register
272
288
272
273
9be3e829423e822b0f1fb973f8eadb9e81802be7
bigcode/the-stack
train
99562a234033a78789f42951
train
function
@app.route('/') def home(): page = request.args.get('page', 1, type=int) tasks = Tasks.query.filter_by(employee_user_id=None).order_by(Tasks.last_updated.desc()).paginate( page, 20, False ) next_url = None if tasks.has_next: next_url = url_for('home', page=tasks.next_num) prev_ur...
@app.route('/') def home():
page = request.args.get('page', 1, type=int) tasks = Tasks.query.filter_by(employee_user_id=None).order_by(Tasks.last_updated.desc()).paginate( page, 20, False ) next_url = None if tasks.has_next: next_url = url_for('home', page=tasks.next_num) prev_url = None if tasks.has_pr...
): return Users.query.get(user_id) # Automatically tear down SQLAlchemy. ''' @app.teardown_request def shutdown_session(exception=None): db_session.remove() ''' #----------------------------------------------------------------------------# # Controllers. #-----------------------------------------------------...
64
64
167
6
57
software-1234/cs2102_project
app.py
Python
home
home
55
71
55
56
b3722083101eb88eeca2315f9a3a3efcd3d4b2c4
bigcode/the-stack
train
41d60acc8bd61e7e037d81b9
train
function
@app.route('/about') def about(): return render_template('pages/placeholder.about.html')
@app.route('/about') def about():
return render_template('pages/placeholder.about.html')
.items bids = [] for task in tasks: bids.extend(Bids.query.filter_by(task_id=task.task_id).order_by(Bids.status.desc(),Bids.bid_amount.desc()).all()) return render_template('pages/placeholder.home.html', **locals()) @app.route('/about') def about():
64
64
19
8
56
software-1234/cs2102_project
app.py
Python
about
about
73
75
73
74
6e82640c0b54e0cf41455aa3796aae07b41757b5
bigcode/the-stack
train
527bd9085f6d97c01043a81b
train
function
@login_required @app.route('/my_profile') def my_profile(): form = RegisterForm(request.form) profile = Users.query.filter_by(user_id=current_user.get_id()).first() return render_template('pages/placeholder.myprofile.html', **locals())
@login_required @app.route('/my_profile') def my_profile():
form = RegisterForm(request.form) profile = Users.query.filter_by(user_id=current_user.get_id()).first() return render_template('pages/placeholder.myprofile.html', **locals())
[] for task in tasks: bids.extend(Bids.query.filter_by(task_id=task.task_id).order_by(Bids.status.desc(),Bids.bid_amount.desc()).all()) return render_template('pages/placeholder.search.html', **locals()) @login_required @app.route('/my_profile') def my_profile():
64
64
52
13
51
software-1234/cs2102_project
app.py
Python
my_profile
my_profile
245
250
245
247
0f4aadeed93523de03f2b261ae46d5b6ef57cb08
bigcode/the-stack
train
6751a36d165f1306b8b5b7ad
train
function
@app.errorhandler(404) def not_found_error(error): return render_template('errors/404.html'), 404
@app.errorhandler(404) def not_found_error(error):
return render_template('errors/404.html'), 404
logout') def logout(): logout_user() return redirect(url_for('home')) # Error handlers. @app.errorhandler(500) def internal_error(error): #db_session.rollback() return render_template('errors/500.html'), 500 @app.errorhandler(404) def not_found_error(error):
64
64
25
12
51
software-1234/cs2102_project
app.py
Python
not_found_error
not_found_error
308
310
308
309
3746824fcfbe8d88065c2e03bbee4d68cf230e64
bigcode/the-stack
train
66c16723de2eb682a4e198e8
train
function
@login_required @app.route('/add_task', methods=["GET","POST"]) def add_task(): form = AddForm(request.form) if(request.method == "POST"): if not (form.validate_on_submit()): print(form.errors) flash('Task info is invalid. Try again') return render_template('pages/pla...
@login_required @app.route('/add_task', methods=["GET","POST"]) def add_task():
form = AddForm(request.form) if(request.method == "POST"): if not (form.validate_on_submit()): print(form.errors) flash('Task info is invalid. Try again') return render_template('pages/placeholder.add.task.html', form=form) task = Tasks(form.datetime_start.dat...
ids.status.desc(),Bids.bid_amount.desc()).all()) return render_template('pages/placeholder.home.html', **locals()) @app.route('/about') def about(): return render_template('pages/placeholder.about.html') @login_required @app.route('/add_task', methods=["GET","POST"]) def add_task():
64
64
155
19
45
software-1234/cs2102_project
app.py
Python
add_task
add_task
77
91
77
79
94aaa7fe744088f0ae33e9f63aa507f785c358d2
bigcode/the-stack
train
f185e8627a9f122fd405563e
train
function
@app.before_request def before_request(): g.user = current_user
@app.before_request def before_request():
g.user = current_user
= Anonymous @login_manager.user_loader def load_user(user_id): return Users.query.get(user_id) # Automatically tear down SQLAlchemy. ''' @app.teardown_request def shutdown_session(exception=None): db_session.remove() ''' #----------------------------------------------------------------------------# # Contr...
64
64
15
8
56
software-1234/cs2102_project
app.py
Python
before_request
before_request
51
53
51
52
447abb92c07162524b3f2b637048b70fa62f7c3c
bigcode/the-stack
train
9a6953c17cdc4a00b1525319
train
function
@login_required @app.route('/<int:tid>/modify_task', methods=["GET","POST"]) def modify_task(tid): form = AddForm(request.form) task = Tasks.query.filter_by(task_id = tid).first() if(request.method == "POST"): if not (form.validate_on_submit()): flash('Task info is invalid. Try again') ...
@login_required @app.route('/<int:tid>/modify_task', methods=["GET","POST"]) def modify_task(tid):
form = AddForm(request.form) task = Tasks.query.filter_by(task_id = tid).first() if(request.method == "POST"): if not (form.validate_on_submit()): flash('Task info is invalid. Try again') return render_template('pages/placeholder.modify.task.html', form=form, task=task) ...
).delete() db.session.commit() flash('Task successfully deleted') return redirect(url_for('home')) else: return render_template('pages/placeholder.delete.task.html') @login_required @app.route('/<int:tid>/modify_task', methods=["GET","POST"]) def modify_task(tid):
64
64
204
26
38
software-1234/cs2102_project
app.py
Python
modify_task
modify_task
104
118
104
106
b21400ee2ec0f1eb87a8f818454d22c638c9171b
bigcode/the-stack
train
a4d6d2b00c15a058f46f7d61
train
function
@login_required @app.route('/<int:bid_id>/delete/bid', methods=["GET","POST"]) def delete_bid(bid_id): if (request.method == "POST"): Bids.query.filter_by(bid_id = bid_id).delete() db.session.commit() flash('Bid successfully deleted') return redirect(url_for('home')) else: ...
@login_required @app.route('/<int:bid_id>/delete/bid', methods=["GET","POST"]) def delete_bid(bid_id):
if (request.method == "POST"): Bids.query.filter_by(bid_id = bid_id).delete() db.session.commit() flash('Bid successfully deleted') return redirect(url_for('home')) else: return render_template('pages/placeholder.delete.bid.html')
redirect(request.args.get('next') or url_for('home')) else: return render_template('pages/placeholder.add.bid.html', form=form, task=task) @login_required @app.route('/<int:bid_id>/delete/bid', methods=["GET","POST"]) def delete_bid(bid_id):
64
64
88
29
35
software-1234/cs2102_project
app.py
Python
delete_bid
delete_bid
141
150
141
143
85e16a4c4e035294fcba5ed975c962eb2f28752e
bigcode/the-stack
train
b0985cbed550594499bf93f4
train
function
@login_manager.user_loader def load_user(user_id): return Users.query.get(user_id)
@login_manager.user_loader def load_user(user_id):
return Users.query.get(user_id)
, Bids, create_db, add_admin, Anonymous, add_test_data #----------------------------------------------------------------------------# # Login #----------------------------------------------------------------------------# login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' logi...
64
64
19
11
52
software-1234/cs2102_project
app.py
Python
load_user
load_user
36
38
36
37
c24c4aeb7d6e63a736bf2b23398355334b9b779a
bigcode/the-stack
train
b7bb0007d83b900c4a2ddf48
train
function
@login_required @app.route('/<int:bid_id>/pick_bid/bid', methods=["GET","POST"]) def pick_bid(bid_id): if (request.method == "POST"): accepted_bid = Bids.query.filter_by(bid_id = bid_id).first() Bids.query.filter_by(task_id = accepted_bid.task_id).update({'status':'Rejected'}) Bids.query.fil...
@login_required @app.route('/<int:bid_id>/pick_bid/bid', methods=["GET","POST"]) def pick_bid(bid_id):
if (request.method == "POST"): accepted_bid = Bids.query.filter_by(bid_id = bid_id).first() Bids.query.filter_by(task_id = accepted_bid.task_id).update({'status':'Rejected'}) Bids.query.filter_by(bid_id = bid_id).update({'status':'Accepted'}) Tasks.query.filter_by(task_id = accepted_...
') return redirect(request.args.get('next') or url_for('home')) else: return render_template('pages/placeholder.update.bid.html', **locals()) @login_required @app.route('/<int:bid_id>/pick_bid/bid', methods=["GET","POST"]) def pick_bid(bid_id):
64
64
155
30
34
software-1234/cs2102_project
app.py
Python
pick_bid
pick_bid
170
182
170
172
69cff0f347fea68d1a9ea19f7dc00b1da836fb4c
bigcode/the-stack
train
e42ab93b1da86deeeb880f67
train
function
@app.route('/login', methods=["GET","POST"]) def login(): form = LoginForm(request.form) if (request.method == "GET"): return render_template('forms/login.html', form = form) user_id = form.user_id.data password = form.password.data registered_user = Users.query.filter_by(user_id = user_id)...
@app.route('/login', methods=["GET","POST"]) def login():
form = LoginForm(request.form) if (request.method == "GET"): return render_template('forms/login.html', form = form) user_id = form.user_id.data password = form.password.data registered_user = Users.query.filter_by(user_id = user_id).first() if registered_user is None: flash('Us...
@app.route('/my_profile') def my_profile(): form = RegisterForm(request.form) profile = Users.query.filter_by(user_id=current_user.get_id()).first() return render_template('pages/placeholder.myprofile.html', **locals()) @app.route('/login', methods=["GET","POST"]) def login():
64
64
161
14
50
software-1234/cs2102_project
app.py
Python
login
login
252
269
252
253
b7dfbc2bbc0ab711c19c8a8a605d7038f3d81252
bigcode/the-stack
train
7e93abc5dd021e4498b9586b
train
function
@login_required @app.route('/mytasks_employer') def mytasks_employer(): page = request.args.get('page', 1, type=int) tasks = Tasks.query.filter_by(employer_user_id=current_user.get_id()).order_by(Tasks.last_updated.desc()).paginate( page, 20, False ) next_url = None if tasks.has_next: ...
@login_required @app.route('/mytasks_employer') def mytasks_employer():
page = request.args.get('page', 1, type=int) tasks = Tasks.query.filter_by(employer_user_id=current_user.get_id()).order_by(Tasks.last_updated.desc()).paginate( page, 20, False ) next_url = None if tasks.has_next: next_url = url_for('mytasks_employer', page=tasks.next_num) prev_u...
).update({'employee_user_id':accepted_bid.user_id}) db.session.commit() flash('Bid successfully picked!') return redirect(url_for('home')) else: return render_template('pages/placeholder.pick.bid.html') @login_required @app.route('/mytasks_employer') def mytasks_employer():
64
64
192
17
47
software-1234/cs2102_project
app.py
Python
mytasks_employer
mytasks_employer
184
201
184
186
cf1d1779de9798d5821479954ac5daf76c9163ce
bigcode/the-stack
train
d31c591e6a40727bd7d7f8df
train
function
@login_required @app.route('/<int:tid>/add_bid', methods=["GET","POST"]) def add_bid(tid): form = BidForm(request.form) task = Tasks.query.filter_by(task_id = tid).first() if(request.method == "POST"): if not (form.validate_on_submit()): flash('Bid info is invalid. Try again') ...
@login_required @app.route('/<int:tid>/add_bid', methods=["GET","POST"]) def add_bid(tid):
form = BidForm(request.form) task = Tasks.query.filter_by(task_id = tid).first() if(request.method == "POST"): if not (form.validate_on_submit()): flash('Bid info is invalid. Try again') return render_template('pages/placeholder.add.bid.html', form=form, task=task) # ...
.session.commit() flash('A task successfully modified') return redirect(request.args.get('next') or url_for('home')) else: return render_template('pages/placeholder.modify.task.html', form=form, task=task) @login_required @app.route('/<int:tid>/add_bid', methods=["GET","POST"]) def add_bid(t...
74
74
247
26
48
software-1234/cs2102_project
app.py
Python
add_bid
add_bid
120
139
120
122
635f13651d5fbbfca32215f12f8225bbc5d88d65
bigcode/the-stack
train
bba1302a9ae98d5ba05dc2f3
train
function
@login_required @app.route('/<int:tid>/delete_task', methods=["GET","POST"]) def delete_task(tid): if (request.method == "POST"): Tasks.query.filter_by(task_id = tid).delete() db.session.commit() flash('Task successfully deleted') return redirect(url_for('home')) else: re...
@login_required @app.route('/<int:tid>/delete_task', methods=["GET","POST"]) def delete_task(tid):
if (request.method == "POST"): Tasks.query.filter_by(task_id = tid).delete() db.session.commit() flash('Task successfully deleted') return redirect(url_for('home')) else: return render_template('pages/placeholder.delete.task.html')
flash('A task successfully added') return redirect(request.args.get('next') or url_for('home')) return render_template('pages/placeholder.add.task.html', form=form) @login_required @app.route('/<int:tid>/delete_task', methods=["GET","POST"]) def delete_task(tid):
64
64
82
26
38
software-1234/cs2102_project
app.py
Python
delete_task
delete_task
93
102
93
95
823acade9128ecf659a3a848d5f1a7f826d94af7
bigcode/the-stack
train
e5dc84b114cae741b6aa9a11
train
function
@app.route('/forgot') def forgot(): form = ForgotForm(request.form) return render_template('forms/forgot.html', form=form)
@app.route('/forgot') def forgot():
form = ForgotForm(request.form) return render_template('forms/forgot.html', form=form)
.password_hash.data, form.address.data, form.contact_number.data, form.display_name.data) db.session.add(user) db.session.commit() flash('User successfully registered') return redirect(url_for('login')) return render_template('forms/register.html', form=form) @app.route('/forgot') de...
64
64
29
8
56
software-1234/cs2102_project
app.py
Python
forgot
forgot
290
293
290
291
6b67011bb1a03ec68a1ceda4ca839f6696f0cb9d
bigcode/the-stack
train
10e4651adfaeb80f24b097bd
train
function
@app.errorhandler(500) def internal_error(error): #db_session.rollback() return render_template('errors/500.html'), 500
@app.errorhandler(500) def internal_error(error): #db_session.rollback()
return render_template('errors/500.html'), 500
(): form = ForgotForm(request.form) return render_template('forms/forgot.html', form=form) @app.route('/logout') def logout(): logout_user() return redirect(url_for('home')) # Error handlers. @app.errorhandler(500) def internal_error(error): #db_session.rollback()
64
64
30
17
47
software-1234/cs2102_project
app.py
Python
internal_error
internal_error
302
305
302
304
a3c14b0c80a37e2475406090836d38b903c453d4
bigcode/the-stack
train
e41081e19c632bc5b741c171
train
function
@login_required @app.route('/mytasks_employee') def mytasks_employee(): page = request.args.get('page', 1, type=int) tasks = Tasks.query.order_by(Tasks.last_updated.desc()).paginate( page, 20, False ) next_url = None if tasks.has_next: next_url = url_for('mytasks_employee', page=task...
@login_required @app.route('/mytasks_employee') def mytasks_employee():
page = request.args.get('page', 1, type=int) tasks = Tasks.query.order_by(Tasks.last_updated.desc()).paginate( page, 20, False ) next_url = None if tasks.has_next: next_url = url_for('mytasks_employee', page=tasks.next_num) prev_url = None if tasks.has_prev: prev_url ...
: bids.extend(Bids.query.filter_by(task_id=task.task_id).order_by(Bids.status.desc(),Bids.bid_amount.desc()).all()) return render_template('pages/placeholder.mytasks.employer.html', **locals()) @login_required @app.route('/mytasks_employee') def mytasks_employee():
64
64
176
15
49
software-1234/cs2102_project
app.py
Python
mytasks_employee
mytasks_employee
203
220
203
205
3617333c72e3445d4c37956903ff70df3b616050
bigcode/the-stack
train
0fb448ba0427320f8e3fe221
train
function
@login_required @app.route('/search', methods=["POST"]) def search(): if(request.method == "POST"): search = request.form['search'] page = request.args.get('page', 1, type=int) tasks = Tasks.query.filter_by(employee_user_id=None).filter(Tasks.title.ilike('%'+search+'%') | Tasks.description.i...
@login_required @app.route('/search', methods=["POST"]) def search():
if(request.method == "POST"): search = request.form['search'] page = request.args.get('page', 1, type=int) tasks = Tasks.query.filter_by(employee_user_id=None).filter(Tasks.title.ilike('%'+search+'%') | Tasks.description.ilike('%'+search+'%') | Tasks.address.ilike('%'+search+...
bids = [] for task in tasks: bids.extend(Bids.query.filter_by(task_id=task.task_id).order_by(Bids.status.desc(),Bids.bid_amount.desc()).all()) return render_template('pages/placeholder.mytasks.employee.html', **locals()) @login_required @app.route('/search', methods=["POST"]) def search():
72
72
241
15
57
software-1234/cs2102_project
app.py
Python
search
search
222
242
222
224
e517f2af0e35acbcf459e136b6f37d0351cf2e78
bigcode/the-stack
train
c0183290ee63d6441343fc0c
train
class
class PuddleWorld(gym.Env): metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 15 } def __init__(self, goal_x=10, goal_y=10, puddle_means=[(1.0, 10.0), (1.0, 8.0), (6.0,6.0),(6.0,4.0)], puddle_var=[(.8, 1.e-5, 1.e-5, .8), (.8, 1.e-5, 1.e-5, .8)...
class PuddleWorld(gym.Env):
metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 15 } def __init__(self, goal_x=10, goal_y=10, puddle_means=[(1.0, 10.0), (1.0, 8.0), (6.0,6.0),(6.0,4.0)], puddle_var=[(.8, 1.e-5, 1.e-5, .8), (.8, 1.e-5, 1.e-5, .8), (.8, 1.e-5, 1.e-5, .8),(.8...
import gym import numpy as np from gym import spaces import math """ The Puddleworld environment Info ---- - State space: 2D Box (x,y) - Action space: Discrete (UP,DOWN,RIGHT,LEFT) - Parameters: goal position x and y, puddle centers, puddle variances References ---------- - Andrea Tirinzoni, Andrea Sessa,...
155
256
1,149
8
147
albertometelli/pfqi
trlib/environments/puddleworld.py
Python
PuddleWorld
PuddleWorld
25
148
25
25
4b982015ab6816e77f4fe5d2728c93eb83cd21e9
bigcode/the-stack
train
0c61a5602f8435228e4593d1
train
function
def print_table(table, name=None, float_format=None, formatters=None, header_rows=None): """ Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters -------...
def print_table(table, name=None, float_format=None, formatters=None, header_rows=None):
""" Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters ---------- table : pandas.Series or pandas.DataFrame Table to pretty-print. name : str, optional Table name to display in upper left cor...
(df) raw_positions.append(df) if not raw_positions: raise ValueError("The backtest does not have any positions.") positions = pd.concat(raw_positions) positions = pos.extract_pos(positions, backtest.ending_cash) transactions = txn.make_transaction_frame(backtest.transactions) if tran...
117
117
393
24
92
lingmicha/pyfolio
pyfolio/utils.py
Python
print_table
print_table
170
219
170
174
9ddcbe8e117d3b2491cb36f969fdc74599f8891d
bigcode/the-stack
train
af4f5a8ba2445a96f6808f74
train
function
def estimate_intraday(returns, positions, transactions, EOD_hour=23): """ Intraday strategies will often not hold positions at the day end. This attempts to find the point in the day that best represents the activity of the strategy on that day, and effectively resamples the end-of-day positions wit...
def estimate_intraday(returns, positions, transactions, EOD_hour=23):
""" Intraday strategies will often not hold positions at the day end. This attempts to find the point in the day that best represents the activity of the strategy on that day, and effectively resamples the end-of-day positions with the positions at this point of day. The point of day is found by...
- See full explanation in create_full_tear_sheet. Returns ------- pd.DataFrame Daily net position values, adjusted for intraday movement. """ if estimate == 'infer': if positions is not None and transactions is not None: if detect_intraday(positions, transactio...
193
193
645
17
175
lingmicha/pyfolio
pyfolio/utils.py
Python
estimate_intraday
estimate_intraday
315
381
315
315
880ae931bce2939ea376105788ac893a4aa01f77
bigcode/the-stack
train
8010beb3d68ff68e6769a397
train
function
def vectorize(func): """ Decorator so that functions can be written to work on Series but may still be called with DataFrames. """ def wrapper(df, *args, **kwargs): if df.ndim == 1: return func(df, *args, **kwargs) elif df.ndim == 2: return df.apply(func, *ar...
def vectorize(func):
""" Decorator so that functions can be written to work on Series but may still be called with DataFrames. """ def wrapper(df, *args, **kwargs): if df.ndim == 1: return func(df, *args, **kwargs) elif df.ndim == 2: return df.apply(func, *args, **kwargs) re...
within the tear sheet. This function should only be applied directly before displaying. """ try: import zipline.assets except ImportError: return asset if isinstance(asset, zipline.assets.Asset): return asset.symbol else: return asset def vectorize(func):
64
64
89
5
58
lingmicha/pyfolio
pyfolio/utils.py
Python
vectorize
vectorize
99
111
99
99
5987205709158cc47f1297d8f20c13d4f1a09009
bigcode/the-stack
train
40f78121066e630d2342af78
train
function
def standardize_data(x): """ Standardize an array with mean and standard deviation. Parameters ---------- x : np.array Array to standardize. Returns ------- np.array Standardized array. """ return (x - np.mean(x)) / np.std(x)
def standardize_data(x):
""" Standardize an array with mean and standard deviation. Parameters ---------- x : np.array Array to standardize. Returns ------- np.array Standardized array. """ return (x - np.mean(x)) / np.std(x)
;"><th>%s</th>' + '<td colspan=%d>%s</td></tr>') % (name, n_cols, value) # Inject the new HTML html = html.replace('<thead>', '<thead>' + rows) display(HTML(html)) def standardize_data(x):
64
64
66
6
58
lingmicha/pyfolio
pyfolio/utils.py
Python
standardize_data
standardize_data
222
237
222
222
2d9dbfba8330e0b1f0b0809d0127baf6e0145514
bigcode/the-stack
train
5e56ccb12569170507d23273
train
function
def one_dec_places(x, pos): """ Adds 1/10th decimal to plot ticks. """ return '%.1f' % x
def one_dec_places(x, pos):
""" Adds 1/10th decimal to plot ticks. """ return '%.1f' % x
d2f53c', '#fabebe', '#008080', '#e6beff', '#aa6e28', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000080', '#808080'] def one_dec_places(x, pos):
64
64
34
8
56
lingmicha/pyfolio
pyfolio/utils.py
Python
one_dec_places
one_dec_places
57
62
57
57
13125785700ce79fb9c0f668ccde1c9d93c17e89
bigcode/the-stack
train
e6535a91c99766a0ba11599f
train
function
def get_symbol_rets(symbol, start=None, end=None): """ Calls the currently registered 'returns_func' Parameters ---------- symbol : object An identifier for the asset whose return series is desired. e.g. ticker symbol or database ID start : date, optional Earlies...
def get_symbol_rets(symbol, start=None, end=None):
""" Calls the currently registered 'returns_func' Parameters ---------- symbol : object An identifier for the asset whose return series is desired. e.g. ticker symbol or database ID start : date, optional Earliest date to fetch data for. Defaults to earli...
returns a pandas Series of asset returns. The signature of the function must be as follows >>> func(symbol) Where symbol is an asset identifier Returns ------- None """ SETTINGS['returns_func'] = func def get_symbol_rets(symbol, start=None, end=None):
64
64
141
13
50
lingmicha/pyfolio
pyfolio/utils.py
Python
get_symbol_rets
get_symbol_rets
469
494
469
469
54e8501918d9ab4651546e5eb054d2cea46c167b
bigcode/the-stack
train
8f16aa09fa52134a02421a22
train
function
def detect_intraday(positions, transactions, threshold=0.25): """ Attempt to detect an intraday strategy. Get the number of positions held at the end of the day, and divide that by the number of unique stocks transacted every day. If the average quotient is below a threshold, then an intraday strate...
def detect_intraday(positions, transactions, threshold=0.25):
""" Attempt to detect an intraday strategy. Get the number of positions held at the end of the day, and divide that by the number of unique stocks transacted every day. If the average quotient is below a threshold, then an intraday strategy is detected. Parameters ---------- positions :...
array with mean and standard deviation. Parameters ---------- x : np.array Array to standardize. Returns ------- np.array Standardized array. """ return (x - np.mean(x)) / np.std(x) def detect_intraday(positions, transactions, threshold=0.25):
69
69
233
15
54
lingmicha/pyfolio
pyfolio/utils.py
Python
detect_intraday
detect_intraday
240
266
240
240
10e6c539dc14a8f4130c5cd5d824306ae13064be
bigcode/the-stack
train
aad1c215cf17b382becaa043
train
function
def to_utc(df): """ For use in tests; applied UTC timestamp to DataFrame. """ try: df.index = df.index.tz_localize('UTC') except TypeError: df.index = df.index.tz_convert('UTC') return df
def to_utc(df):
""" For use in tests; applied UTC timestamp to DataFrame. """ try: df.index = df.index.tz_localize('UTC') except TypeError: df.index = df.index.tz_convert('UTC') return df
[0] < benchmark_rets.index[0]) \ or (rets.index[-1] > benchmark_rets.index[-1]): clipped_rets = rets[benchmark_rets.index] else: clipped_rets = rets return clipped_rets def to_utc(df):
64
64
60
6
57
lingmicha/pyfolio
pyfolio/utils.py
Python
to_utc
to_utc
414
424
414
414
470968b09694a2be4bedc14d673c895a7be5ca6d
bigcode/the-stack
train
4dff662e69aefb06b81292ad
train
function
def percentage(x, pos): """ Adds percentage sign to plot ticks. """ return '%.0f%%' % x
def percentage(x, pos):
""" Adds percentage sign to plot ticks. """ return '%.0f%%' % x
Adds 1/10th decimal to plot ticks. """ return '%.1f' % x def two_dec_places(x, pos): """ Adds 1/100th decimal to plot ticks. """ return '%.2f' % x def percentage(x, pos):
64
64
29
6
57
lingmicha/pyfolio
pyfolio/utils.py
Python
percentage
percentage
73
78
73
73
4a6e2c9b149b4d1d2448bb33c565bb9ee64bb969
bigcode/the-stack
train
772b4917aad28a1ff823943b
train
function
def register_return_func(func): """ Registers the 'returns_func' that will be called for retrieving returns data. Parameters ---------- func : function A function that returns a pandas Series of asset returns. The signature of the function must be as follows >>> func(sy...
def register_return_func(func):
""" Registers the 'returns_func' that will be called for retrieving returns data. Parameters ---------- func : function A function that returns a pandas Series of asset returns. The signature of the function must be as follows >>> func(symbol) Where symbol is a...
the register_returns_func and get_symbol_rets. default_returns_func = empyrical.utils.default_returns_func # Settings dict to store functions/values that may # need to be overridden depending on the users environment SETTINGS = { 'returns_func': default_returns_func } def register_return_func(func):
64
64
91
6
58
lingmicha/pyfolio
pyfolio/utils.py
Python
register_return_func
register_return_func
446
466
446
446
5c3238f2689f6875afc74a885f1323950952fa07
bigcode/the-stack
train
d98e1bdf1d48636f065f1b51
train
function
def clip_returns_to_benchmark(rets, benchmark_rets): """ Drop entries from rets so that the start and end dates of rets match those of benchmark_rets. Parameters ---------- rets : pd.Series Daily returns of the strategy, noncumulative. - See pf.tears.create_full_tear_sheet for ...
def clip_returns_to_benchmark(rets, benchmark_rets):
""" Drop entries from rets so that the start and end dates of rets match those of benchmark_rets. Parameters ---------- rets : pd.Series Daily returns of the strategy, noncumulative. - See pf.tears.create_full_tear_sheet for more details benchmark_rets : pd.Series ...
txn_val.index = txn_val.index.normalize() corrected_positions = positions_shifted.add(txn_val, fill_value=0) corrected_positions.index.name = 'period_close' corrected_positions.columns.name = 'sid' return corrected_positions def clip_returns_to_benchmark(rets, benchmark_rets):
64
64
193
13
50
lingmicha/pyfolio
pyfolio/utils.py
Python
clip_returns_to_benchmark
clip_returns_to_benchmark
384
411
384
384
de528f139b85dee9e9648c177fdd970c5c8c320a
bigcode/the-stack
train
558bc1c4edbf74901924ceee
train
function
def format_asset(asset): """ If zipline asset objects are used, we want to print them out prettily within the tear sheet. This function should only be applied directly before displaying. """ try: import zipline.assets except ImportError: return asset if isinstance(asset...
def format_asset(asset):
""" If zipline asset objects are used, we want to print them out prettily within the tear sheet. This function should only be applied directly before displaying. """ try: import zipline.assets except ImportError: return asset if isinstance(asset, zipline.assets.Asset): ...
(x, pos): """ Adds 1/100th decimal to plot ticks. """ return '%.2f' % x def percentage(x, pos): """ Adds percentage sign to plot ticks. """ return '%.0f%%' % x def format_asset(asset):
64
64
85
5
58
lingmicha/pyfolio
pyfolio/utils.py
Python
format_asset
format_asset
81
96
81
81
203c1ae69748f0e020ec91a5b7d67d6a8120628f
bigcode/the-stack
train
b2357783a2b26ad21a296e7c
train
function
def two_dec_places(x, pos): """ Adds 1/100th decimal to plot ticks. """ return '%.2f' % x
def two_dec_places(x, pos):
""" Adds 1/100th decimal to plot ticks. """ return '%.2f' % x
c3', '#808000', '#ffd8b1', '#000080', '#808080'] def one_dec_places(x, pos): """ Adds 1/10th decimal to plot ticks. """ return '%.1f' % x def two_dec_places(x, pos):
64
64
34
8
55
lingmicha/pyfolio
pyfolio/utils.py
Python
two_dec_places
two_dec_places
65
70
65
65
1c6207af2323e8121393e356b81676ad1075b9d5
bigcode/the-stack
train
aedab4b135b8af0cb3ab620c
train
function
def check_intraday(estimate, returns, positions, transactions): """ Logic for checking if a strategy is intraday and processing it. Parameters ---------- estimate: boolean or str, optional Approximate returns for intraday strategies. See description in tears.create_full_tear_sheet. ...
def check_intraday(estimate, returns, positions, transactions):
""" Logic for checking if a strategy is intraday and processing it. Parameters ---------- estimate: boolean or str, optional Approximate returns for intraday strategies. See description in tears.create_full_tear_sheet. returns : pd.Series Daily returns of the strategy, n...
is detected. """ daily_txn = transactions.copy() daily_txn.index = daily_txn.index.date txn_count = daily_txn.groupby(level=0).symbol.nunique().sum() daily_pos = positions.drop('cash', axis=1).replace(0, np.nan) return daily_pos.count(axis=1).sum() / txn_count < threshold def check_intraday(es...
93
93
313
13
79
lingmicha/pyfolio
pyfolio/utils.py
Python
check_intraday
check_intraday
269
312
269
269
e4f65beb9e6c036ecd3a470d184d518a89e5e915
bigcode/the-stack
train
8b23feabb209bc8bea2778e5
train
function
def sample_colormap(cmap_name, n_samples): """ Sample a colormap from matplotlib """ colors = [] colormap = cm.cmap_d[cmap_name] for i in np.linspace(0, 1, n_samples): colors.append(colormap(i)) return colors
def sample_colormap(cmap_name, n_samples):
""" Sample a colormap from matplotlib """ colors = [] colormap = cm.cmap_d[cmap_name] for i in np.linspace(0, 1, n_samples): colors.append(colormap(i)) return colors
of using matplotlib's autofmt_xdate # because it disables xticklabels for all but the last plot if autofmt_xdate: for label in ax.get_xticklabels(): label.set_ha(ha) label.set_rotation(rotation) def sample_colormap(cmap_name, n_samples):
64
64
65
11
53
lingmicha/pyfolio
pyfolio/utils.py
Python
sample_colormap
sample_colormap
540
549
540
540
66b914fb0389b88ee83354ff94047d5fb1b112e9
bigcode/the-stack
train
d1648cb03a7677cf58f662ff
train
function
def to_series(df): """ For use in tests; converts DataFrame's first column to Series. """ return df[df.columns[0]]
def to_series(df):
""" For use in tests; converts DataFrame's first column to Series. """ return df[df.columns[0]]
to_utc(df): """ For use in tests; applied UTC timestamp to DataFrame. """ try: df.index = df.index.tz_localize('UTC') except TypeError: df.index = df.index.tz_convert('UTC') return df def to_series(df):
64
64
32
5
58
lingmicha/pyfolio
pyfolio/utils.py
Python
to_series
to_series
427
432
427
427
a7c98fb434fe44f69cf21e059907f22a7b0c269c
bigcode/the-stack
train
573e7cca9ee6c9caf02980cd
train
function
def configure_legend(ax, autofmt_xdate=True, change_colors=False, rotation=30, ha='right'): """ Format legend for perf attribution plots: - put legend to the right of plot instead of overlapping with it - make legend order match up with graph lines - set colors according to colo...
def configure_legend(ax, autofmt_xdate=True, change_colors=False, rotation=30, ha='right'):
""" Format legend for perf attribution plots: - put legend to the right of plot instead of overlapping with it - make legend order match up with graph lines - set colors according to colormap """ chartBox = ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, ...
Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. Returns ------- pandas.Series Returned by the current 'returns_func' """ return SETTINGS['returns_func']...
100
100
334
25
75
lingmicha/pyfolio
pyfolio/utils.py
Python
configure_legend
configure_legend
497
537
497
498
3a14055f831d9805f5b9eea3cdf593549edbae12
bigcode/the-stack
train
d7395d5d2ee37caca65f33eb
train
function
def extract_rets_pos_txn_from_zipline(backtest): """ Extract returns, positions, transactions and leverage from the backtest data structure returned by zipline.TradingAlgorithm.run(). The returned data structures are in a format compatible with the rest of pyfolio and can be directly passed to ...
def extract_rets_pos_txn_from_zipline(backtest):
""" Extract returns, positions, transactions and leverage from the backtest data structure returned by zipline.TradingAlgorithm.run(). The returned data structures are in a format compatible with the rest of pyfolio and can be directly passed to e.g. tears.create_full_tear_sheet(). Paramet...
Error: return asset if isinstance(asset, zipline.assets.Asset): return asset.symbol else: return asset def vectorize(func): """ Decorator so that functions can be written to work on Series but may still be called with DataFrames. """ def wrapper(df, *args, **kwarg...
130
130
436
13
116
lingmicha/pyfolio
pyfolio/utils.py
Python
extract_rets_pos_txn_from_zipline
extract_rets_pos_txn_from_zipline
114
167
114
114
4b35505e527ac8736ca88c8aeb244940b9714f9e
bigcode/the-stack
train
ca26f8bfc65e042a559ac301
train
function
def main(): argument_spec = f5_argument_spec() meta_args = dict( name=dict(required=True), type=dict(default=DEFAULT_TEMPLATE_TYPE_CHOICE, choices=TEMPLATE_TYPE_CHOICES), parent=dict(default=DEFAULT_PARENT), parent_partition=dict(default='Common'), send=dict(required=Fal...
def main():
argument_spec = f5_argument_spec() meta_args = dict( name=dict(required=True), type=dict(default=DEFAULT_TEMPLATE_TYPE_CHOICE, choices=TEMPLATE_TYPE_CHOICES), parent=dict(default=DEFAULT_PARENT), parent_partition=dict(default='Common'), send=dict(required=False), ...
(api, module, monitor, template_string_properties, template_integer_properties): changed = False for str_property in template_string_properties: if str_property['value'] is not None and not check_string_property(api, monitor, str_property): if not module.check_mode: set_strin...
256
256
1,291
3
252
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
main
main
306
483
306
306
24b944d510c93753f76b5bf9024463a6656b8c6f
bigcode/the-stack
train
51160a7f5f49fef5b2272006
train
function
def check_integer_property(api, monitor, int_property): try: return int_property == api.LocalLB.Monitor.get_template_integer_property( [monitor], [int_property['type']] )[0] except bigsuds.OperationFailed as e: # happens in check mode if not created yet if "was not fo...
def check_integer_property(api, monitor, int_property):
try: return int_property == api.LocalLB.Monitor.get_template_integer_property( [monitor], [int_property['type']] )[0] except bigsuds.OperationFailed as e: # happens in check mode if not created yet if "was not found" in str(e): return True else: ...
(e): return True else: # genuine exception raise def set_string_property(api, monitor, str_property): api.LocalLB.Monitor.set_template_string_property( template_names=[monitor], values=[str_property] ) def check_integer_property(api, monitor, int_pro...
64
64
90
11
53
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
check_integer_property
check_integer_property
249
260
249
249
5456eeb142a6ac9efb48e756cc8da1dab2378c6f
bigcode/the-stack
train
fb960926d1c26c1ec133c2cb
train
function
def create_monitor(api, monitor, template_attributes): try: api.LocalLB.Monitor.create_template( templates=[{ 'template_name': monitor, 'template_type': TEMPLATE_TYPE }], template_attributes=[template_attributes] ) except bigsud...
def create_monitor(api, monitor, template_attributes):
try: api.LocalLB.Monitor.create_template( templates=[{ 'template_name': monitor, 'template_type': TEMPLATE_TYPE }], template_attributes=[template_attributes] ) except bigsuds.OperationFailed as e: if "already exists" in ...
) or parent(%s)' % (ttype, parent)) except bigsuds.OperationFailed as e: if "was not found" in str(e): result = False else: # genuine exception raise return result def create_monitor(api, monitor, template_attributes):
64
64
91
10
53
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
create_monitor
create_monitor
196
211
196
196
45f996277a11df4b74b2cd2393287547385b6764
bigcode/the-stack
train
0cc0f2d0ff602aadf799d2de
train
function
def set_ipport(api, monitor, ipport): try: api.LocalLB.Monitor.set_template_destination( template_names=[monitor], destinations=[ipport] ) return True, "" except bigsuds.OperationFailed as e: if "Cannot modify the address type of monitor" in str(e): retur...
def set_ipport(api, monitor, ipport):
try: api.LocalLB.Monitor.set_template_destination( template_names=[monitor], destinations=[ipport] ) return True, "" except bigsuds.OperationFailed as e: if "Cannot modify the address type of monitor" in str(e): return False, "Cannot modify the address ty...
): if not module.check_mode: set_integer_property(api, monitor, int_property) changed = True return changed def get_ipport(api, monitor): return api.LocalLB.Monitor.get_template_destination(template_names=[monitor])[0] def set_ipport(api, monitor, ipport):
64
64
97
11
53
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
set_ipport
set_ipport
291
303
291
291
59175eb7848f2fb67bd5ada556d14d338f7998e5
bigcode/the-stack
train
35042712a5291f39db29f199
train
function
def delete_monitor(api, monitor): try: api.LocalLB.Monitor.delete_template(template_names=[monitor]) except bigsuds.OperationFailed as e: # maybe it was deleted since we checked if "was not found" in str(e): return False else: # genuine exception ...
def delete_monitor(api, monitor):
try: api.LocalLB.Monitor.delete_template(template_names=[monitor]) except bigsuds.OperationFailed as e: # maybe it was deleted since we checked if "was not found" in str(e): return False else: # genuine exception raise return True
'template_type': TEMPLATE_TYPE }], template_attributes=[template_attributes] ) except bigsuds.OperationFailed as e: if "already exists" in str(e): return False else: # genuine exception raise return True def delete_monitor(api,...
64
64
73
7
56
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
delete_monitor
delete_monitor
214
224
214
214
11841c6647dc6338a5a842c2708387a061ea409b
bigcode/the-stack
train
76dbd30e0506932bdc334da5
train
function
def get_ipport(api, monitor): return api.LocalLB.Monitor.get_template_destination(template_names=[monitor])[0]
def get_ipport(api, monitor):
return api.LocalLB.Monitor.get_template_destination(template_names=[monitor])[0]
int_property in template_integer_properties: if int_property['value'] is not None and not check_integer_property(api, monitor, int_property): if not module.check_mode: set_integer_property(api, monitor, int_property) changed = True return changed def get_ipport(api,...
64
64
25
8
55
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
get_ipport
get_ipport
287
288
287
287
aa6b70105ae51bd2597600faf53f51d36e9b0239
bigcode/the-stack
train
cdab7cd1a9894b19523aa790
train
function
def check_string_property(api, monitor, str_property): try: template_prop = api.LocalLB.Monitor.get_template_string_property( [monitor], [str_property['type']] )[0] return str_property == template_prop except bigsuds.OperationFailed as e: # happens in check mode if no...
def check_string_property(api, monitor, str_property):
try: template_prop = api.LocalLB.Monitor.get_template_string_property( [monitor], [str_property['type']] )[0] return str_property == template_prop except bigsuds.OperationFailed as e: # happens in check mode if not created yet if "was not found" in str(e): ...
=[monitor]) except bigsuds.OperationFailed as e: # maybe it was deleted since we checked if "was not found" in str(e): return False else: # genuine exception raise return True def check_string_property(api, monitor, str_property):
64
64
97
11
52
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
check_string_property
check_string_property
227
239
227
227
5e4fc697c8749baecccc2664eb1c3542d2671ad8
bigcode/the-stack
train
61b181445e77a644558f9413
train
function
def update_monitor_properties(api, module, monitor, template_string_properties, template_integer_properties): changed = False for str_property in template_string_properties: if str_property['value'] is not None and not check_string_property(api, monitor, str_property): if not module.check_mo...
def update_monitor_properties(api, module, monitor, template_string_properties, template_integer_properties):
changed = False for str_property in template_string_properties: if str_property['value'] is not None and not check_string_property(api, monitor, str_property): if not module.check_mode: set_string_property(api, monitor, str_property) changed = True for int_pr...
else: # genuine exception raise def set_integer_property(api, monitor, int_property): api.LocalLB.Monitor.set_template_integer_property( template_names=[monitor], values=[int_property] ) def update_monitor_properties(api, module, monitor, template_string_properties, te...
64
64
135
18
46
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
update_monitor_properties
update_monitor_properties
270
284
270
270
88b32807ec0f234e117e87200b0ba75aa5d314a5
bigcode/the-stack
train
3c59c482ae51f1a6af99750c
train
function
def check_monitor_exists(module, api, monitor, parent): # hack to determine if monitor exists result = False try: ttype = api.LocalLB.Monitor.get_template_type(template_names=[monitor])[0] parent2 = api.LocalLB.Monitor.get_parent_template(template_names=[monitor])[0] if ttype == TEMP...
def check_monitor_exists(module, api, monitor, parent): # hack to determine if monitor exists
result = False try: ttype = api.LocalLB.Monitor.get_template_type(template_names=[monitor])[0] parent2 = api.LocalLB.Monitor.get_parent_template(template_names=[monitor])[0] if ttype == TEMPLATE_TYPE and parent == parent2: result = True else: module.fail_j...
'TTYPE_TCP' TEMPLATE_TYPE_CHOICES = ['tcp', 'tcp_echo', 'tcp_half_open'] DEFAULT_PARENT = DEFAULT_TEMPLATE_TYPE_CHOICE = DEFAULT_TEMPLATE_TYPE.replace('TTYPE_', '').lower() def check_monitor_exists(module, api, monitor, parent): # hack to determine if monitor exists
64
64
159
21
43
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
check_monitor_exists
check_monitor_exists
177
193
177
178
21a62161496f69fa96589e94044441c287bcb569
bigcode/the-stack
train
bd54f9c6ebce601920ceb2b6
train
function
def set_string_property(api, monitor, str_property): api.LocalLB.Monitor.set_template_string_property( template_names=[monitor], values=[str_property] )
def set_string_property(api, monitor, str_property):
api.LocalLB.Monitor.set_template_string_property( template_names=[monitor], values=[str_property] )
str_property == template_prop except bigsuds.OperationFailed as e: # happens in check mode if not created yet if "was not found" in str(e): return True else: # genuine exception raise def set_string_property(api, monitor, str_property):
64
64
36
11
52
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
set_string_property
set_string_property
242
246
242
242
0825baaf5e1f398a5b7a129ae1f94efef3b2de77
bigcode/the-stack
train
35342b94632367ff67e2e256
train
function
def set_integer_property(api, monitor, int_property): api.LocalLB.Monitor.set_template_integer_property( template_names=[monitor], values=[int_property] )
def set_integer_property(api, monitor, int_property):
api.LocalLB.Monitor.set_template_integer_property( template_names=[monitor], values=[int_property] )
type']] )[0] except bigsuds.OperationFailed as e: # happens in check mode if not created yet if "was not found" in str(e): return True else: # genuine exception raise def set_integer_property(api, monitor, int_property):
64
64
36
11
52
EnjoyLifeFund/py36pkgs
ansible/modules/network/f5/bigip_monitor_tcp.py
Python
set_integer_property
set_integer_property
263
267
263
263
ab0bb1bce2f6a9f402fbf205c9c5e5ed5e8805c5
bigcode/the-stack
train
e724f63d9c094181b36b8427
train
class
class Opcode(): """ The Opcode class acts as a container for the instruction, if the opcode class is found when the processor goes to execute a memory location then it will be run instead, negating the need for the processor to decode previously decoded instructions. """ FUNCTION_POI...
class Opcode():
""" The Opcode class acts as a container for the instruction, if the opcode class is found when the processor goes to execute a memory location then it will be run instead, negating the need for the processor to decode previously decoded instructions. """ FUNCTION_POINTERS = { ...
from processor.opcodes.opcodes_flow import * from processor.opcodes.opcodes_conditional import * from processor.opcodes.opcodes_display import * from processor.opcodes.opcodes_maths import * from processor.opcodes.opcodes_memory import * from processor.opcodes.opcodes_delay import * from processor.opcodes.opcodes_input...
68
256
1,504
3
65
Jackson-S/python-chip8
processor/opcode_class.py
Python
Opcode
Opcode
10
142
10
10
46e3393c602da8e71b17c291c47e85b1c8765c55
bigcode/the-stack
train
a43b6b3f10a8a94a42d7cdb9
train
function
def test_correlate_sparse_valid_mode(): image = cp.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=float) kernel = cp.array([0, 1, 2, 4, 8, 16, 32, 64, 128]).reshape((3, 3)...
def test_correlate_sparse_valid_mode():
image = cp.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=float) kernel = cp.array([0, 1, 2, 4, 8, 16, 32, 64, 128]).reshape((3, 3)) cs_output = correlate_sparse(imag...
import cupy as cp import pytest from cupy.testing import assert_array_equal from cupyx.scipy import ndimage as ndi from cucim.skimage._shared.utils import _supported_float_type from cucim.skimage.filters import correlate_sparse def test_correlate_sparse_valid_mode():
62
64
191
9
52
chrisroat/cucim
python/cucim/src/cucim/skimage/filters/tests/test_correlate.py
Python
test_correlate_sparse_valid_mode
test_correlate_sparse_valid_mode
10
23
10
10
188d45e0f7858479c16c2bab19ec849db0a4677b
bigcode/the-stack
train
8703911b045322bce9a9e770
train
function
@pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) @pytest.mark.parametrize( "dtype", [cp.uint16, cp.int32, cp.float16, cp.float32, cp.float64] ) def test_correlate_sparse(mode, dtype): image = cp.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1...
@pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) @pytest.mark.parametrize( "dtype", [cp.uint16, cp.int32, cp.float16, cp.float32, cp.float64] ) def test_correlate_sparse(mode, dtype):
image = cp.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=dtype) kernel = cp.array([0, 1, 2, 4, 8, 16, 32, 64, 128]).reshape((3, 3)) cs_output = correlate_sparse(imag...
:4, 1:4] assert_array_equal(cs_output, ndi_output) @pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) @pytest.mark.parametrize( "dtype", [cp.uint16, cp.int32, cp.float16, cp.float32, cp.float64] ) def test_correlate_sparse(mode, dtype):
73
73
244
55
18
chrisroat/cucim
python/cucim/src/cucim/skimage/filters/tests/test_correlate.py
Python
test_correlate_sparse
test_correlate_sparse
26
44
26
30
7fd977e491394f928d69087d300ad04590cb9e88
bigcode/the-stack
train
eda42115962db5aec11b8572
train
function
@pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) def test_correlate_sparse_invalid_kernel(mode): image = cp.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=flo...
@pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) def test_correlate_sparse_invalid_kernel(mode):
image = cp.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=float) # invalid kernel size invalid_kernel = cp.array([0, 1, 2, 4]).reshape((2, 2)) with pytest.raises(Va...
_type(image.dtype) ndi_output = ndi.correlate( image.astype(float, copy=False), kernel, mode=mode ) assert_array_equal(cs_output, ndi_output) @pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) def test_correlate_sparse_invalid_kernel(mode):
64
64
162
25
39
chrisroat/cucim
python/cucim/src/cucim/skimage/filters/tests/test_correlate.py
Python
test_correlate_sparse_invalid_kernel
test_correlate_sparse_invalid_kernel
47
57
47
48
8353d5cee9c761c811086120cf6db48f4344f57b
bigcode/the-stack
train
dbf43cf0a0fd26967b6f6562
train
class
class TestInputTracker(unittest.TestCase): def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) def setUp(self): self.speedTracker = MagicMock() self.speedTracker.getTopSpeed = MagicMock(return_value = 0) self.notify = MagicMock() self.thing = In...
class TestInputTracker(unittest.TestCase):
def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) def setUp(self): self.speedTracker = MagicMock() self.speedTracker.getTopSpeed = MagicMock(return_value = 0) self.notify = MagicMock() self.thing = InputTracker(self.speedTracker, self.notify) ...
import unittest from timerecorder.inputTracker import InputTracker, Signal from unittest.mock import MagicMock fieldCount = 66 class TestInputTracker(unittest.TestCase):
36
232
776
8
27
fenugrec/dirt-rally-time-recorder
tests/test_inputTracker.py
Python
TestInputTracker
TestInputTracker
7
100
7
8
3a630841e244ded5c514219eb53f0edae20e5ba6
bigcode/the-stack
train
76d0b0da5922f17035180b28
train
class
class ChemspiderSearcher: def __init__(self, api_key: str): self.cs = ChemSpider(api_key) def chemspider_names(self, names: Iterable[str], partial_dict: Mapping[str, chemspipy.objects.Compound]={}, sleep_secs_between:float=0.1) -> Mapping[str, chemspipy.objects.Compound]: """Build a dictionary mapping compound n...
class ChemspiderSearcher:
def __init__(self, api_key: str): self.cs = ChemSpider(api_key) def chemspider_names(self, names: Iterable[str], partial_dict: Mapping[str, chemspipy.objects.Compound]={}, sleep_secs_between:float=0.1) -> Mapping[str, chemspipy.objects.Compound]: """Build a dictionary mapping compound names to unique ChemSpider ...
import re import chemspipy from chemspipy import ChemSpider from typing import Iterable, Mapping, Optional, Iterator, Tuple import warnings import time class ChemspiderSearcher:
41
153
512
6
34
kokellab/klgists
klgists/bioinf/chemspider_utils.py
Python
ChemspiderSearcher
ChemspiderSearcher
9
42
9
9
3ffdc549b4b55a30111e8110b4b33b3e74fdeeb3
bigcode/the-stack
train
f36d5c9affe885915a4e3ec3
train
class
class SpiderRecovery: def __init__(self, chemspider_api_key: str): self._cs = ChemSpider(chemspider_api_key) self._cs = None self._has_stero = re.compile('(?:\([RSrsEZez+\-]\))|(?:[RSrsEZez][- \(])') def recover_spider(self, name: str) -> Optional[str]: """Makes a best-effort attempt to recover SMILES strin...
class SpiderRecovery:
def __init__(self, chemspider_api_key: str): self._cs = ChemSpider(chemspider_api_key) self._cs = None self._has_stero = re.compile('(?:\([RSrsEZez+\-]\))|(?:[RSrsEZez][- \(])') def recover_spider(self, name: str) -> Optional[str]: """Makes a best-effort attempt to recover SMILES strings from compound names ...
[chemspipy.objects.Compound]: results = [] for result in self.cs.search(name): # blocks results.append(result) if len(results) == 0: warnings.warn("No results found for {}".format(name)) elif len(results) > 1: warnings.warn('Multiple ({}) hits found for {}'.format(len(results), name)) else: ...
157
157
525
4
152
kokellab/klgists
klgists/bioinf/chemspider_utils.py
Python
SpiderRecovery
SpiderRecovery
47
90
47
48
016e0e17db4b57f04fd9d3c9f68429992776ca0d
bigcode/the-stack
train
5771e2db7e1ab04f2db6ef0d
train
function
def latest_aws_image(owner, name, arm64=False): client = boto3.client('ec2', region_name='us-east-1') response = client.describe_images( Owners=[owner], Filters=[ { 'Name': 'name', 'Values': [ name, ], },...
def latest_aws_image(owner, name, arm64=False):
client = boto3.client('ec2', region_name='us-east-1') response = client.describe_images( Owners=[owner], Filters=[ { 'Name': 'name', 'Values': [ name, ], }, { 'Name': 'architec...
=" in arg: image_overridden = True args = args + " " + arg if kops_image and not image_overridden: args = f"--image='{kops_image}' {args}" return args.strip() def latest_aws_image(owner, name, arm64=False):
64
64
142
13
51
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
latest_aws_image
latest_aws_image
118
140
118
118
27a8773819e7b17e8575e290fb6e81b672ae7e55
bigcode/the-stack
train
66a8a4099c3cf822debb10c8
train
function
def simple_hash(s): # & 0xffffffff avoids python2/python3 compatibility return zlib.crc32(s.encode()) & 0xffffffff
def simple_hash(s): # & 0xffffffff avoids python2/python3 compatibility
return zlib.crc32(s.encode()) & 0xffffffff
'kops-grid-scenario-service-account-iam', 'kops-grid-scenario-arm64', 'kops-grid-scenario-serial-test-for-timeout', 'kops-grid-scenario-terraform', ] def simple_hash(s): # & 0xffffffff avoids python2/python3 compatibility
64
64
33
18
46
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
simple_hash
simple_hash
32
34
32
33
7047058ec9bc332fe7826b476a56ce038a5fc23c
bigcode/the-stack
train