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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95ec5b187914c292ad52b7a5 | train | function | def ogr_shape_19():
ds = ogr.Open('data/Stacks.shp')
lyr = ds.GetLayer(0)
lyr.ResetReading()
feat = lyr.GetNextFeature()
wkt = 'MULTIPOLYGON (((3115478.809630727861077 13939288.008583962917328,3134266.47213465673849 13971973.394036004319787,3176989.101938112173229 13957303.575368551537395,3198607.... | def ogr_shape_19():
| ds = ogr.Open('data/Stacks.shp')
lyr = ds.GetLayer(0)
lyr.ResetReading()
feat = lyr.GetNextFeature()
wkt = 'MULTIPOLYGON (((3115478.809630727861077 13939288.008583962917328,3134266.47213465673849 13971973.394036004319787,3176989.101938112173229 13957303.575368551537395,3198607.7820796193555 1392178... | _ds.GetLayer(0)
srs_lyr = shp_lyr.GetSpatialRef()
if srs_lyr is None:
gdaltest.post_reason( 'Missing projection definition.' )
return 'fail'
# data/poly.shp has arbitrarily assigned EPSG:27700
srs = osr.SpatialReference()
srs.ImportFromEPSG( 27700 )
#srs.StripCTParms()
if... | 207 | 207 | 690 | 6 | 201 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_19 | ogr_shape_19 | 661 | 674 | 661 | 662 | 3fe799ace070f8c75ff9d37f470aae2acdb8faae | bigcode/the-stack | train |
434d9fdf6c7b8261cc29323a | train | function | def ogr_shape_105():
ds = ogr.Open('data/padding_after_field_defns.dbf')
lyr = ds.GetLayer(0)
if lyr.GetLayerDefn().GetFieldCount() != 2:
gdaltest.post_reason('fail')
return 'fail'
f = lyr.GetNextFeature()
if f['id'] != '1' or f['foo'] != '2':
gdaltest.post_reason('fail')
... | def ogr_shape_105():
| ds = ogr.Open('data/padding_after_field_defns.dbf')
lyr = ds.GetLayer(0)
if lyr.GetLayerDefn().GetFieldCount() != 2:
gdaltest.post_reason('fail')
return 'fail'
f = lyr.GetNextFeature()
if f['id'] != '1' or f['foo'] != '2':
gdaltest.post_reason('fail')
return 'fail'
... | , options)
f.DumpReadable()
return 'fail'
ds = None
ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename)
return 'success'
###############################################################################
# Test reading .dbf with substantial padding after last fie... | 64 | 64 | 107 | 6 | 58 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_105 | ogr_shape_105 | 5,086 | 5,098 | 5,086 | 5,087 | 8686efc8e73a1db46ded5203e4ad9c25055ad379 | bigcode/the-stack | train |
f5bca7e25d294afe78ae6649 | train | function | def ogr_shape_60():
if gdaltest.shape_ds is None:
return 'skip'
shp_ds = ogr.Open( 'data/testpointzm.shp' )
if shp_ds is None:
return 'skip'
shp_lyr = shp_ds.GetLayer(0)
feat = shp_lyr.GetNextFeature()
geom = feat.GetGeometryRef()
if geom.GetGeometryName() != 'POINT':
... | def ogr_shape_60():
| if gdaltest.shape_ds is None:
return 'skip'
shp_ds = ogr.Open( 'data/testpointzm.shp' )
if shp_ds is None:
return 'skip'
shp_lyr = shp_ds.GetLayer(0)
feat = shp_lyr.GetNextFeature()
geom = feat.GetGeometryRef()
if geom.GetGeometryName() != 'POINT':
gdaltest.post_re... | 80))':
print (geom.ExportToIsoWkt())
gdaltest.post_reason( 'fail' )
return 'fail'
geom = None
feat = None
return 'success'
###############################################################################
# Test reading a shape with XYZM geometries
def ogr_shape_60():
| 64 | 64 | 206 | 6 | 57 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_60 | ogr_shape_60 | 2,914 | 2,943 | 2,914 | 2,915 | 730e715abb907cb880b2f894cf50e4ea9d5784d6 | bigcode/the-stack | train |
927035bd8f96b6f6808042d8 | train | function | def ogr_shape_7():
if gdaltest.shape_ds is None:
return 'skip'
gdaltest.shape_lyr.SetAttributeFilter( None )
geom = ogr.CreateGeometryFromWkt(
'LINESTRING(479505 4763195,480526 4762819)' )
gdaltest.shape_lyr.SetSpatialFilter( geom )
geom.Destroy()
tr = ogrtest.check_features_... | def ogr_shape_7():
| if gdaltest.shape_ds is None:
return 'skip'
gdaltest.shape_lyr.SetAttributeFilter( None )
geom = ogr.CreateGeometryFromWkt(
'LINESTRING(479505 4763195,480526 4762819)' )
gdaltest.shape_lyr.SetSpatialFilter( geom )
geom.Destroy()
tr = ogrtest.check_features_against_list( gdalte... | ', max_error = 0.001 ) != 0:
tr = 0
gdaltest.shape_ds.ReleaseResultSet( sql_lyr )
if tr:
return 'success'
else:
return 'fail'
###############################################################################
# Test spatial filtering.
def ogr_shape_7():
| 64 | 64 | 144 | 6 | 58 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_7 | ogr_shape_7 | 218 | 238 | 218 | 219 | c0ef78d6ee3f20d24674ad32ffbc5aea1eacd917 | bigcode/the-stack | train |
2bd1b3c6717f85aaf1b1407f | train | function | def ogr_shape_92():
ds = ogr.Open('data/multipointz_without_m.shp')
lyr = ds.GetLayer(0)
f = lyr.GetNextFeature()
wkt = f.GetGeometryRef().ExportToIsoWkt()
if wkt != 'MULTIPOINT Z ((0 1 2),(3 4 5))':
gdaltest.post_reason('fail')
print(wkt)
return 'fail'
return 'success'... | def ogr_shape_92():
| ds = ogr.Open('data/multipointz_without_m.shp')
lyr = ds.GetLayer(0)
f = lyr.GetNextFeature()
wkt = f.GetGeometryRef().ExportToIsoWkt()
if wkt != 'MULTIPOINT Z ((0 1 2),(3 4 5))':
gdaltest.post_reason('fail')
print(wkt)
return 'fail'
return 'success'
| f in lyr:
pass
ds = ogr.Open('data/polygonm_without_m.shp')
lyr = ds.GetLayer(0)
for f in lyr:
pass
return 'success'
###############################################################################
# Test reading multipoint Z geometries without M
def ogr_shape_92():
| 64 | 64 | 102 | 6 | 57 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_92 | ogr_shape_92 | 4,270 | 4,281 | 4,270 | 4,271 | 1d72d828160c6f5c2940cd0843765d4b3a589f45 | bigcode/the-stack | train |
36a50e8f0cd3530140248840 | train | function | def ogr_shape_52():
expected_geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((175.524709766699999 -40.17203475,175.524757883299998 -40.172050566700001,175.52480505 -40.1720663,175.524858766699992 -40.172091433299997,175.524913916700001 -40.172112966699999,175.524966049999989 -40.172136933300003,175.52503063329999... | def ogr_shape_52():
| expected_geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((175.524709766699999 -40.17203475,175.524757883299998 -40.172050566700001,175.52480505 -40.1720663,175.524858766699992 -40.172091433299997,175.524913916700001 -40.172112966699999,175.524966049999989 -40.172136933300003,175.525030633299991 -40.17216185,175.52... | f')
ds = ogr.Open('/vsimem/ogr_shape_51.shp', update = 1)
lyr = ds.GetLayer(0)
lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString))
feat = lyr.GetNextFeature()
feat.SetField(0, 'bar')
lyr.SetFeature(feat)
ds = None
ds = ogr.Open('/vsimem/ogr_shape_51.shp')
lyr = ds.GetLayer(0)
... | 256 | 256 | 1,792 | 6 | 249 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_52 | ogr_shape_52 | 2,168 | 2,201 | 2,168 | 2,169 | 4559a664054d423fcfc7e70b4948134c338a0341 | bigcode/the-stack | train |
473397d01ce98579586db94e | train | function | def ogr_shape_50():
ds = ogr.Open( 'data/chinese.dbf')
if ds is None:
return 'skip'
lyr = ds.GetLayer(0)
reconv_possible = lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1
if gdal.GetLastErrorMsg().find('Recode from CP936 to UTF-8 not supported, treated as ISO8859-1 to UTF-8.') != -1:
... | def ogr_shape_50():
| ds = ogr.Open( 'data/chinese.dbf')
if ds is None:
return 'skip'
lyr = ds.GetLayer(0)
reconv_possible = lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1
if gdal.GetLastErrorMsg().find('Recode from CP936 to UTF-8 not supported, treated as ISO8859-1 to UTF-8.') != -1:
if reconv_possible:... | else:
exec("gdaltest.exp_name = u'OSEBERG S\u00D8R'")
gdaltest.exp_name = gdaltest.exp_name.encode('utf-8')
if name != gdaltest.exp_name:
gdaltest.post_reason( 'Did not get expected name, encoding problems?' )
return 'fail'
return 'success'
##################################... | 98 | 98 | 329 | 6 | 91 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_50 | ogr_shape_50 | 2,085 | 2,117 | 2,085 | 2,086 | 11578072cf8ba3effcbe3ad393b4ce1adf6f96d3 | bigcode/the-stack | train |
00ceff8889da77c53956e9e8 | train | function | def ogr_shape_37_bis():
ds = ogr.Open('/vsitar/data/poly.tar')
if ds is None:
return 'fail'
lyr = ds.GetLayer(0)
srs = lyr.GetSpatialRef()
wkt = srs.ExportToWkt()
if wkt.find('OSGB') == -1:
gdaltest.post_reason('did not get expected SRS')
return 'fail'
for i in ra... | def ogr_shape_37_bis():
| ds = ogr.Open('/vsitar/data/poly.tar')
if ds is None:
return 'fail'
lyr = ds.GetLayer(0)
srs = lyr.GetSpatialRef()
wkt = srs.ExportToWkt()
if wkt.find('OSGB') == -1:
gdaltest.post_reason('did not get expected SRS')
return 'fail'
for i in range(10):
feat_rea... | 1.0,479735.90625 4764752.0,479750.6875 4764702.0))'),
max_error = 0.000000001 ) != 0:
print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt())
return 'fail'
ds = None
gdal.Unlink('data/poly.tar.gz.properties')
return 'success'
###############... | 114 | 114 | 382 | 8 | 105 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_37_bis | ogr_shape_37_bis | 1,592 | 1,621 | 1,592 | 1,593 | c2b606edd148c9f58c8226edebb8526826dc00f3 | bigcode/the-stack | train |
fac4afe70a379dcc006c5525 | train | function | def ogr_shape_107():
layer_name = 'ogr_shape_107'
filename = '/vsimem/' + layer_name + '.shp'
copy_filename = '/vsimem/' + layer_name + '_copy.shp'
shape_drv = ogr.GetDriverByName('ESRI Shapefile')
ds = shape_drv.CreateDataSource(filename)
lyr = ds.CreateLayer(layer_name)
# Create a shape... | def ogr_shape_107():
| layer_name = 'ogr_shape_107'
filename = '/vsimem/' + layer_name + '.shp'
copy_filename = '/vsimem/' + layer_name + '_copy.shp'
shape_drv = ogr.GetDriverByName('ESRI Shapefile')
ds = shape_drv.CreateDataSource(filename)
lyr = ds.CreateLayer(layer_name)
# Create a shape
f = ogr.Feature(l... | if verbose:
print('%s size is %d, whereas %s size is %d' % (filename1, size1, filename2, size2))
ret = False
if ret:
data1 = gdal.VSIFReadL(1, size1, f1)
data2 = gdal.VSIFReadL(1, size2, f2)
if data1 != data2:
if verbose:
print('File content o... | 201 | 201 | 671 | 6 | 195 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_107 | ogr_shape_107 | 5,178 | 5,260 | 5,178 | 5,179 | 73ebb0339ccdbefe06e8ed2baaf6d95e03f123ac | bigcode/the-stack | train |
bbcd1104ecbc01fcc3357320 | train | function | def ogr_shape_108():
ds = ogr.Open('data/poly.shp')
lyr = ds.GetLayer(0)
lyr.SetSpatialFilterRect(479750.6875,4764702.0,479750.6875,4764702.0)
expected_fc = lyr.GetFeatureCount()
lyr.SetAttributeFilter("1=1")
if lyr.GetFeatureCount() != expected_fc:
gdaltest.post_reason('fail')
... | def ogr_shape_108():
| ds = ogr.Open('data/poly.shp')
lyr = ds.GetLayer(0)
lyr.SetSpatialFilterRect(479750.6875,4764702.0,479750.6875,4764702.0)
expected_fc = lyr.GetFeatureCount()
lyr.SetAttributeFilter("1=1")
if lyr.GetFeatureCount() != expected_fc:
gdaltest.post_reason('fail')
print(lyr.GetFeatureCo... | )
if not is_same(copy_filename, filename):
gdaltest.post_reason('fail')
return'fail'
shape_drv.DeleteDataSource( copy_filename )
shape_drv.DeleteDataSource( filename )
return 'success'
###############################################################################
# Test spatial + at... | 64 | 64 | 118 | 6 | 57 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_108 | ogr_shape_108 | 5,265 | 5,277 | 5,265 | 5,266 | 2c8995a5b0bd58396fcd9651a84ed97c374fa3e2 | bigcode/the-stack | train |
7728c51c9965151f3e0eae0f | train | function | def ogr_shape_95():
ds = gdal.OpenEx('data/pointzm_with_all_nodata_m.shp')
lyr = ds.GetLayer(0)
if lyr.GetGeomType() != ogr.wkbPoint25D:
gdaltest.post_reason('fail')
print(lyr.GetGeomType())
return 'fail'
f = lyr.GetNextFeature()
if f.GetGeometryRef().ExportToIsoWkt() != 'PO... | def ogr_shape_95():
| ds = gdal.OpenEx('data/pointzm_with_all_nodata_m.shp')
lyr = ds.GetLayer(0)
if lyr.GetGeomType() != ogr.wkbPoint25D:
gdaltest.post_reason('fail')
print(lyr.GetGeomType())
return 'fail'
f = lyr.GetNextFeature()
if f.GetGeometryRef().ExportToIsoWkt() != 'POINT Z (1 2 3)':
... | :
if expected_fail:
print('FIXME!:', i, shpt, geom_type, wkt, f.GetGeometryRef().ExportToIsoWkt())
else:
gdaltest.post_reason('fail')
print(i, shpt, geom_type, wkt, f.GetGeometryRef().ExportToIsoWkt())
return... | 139 | 139 | 465 | 6 | 132 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_95 | ogr_shape_95 | 4,375 | 4,416 | 4,375 | 4,376 | d7d59c789b5fa8cc083743166c99c53742417b03 | bigcode/the-stack | train |
a7a9b9dd09f527e7862a6f89 | train | function | def ogr_shape_84():
ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_84.shp')
lyr = ds.CreateLayer('ogr_shape_84', options = ['SPATIAL_INDEX=YES'])
f = ogr.Feature(lyr.GetLayerDefn())
f.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0,0 0))'))
lyr.Create... | def ogr_shape_84():
| ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_84.shp')
lyr = ds.CreateLayer('ogr_shape_84', options = ['SPATIAL_INDEX=YES'])
f = ogr.Feature(lyr.GetLayerDefn())
f.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0,0 0))'))
lyr.CreateFeature(f)
f = No... | lyr.GetFeature(0)
if f.GetGeometryRef().GetGeometryType() != ogr.wkbPolygon:
gdaltest.post_reason('fail')
return 'fail'
ds = None
return 'success'
###############################################################################
# Test SPATIAL_INDEX creation option
def ogr_shape_84():
| 64 | 64 | 165 | 6 | 57 | OpenGeoLabs/gdal | autotest/ogr/ogr_shape.py | Python | ogr_shape_84 | ogr_shape_84 | 3,989 | 4,003 | 3,989 | 3,990 | dd17dc8a79c844e596e2ca2e6483ca09a2777f8d | bigcode/the-stack | train |
28751f23ca8f63a12f0f0a29 | train | function | def is_prime(number):
for b in range(2,int(math.sqrt(number))+1):
if number%b==0:
return False
return True
| def is_prime(number):
| for b in range(2,int(math.sqrt(number))+1):
if number%b==0:
return False
return True
| #The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#Find the sum of all the primes below two million.
import math
def is_prime(number):
| 45 | 64 | 34 | 5 | 39 | raedeid/python-puzzle | proplem10 ten.py | Python | is_prime | is_prime | 5 | 9 | 5 | 5 | 8a6f4b79935d2683a6eaa18483136174afd4cce0 | bigcode/the-stack | train |
399cb7ec01484254b4c97b9e | train | class | class DeconzAlarmControlPanel(DeconzDevice, AlarmControlPanelEntity):
"""Representation of a deCONZ alarm control panel."""
TYPE = DOMAIN
_device: AncillaryControl
_attr_code_format = CodeFormat.NUMBER
_attr_supported_features = (
AlarmControlPanelEntityFeature.ARM_AWAY
| AlarmCont... | class DeconzAlarmControlPanel(DeconzDevice, AlarmControlPanelEntity):
| """Representation of a deCONZ alarm control panel."""
TYPE = DOMAIN
_device: AncillaryControl
_attr_code_format = CodeFormat.NUMBER
_attr_supported_features = (
AlarmControlPanelEntityFeature.ARM_AWAY
| AlarmControlPanelEntityFeature.ARM_HOME
| AlarmControlPanelEntityFeatur... | illaryControl)
and sensor.unique_id not in gateway.entities[DOMAIN]
and (
alarm_system := get_alarm_system_for_unique_id(
gateway, sensor.unique_id
)
)
is not None
):
... | 135 | 135 | 453 | 18 | 117 | sti0/homeassistant-core | homeassistant/components/deconz/alarm_control_panel.py | Python | DeconzAlarmControlPanel | DeconzAlarmControlPanel | 117 | 175 | 117 | 117 | f1bd62922586027933e9a745100b52aed7396fbf | bigcode/the-stack | train |
363111b2d86a49388bfe51b0 | train | function | def get_alarm_system_for_unique_id(
gateway: DeconzGateway, unique_id: str
) -> AlarmSystem | None:
"""Retrieve alarm system unique ID is registered to."""
for alarm_system in gateway.api.alarmsystems.values():
if unique_id in alarm_system.devices:
return alarm_system
return None
| def get_alarm_system_for_unique_id(
gateway: DeconzGateway, unique_id: str
) -> AlarmSystem | None:
| """Retrieve alarm system unique ID is registered to."""
for alarm_system in gateway.api.alarmsystems.values():
if unique_id in alarm_system.devices:
return alarm_system
return None
| _DELAY: STATE_ALARM_PENDING,
ANCILLARY_CONTROL_EXIT_DELAY: STATE_ALARM_PENDING,
ANCILLARY_CONTROL_IN_ALARM: STATE_ALARM_TRIGGERED,
}
def get_alarm_system_for_unique_id(
gateway: DeconzGateway, unique_id: str
) -> AlarmSystem | None:
| 64 | 64 | 70 | 28 | 36 | sti0/homeassistant-core | homeassistant/components/deconz/alarm_control_panel.py | Python | get_alarm_system_for_unique_id | get_alarm_system_for_unique_id | 56 | 63 | 56 | 58 | 556938722e2d31324a53f0f8692da89083acbd68 | bigcode/the-stack | train |
8440e47b7ce86e0f886babb0 | train | function | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the deCONZ alarm control panel devices.
Alarm control panels are based on the same device class as sensors in deCONZ.
"""
gateway = get_gateway_from_con... | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
| """Set up the deCONZ alarm control panel devices.
Alarm control panels are based on the same device class as sensors in deCONZ.
"""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
@callback
def async_add_alarm_control_panel(
sensors: lis... | unique_id: str
) -> AlarmSystem | None:
"""Retrieve alarm system unique ID is registered to."""
for alarm_system in gateway.api.alarmsystems.values():
if unique_id in alarm_system.devices:
return alarm_system
return None
async def async_setup_entry(
hass: HomeAssistant,
config_e... | 86 | 86 | 287 | 32 | 53 | sti0/homeassistant-core | homeassistant/components/deconz/alarm_control_panel.py | Python | async_setup_entry | async_setup_entry | 66 | 114 | 66 | 70 | ecb8f33461c74f70c08f2561a1319710c271c23c | bigcode/the-stack | train |
fdbb24f140a8321b0dc9a483 | train | function | def readme():
"""Print long description."""
with open("README.md") as f:
return f.read()
| def readme():
| """Print long description."""
with open("README.md") as f:
return f.read()
| """Setup module for ZHAQuirks."""
from setuptools import find_packages, setup
VERSION = "0.0.58"
def readme():
| 31 | 64 | 25 | 4 | 27 | geoffreylagaisse/zha-device-handlers | setup.py | Python | readme | readme | 8 | 11 | 8 | 8 | 193c683ed705d9fc12dad1143f3db8c4456697cf | bigcode/the-stack | train |
8b4ca254815bb877bad336f1 | train | class | class TestAgeInYears:
def test_when_no_age_or_birthday(self):
assert age_in_years(Dataset()) == ''
def test_when_patient_age(self):
dicom = Dataset()
age = '100Y'
dicom.update({'PatientAge': age})
assert age_in_years(dicom) == age
def test_when_patient_birth_date(... | class TestAgeInYears:
| def test_when_no_age_or_birthday(self):
assert age_in_years(Dataset()) == ''
def test_when_patient_age(self):
dicom = Dataset()
age = '100Y'
dicom.update({'PatientAge': age})
assert age_in_years(dicom) == age
def test_when_patient_birth_date(self):
expected... | """Unit tests for dicom_utils module."""
from pydicom import Dataset
from dicomsorter.dicom_utils import age_in_years
class TestAgeInYears:
| 35 | 64 | 176 | 6 | 28 | suever/dicomsorter | tests/test_dicom_utils.py | Python | TestAgeInYears | TestAgeInYears | 7 | 36 | 7 | 8 | bd484398cc442bb832c2628287559b91f85a6599 | bigcode/the-stack | train |
4c25bebe0a5b7fa392bd5538 | train | class | @dataclass
class PredictionOutput:
answers: List[PredictionAnswer]
no_ans_gap: float
question: str
def __post_init__(self):
self.answers = [PredictionAnswer(**ans) for ans in self.answers]
def as_dict(self):
return asdict(self)
| @dataclass
class PredictionOutput:
| answers: List[PredictionAnswer]
no_ans_gap: float
question: str
def __post_init__(self):
self.answers = [PredictionAnswer(**ans) for ans in self.answers]
def as_dict(self):
return asdict(self)
| meta: Dict
offset_end: int
offset_end_in_doc: int
offset_start: int
offset_start_in_doc: int
probability: float
score: float
def get_answer(self) -> str:
return self.answer
@dataclass
class PredictionOutput:
| 64 | 64 | 63 | 7 | 56 | lmbaker/crows | src/prediction/prediction_format.py | Python | PredictionOutput | PredictionOutput | 20 | 30 | 20 | 21 | 4e8786be5724e7339e72176ab214d0079e8411e4 | bigcode/the-stack | train |
124afa18077222784a426f84 | train | class | @dataclass
class PredictionAnswer:
answer: str
context: str
document_id: str
meta: Dict
offset_end: int
offset_end_in_doc: int
offset_start: int
offset_start_in_doc: int
probability: float
score: float
def get_answer(self) -> str:
return self.answer
| @dataclass
class PredictionAnswer:
| answer: str
context: str
document_id: str
meta: Dict
offset_end: int
offset_end_in_doc: int
offset_start: int
offset_start_in_doc: int
probability: float
score: float
def get_answer(self) -> str:
return self.answer
| from dataclasses import dataclass, asdict
from typing import Dict, List
@dataclass
class PredictionAnswer:
| 24 | 64 | 80 | 7 | 16 | lmbaker/crows | src/prediction/prediction_format.py | Python | PredictionAnswer | PredictionAnswer | 4 | 18 | 4 | 5 | 4fc5e6fc58492fb83ea5ab05aff42f401b9f567c | bigcode/the-stack | train |
f821d1920d8b1f079c972cf1 | train | function | def assert_merge_protocol(tnfm_ids, message):
"""Merge should output an ndict with a field for each id
in its transform set."""
assert set(tnfm_ids) == set(message.keys())
| def assert_merge_protocol(tnfm_ids, message):
| """Merge should output an ndict with a field for each id
in its transform set."""
assert set(tnfm_ids) == set(message.keys())
| assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
def assert_sort_unframe_protocol(event):
"""Same as above."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
def assert_merge_protocol(tnfm_ids, message):
| 64 | 64 | 45 | 11 | 52 | aidoom/zipline | zipline/gens/utils.py | Python | assert_merge_protocol | assert_merge_protocol | 78 | 81 | 78 | 78 | 0860866c47badb1a8c59c8054a412c0acfcb62d0 | bigcode/the-stack | train |
3ef29ab1ac84a6b991127c82 | train | function | def assert_datasource_unframe_protocol(event):
"""Assert that an event is valid output of zp.DATASOURCE_UNFRAME."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
| def assert_datasource_unframe_protocol(event):
| """Assert that an event is valid output of zp.DATASOURCE_UNFRAME."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
| assert_datasource_protocol(event)
assert event.type == DATASOURCE_TYPE.TRADE
assert isinstance(event.sid, int)
assert isinstance(event.price, numbers.Real)
assert isinstance(event.volume, numbers.Integral)
assert isinstance(event.dt, datetime)
def assert_datasource_unframe_protocol(event):
| 64 | 64 | 47 | 9 | 55 | aidoom/zipline | zipline/gens/utils.py | Python | assert_datasource_unframe_protocol | assert_datasource_unframe_protocol | 60 | 63 | 60 | 60 | 08c52fb40c049c05d0d6758e5cad8bfd451ba938 | bigcode/the-stack | train |
3e0c4ab360766cd7cec8d7a1 | train | function | def hash_args(*args, **kwargs):
"""Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
kwarg_string = '_'.join([str(key) + '=' + str(value)
for key, value in kwargs.iteritems()])
combined = ':'.join([arg_string, kwar... | def hash_args(*args, **kwargs):
| """Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
kwarg_string = '_'.join([str(key) + '=' + str(value)
for key, value in kwargs.iteritems()])
combined = ':'.join([arg_string, kwarg_string])
hasher = md5()
... | OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytz
import numbers
from hashlib import md5
from datetime import datetime
from zipline.protocol import DATASOURCE_TYPE
def hash_args(*args, **kwargs):
| 64 | 64 | 101 | 9 | 54 | aidoom/zipline | zipline/gens/utils.py | Python | hash_args | hash_args | 25 | 34 | 25 | 25 | 755ebc276d437aa5994953bc1771fad631dd67b1 | bigcode/the-stack | train |
7f553ab1ce572984a83cac43 | train | function | def assert_sort_protocol(event):
"""Assert that an event is valid input to zp.FEED_FRAME."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
| def assert_sort_protocol(event):
| """Assert that an event is valid input to zp.FEED_FRAME."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
| tegral)
assert isinstance(event.dt, datetime)
def assert_datasource_unframe_protocol(event):
"""Assert that an event is valid output of zp.DATASOURCE_UNFRAME."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
def assert_sort_protocol(event):
| 64 | 64 | 41 | 6 | 57 | aidoom/zipline | zipline/gens/utils.py | Python | assert_sort_protocol | assert_sort_protocol | 66 | 69 | 66 | 66 | f67324f767732d4196a932be713ccec097cd00ad | bigcode/the-stack | train |
e2328e87fbbceed77f2bc775 | train | function | def assert_datasource_protocol(event):
"""Assert that an event meets the protocol for datasource outputs."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
# Done packets have no dt.
if not event.type == DATASOURCE_TYPE.DONE:
assert isinstance(event.dt,... | def assert_datasource_protocol(event):
| """Assert that an event meets the protocol for datasource outputs."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
# Done packets have no dt.
if not event.type == DATASOURCE_TYPE.DONE:
assert isinstance(event.dt, datetime)
assert event.dt.tzin... | '_'.join([str(key) + '=' + str(value)
for key, value in kwargs.iteritems()])
combined = ':'.join([arg_string, kwarg_string])
hasher = md5()
hasher.update(combined)
return hasher.hexdigest()
def assert_datasource_protocol(event):
| 64 | 64 | 81 | 7 | 57 | aidoom/zipline | zipline/gens/utils.py | Python | assert_datasource_protocol | assert_datasource_protocol | 37 | 46 | 37 | 37 | 2d5f8a02c580318aa4557d3a403ce72c2081ed0e | bigcode/the-stack | train |
e38b02b93534125c876bef6b | train | function | def assert_trade_protocol(event):
"""Assert that an event meets the protocol for datasource TRADE outputs."""
assert_datasource_protocol(event)
assert event.type == DATASOURCE_TYPE.TRADE
assert isinstance(event.sid, int)
assert isinstance(event.price, numbers.Real)
assert isinstance(event.volum... | def assert_trade_protocol(event):
| """Assert that an event meets the protocol for datasource TRADE outputs."""
assert_datasource_protocol(event)
assert event.type == DATASOURCE_TYPE.TRADE
assert isinstance(event.sid, int)
assert isinstance(event.price, numbers.Real)
assert isinstance(event.volume, numbers.Integral)
assert is... | (event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
# Done packets have no dt.
if not event.type == DATASOURCE_TYPE.DONE:
assert isinstance(event.dt, datetime)
assert event.dt.tzinfo == pytz.utc
def assert_trade_protocol(event):
| 64 | 64 | 76 | 6 | 57 | aidoom/zipline | zipline/gens/utils.py | Python | assert_trade_protocol | assert_trade_protocol | 49 | 57 | 49 | 49 | 515f4839224b84d98994dcb7278fced2e5d85470 | bigcode/the-stack | train |
b7998a96964d44a9eeaad936 | train | function | def assert_sort_unframe_protocol(event):
"""Same as above."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
| def assert_sort_unframe_protocol(event):
| """Same as above."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
| _id, basestring)
assert event.type in DATASOURCE_TYPE
def assert_sort_protocol(event):
"""Assert that an event is valid input to zp.FEED_FRAME."""
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
def assert_sort_unframe_protocol(event):
| 64 | 64 | 34 | 8 | 55 | aidoom/zipline | zipline/gens/utils.py | Python | assert_sort_unframe_protocol | assert_sort_unframe_protocol | 72 | 75 | 72 | 72 | 677ce7e1552a16ceb1543a913a597418d4613273 | bigcode/the-stack | train |
e54e40277ae973ea1cc28d2f | train | class | class ChecklistStatelet:
"""
This class keeps track of checklist related variables that are used while training a coverage
based semantic parser (or any other kind of transition based constrained decoder). This is
intended to be used within a ``State``.
Parameters
----------
terminal_action... | class ChecklistStatelet:
| """
This class keeps track of checklist related variables that are used while training a coverage
based semantic parser (or any other kind of transition based constrained decoder). This is
intended to be used within a ``State``.
Parameters
----------
terminal_actions : ``torch.Tensor``
... | from typing import Dict
import torch
from allennlp.nn import util
class ChecklistStatelet:
| 21 | 230 | 767 | 5 | 15 | annaproxy/udify-metalearning | allennlp/state_machines/states/checklist_statelet.py | Python | ChecklistStatelet | ChecklistStatelet | 8 | 82 | 8 | 8 | 453c82df4bbeec7c943764a8206d47dcea7d7adc | bigcode/the-stack | train |
58b4f41c1f48c771eb882daa | train | class | class Solution2(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
def heuristic_estimate(board, R, C, expected):
result = 0
for i in xrange(R):
for j in xrange(C):
val = board[... | class Solution2(object):
| def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
def heuristic_estimate(board, R, C, expected):
result = 0
for i in xrange(R):
for j in xrange(C):
val = board[C*i + j]
... | _zero = i*C+j
tmp = list(board)
tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero]
new_board = tuple(tmp)
r2, c2 = expected[board[new_zero]]
r1, c1 = divmod(zero, C)
r0, c0 = ... | 140 | 140 | 468 | 5 | 134 | paperfactory/LeetCode-Solution | Python/sliding-puzzle.py | Python | Solution2 | Solution2 | 61 | 104 | 61 | 61 | d425baaa0f562b94196a8d2823297e5da80ac823 | bigcode/the-stack | train |
9986039df141386a287421f4 | train | class | class Solution(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
def dot(p1, p2):
return p1[0]*p2[0]+p1[1]*p2[1]
def heuristic_estimate(board, R, C, expected):
result = 0
for i in xrange(R):
... | class Solution(object):
| def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
def dot(p1, p2):
return p1[0]*p2[0]+p1[1]*p2[1]
def heuristic_estimate(board, R, C, expected):
result = 0
for i in xrange(R):
for j in... | # Time: O((m * n) * (m * n)!)
# Space: O((m * n) * (m * n)!)
import heapq
import itertools
class Solution(object):
| 44 | 157 | 524 | 4 | 39 | paperfactory/LeetCode-Solution | Python/sliding-puzzle.py | Python | Solution | Solution | 7 | 59 | 7 | 7 | 26e042a0723d25cf7d26f709784d2a3d0661c178 | bigcode/the-stack | train |
cda811013159493e4f80bd9b | train | class | class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
output = ''
for i, start_letter in enumerate(s):
j = len(s) - 1
while(True):
if i > j:
break
if (... | class Solution(object):
| def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
output = ''
for i, start_letter in enumerate(s):
j = len(s) - 1
while(True):
if i > j:
break
if (start_letter == s[j] and... | class Solution(object):
| 4 | 64 | 170 | 4 | 0 | C24054057/leetcode | Longest Palindromic Substring/LongestPalindromicSubstring.py | Python | Solution | Solution | 1 | 19 | 1 | 1 | 1b1ab80215d2f4462cb8ed9c972a161ee75ae858 | bigcode/the-stack | train |
af2cc1751705fd731c0fa61b | train | function | def create_event_source_mapping(
EventSourceArn,
FunctionName,
StartingPosition,
Enabled=True,
BatchSize=100,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Identifies a stream as an event source for a Lambda function. It can be
either an Amazon Kinesis stream or... | def create_event_source_mapping(
EventSourceArn,
FunctionName,
StartingPosition,
Enabled=True,
BatchSize=100,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Identifies a stream as an event source for a Lambda function. It can be
either an Amazon Kinesis stream or an Amazon DynamoDB stream. AWS Lambda
invokes the specified function when records are posted to the stream.
Returns {created: true} if the event source mapping was created and returns
... | }}
else:
log.warning("Alias was not updated")
return {"updated": False}
except ClientError as e:
return {"created": False, "error": __utils__["boto3.get_error"](e)}
def create_event_source_mapping(
EventSourceArn,
FunctionName,
StartingPosition,
Enabled=True,
... | 95 | 96 | 322 | 47 | 48 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | create_event_source_mapping | create_event_source_mapping | 944 | 987 | 944 | 954 | 3684b62279ee2b562fd0a46d5326becfdd6e7450 | bigcode/the-stack | train |
6e8a9223bd3376085943cecb | train | function | def list_function_versions(FunctionName, region=None, key=None, keyid=None, profile=None):
"""
List the versions available for the given function.
Returns list of function versions
CLI Example:
.. code-block:: yaml
versions:
- {...}
- {...}
"""
try:
c... | def list_function_versions(FunctionName, region=None, key=None, keyid=None, profile=None):
| """
List the versions available for the given function.
Returns list of function versions
CLI Example:
.. code-block:: yaml
versions:
- {...}
- {...}
"""
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
vers = []
... | , keyid=keyid, profile=profile)
ret = []
for funcs in __utils__["boto3.paged_call"](conn.list_functions):
ret += funcs["Functions"]
return ret
def list_function_versions(FunctionName, region=None, key=None, keyid=None, profile=None):
| 64 | 64 | 176 | 20 | 43 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | list_function_versions | list_function_versions | 732 | 758 | 732 | 732 | 2e57c3e1b01912beab48ce519797c2b93fabf549 | bigcode/the-stack | train |
e7e80bd1fc1f172e79149242 | train | function | def add_permission(
FunctionName,
StatementId,
Action,
Principal,
SourceArn=None,
SourceAccount=None,
Qualifier=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Add a permission to a lambda function.
Returns {added: true} if the permission was added ... | def add_permission(
FunctionName,
StatementId,
Action,
Principal,
SourceArn=None,
SourceAccount=None,
Qualifier=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Add a permission to a lambda function.
Returns {added: true} if the permission was added and returns
{added: False} if the permission was not added.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.add_permission my_function my_id "lambda:*" \\
... | not updated")
return {"updated": False}
except ClientError as e:
return {"updated": False, "error": __utils__["boto3.get_error"](e)}
def add_permission(
FunctionName,
StatementId,
Action,
Principal,
SourceArn=None,
SourceAccount=None,
Qualifier=None,
region=None,... | 89 | 90 | 301 | 51 | 38 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | add_permission | add_permission | 579 | 623 | 579 | 591 | 855e22fbdafddd6585ef8bef95a57e7863d8048f | bigcode/the-stack | train |
004a5b6d6ece743d7f8fb859 | train | function | def delete_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
"""
Given a function name and alias name, delete the alias.
Returns {deleted: true} if the alias was deleted and returns
{deleted: false} if the alias was not deleted.
CLI Example:
.. code-block:: bash
... | def delete_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
| """
Given a function name and alias name, delete the alias.
Returns {deleted: true} if the alias was deleted and returns
{deleted: false} if the alias was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.delete_alias myfunction myalias
"""
try:
... | .warning("Alias was not created")
return {"created": False}
except ClientError as e:
return {"created": False, "error": __utils__["boto3.get_error"](e)}
def delete_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
| 63 | 64 | 167 | 21 | 42 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | delete_alias | delete_alias | 803 | 823 | 803 | 803 | 9e70d4fe1799a046b70007a15370de7caccdba89 | bigcode/the-stack | train |
9dcb5709c0c0cd3852eacd06 | train | function | def describe_event_source_mapping(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given an event source mapping ID or an event source ARN and FunctionName,
obtain the current settings of that mapping.
Returns a dict... | def describe_event_source_mapping(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Given an event source mapping ID or an event source ARN and FunctionName,
obtain the current settings of that mapping.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_event_source_mapping uuid
"""
ids =... | region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in desc:
return desc
return {"exists": bool(desc.get("event_source_mapping"))}
def describe_event_source_mapping(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyi... | 86 | 86 | 287 | 39 | 47 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | describe_event_source_mapping | describe_event_source_mapping | 1,121 | 1,166 | 1,121 | 1,129 | 9d0e305287aacf9ffc7cd901d803fec1f435892c | bigcode/the-stack | train |
04c5ecfab0ca632472662428 | train | function | def __virtual__():
"""
Only load if boto libraries exist and if boto libraries are greater than
a given version.
"""
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce1... | def __virtual__():
| """
Only load if boto libraries exist and if boto libraries are greater than
a given version.
"""
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
# b... | ocore_version
logging.getLogger("boto").setLevel(logging.CRITICAL)
logging.getLogger("boto3").setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
| 64 | 64 | 160 | 5 | 58 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | __virtual__ | __virtual__ | 111 | 122 | 111 | 111 | a4621e54426bfbeb1df97d0734f2b92736c93ddc | bigcode/the-stack | train |
e1d321203b804a0491f78c93 | train | function | def describe_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
"""
Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_ali... | def describe_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
| """
Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_alias myalias
"""
try:
alias = _find_alias(
FunctionName, Name... | id=keyid, profile=profile
)
return {"exists": bool(alias)}
except ClientError as e:
return {"error": __utils__["boto3.get_error"](e)}
def describe_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
| 63 | 64 | 178 | 21 | 42 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | describe_alias | describe_alias | 875 | 899 | 875 | 875 | 60f8ccd37e88afd627df044de831fa2a230408d8 | bigcode/the-stack | train |
affb99f3f7b8bd0da9bac0c4 | train | function | def update_alias(
FunctionName,
Name,
FunctionVersion=None,
Description=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Update the named alias to the configuration.
Returns {updated: true} if the alias was updated and returns
{updated: False} if the alias w... | def update_alias(
FunctionName,
Name,
FunctionVersion=None,
Description=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Update the named alias to the configuration.
Returns {updated: true} if the alias was updated and returns
{updated: False} if the alias was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST
"""
try:
c... | alias.get(k) for k in keys}}
else:
return {"alias": None}
except ClientError as e:
return {"error": __utils__["boto3.get_error"](e)}
def update_alias(
FunctionName,
Name,
FunctionVersion=None,
Description=None,
region=None,
key=None,
keyid=None,
profile=N... | 80 | 81 | 270 | 38 | 42 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | update_alias | update_alias | 902 | 941 | 902 | 911 | 04eff5f4bfee4d3baed3faf61fe2fe609af06cc8 | bigcode/the-stack | train |
b5dfaadb00d5f9b29ee91715 | train | function | def __init__(opts):
if HAS_BOTO:
__utils__["boto3.assign_funcs"](__name__, "lambda")
| def __init__(opts):
| if HAS_BOTO:
__utils__["boto3.assign_funcs"](__name__, "lambda")
| 1.5.2 is required due to lambda environment variables
return salt.utils.versions.check_boto_reqs(
boto_ver="2.8.0", boto3_ver="1.2.5", botocore_ver="1.5.2"
)
def __init__(opts):
| 64 | 64 | 28 | 6 | 58 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | __init__ | __init__ | 125 | 127 | 125 | 125 | d44a1414c60228264a20a944e1cdd19bbb14c378 | bigcode/the-stack | train |
19c036d9723b76dc51f47969 | train | function | def create_function(
FunctionName,
Runtime,
Role,
Handler,
ZipFile=None,
S3Bucket=None,
S3Key=None,
S3ObjectVersion=None,
Description="",
Timeout=3,
MemorySize=128,
Publish=False,
WaitForRole=False,
RoleRetries=5,
region=None,
key=None,
keyid=None,
... | def create_function(
FunctionName,
Runtime,
Role,
Handler,
ZipFile=None,
S3Bucket=None,
S3Key=None,
S3ObjectVersion=None,
Description="",
Timeout=3,
MemorySize=128,
Publish=False,
WaitForRole=False,
RoleRetries=5,
region=None,
key=None,
keyid=None,
... | """
.. versionadded:: 2017.7.0
Given a valid config, create a function.
Environment
The parent object that contains your environment's configuration
settings. This is a dictionary of the form:
.. code-block:: python
{"Variables": {"VariableName": "VariableValue"}}... | SaltInvocationError("VpcConfig must be a dict.")
sns = [
__salt__["boto_vpc.get_resource_id"](
"subnet", s, region=region, key=key, keyid=keyid, profile=profile
).get("id")
for s in conf.pop("SubnetNames", [])
]
sgs = [
__salt__["boto_secgroup.get_group_id"](
... | 256 | 256 | 934 | 100 | 155 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | create_function | create_function | 208 | 332 | 208 | 229 | a903bd4bf44b65d5fe4ed735c47c581657383e82 | bigcode/the-stack | train |
fa76d704e92fe9b7a3c2bf30 | train | function | def get_event_source_mapping_ids(
EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None
):
"""
Given an event source and function name, return a list of mapping IDs
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.get_event_source_mapping_ids arn:::: myf... | def get_event_source_mapping_ids(
EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None
):
| """
Given an event source and function name, return a list of mapping IDs
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.get_event_source_mapping_ids arn:::: myfunction
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
mappings ... | return {"created": False}
except ClientError as e:
return {"created": False, "error": __utils__["boto3.get_error"](e)}
def get_event_source_mapping_ids(
EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None
):
| 63 | 64 | 194 | 29 | 34 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | get_event_source_mapping_ids | get_event_source_mapping_ids | 990 | 1,015 | 990 | 992 | ba7dcb99de38101c0af951a725b3768c7a60ac1d | bigcode/the-stack | train |
2d9eea80d6e311006ed516e9 | train | function | def function_exists(FunctionName, region=None, key=None, keyid=None, profile=None):
"""
Given a function name, check to see if the given function name exists.
Returns True if the given function exists and returns False if the given
function does not exist.
CLI Example:
.. code-block:: bash
... | def function_exists(FunctionName, region=None, key=None, keyid=None, profile=None):
| """
Given a function name, check to see if the given function name exists.
Returns True if the given function exists and returns False if the given
function does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.function_exists myfunction
"""
try:
... | )
for funcs in __utils__["boto3.paged_call"](conn.list_functions):
for func in funcs["Functions"]:
if func["FunctionName"] == name:
return func
return None
def function_exists(FunctionName, region=None, key=None, keyid=None, profile=None):
| 64 | 64 | 144 | 19 | 44 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | function_exists | function_exists | 143 | 162 | 143 | 143 | f8941b82de94edc9eb9c72205914d7d8a305ad2d | bigcode/the-stack | train |
2983a463a17a99759611c0ef | train | function | def update_function_config(
FunctionName,
Role=None,
Handler=None,
Description=None,
Timeout=None,
MemorySize=None,
region=None,
key=None,
keyid=None,
profile=None,
VpcConfig=None,
WaitForRole=False,
RoleRetries=5,
Environment=None,
):
"""
.. versionadded:... | def update_function_config(
FunctionName,
Role=None,
Handler=None,
Description=None,
Timeout=None,
MemorySize=None,
region=None,
key=None,
keyid=None,
profile=None,
VpcConfig=None,
WaitForRole=False,
RoleRetries=5,
Environment=None,
):
| """
.. versionadded:: 2017.7.0
Update the named lambda function to the configuration.
Environment
The parent object that contains your environment's configuration
settings. This is a dictionary of the form:
.. code-block:: python
{"Variables": {"VariableName": "Va... | =key, keyid=keyid, profile=profile)
if func:
keys = (
"FunctionName",
"Runtime",
"Role",
"Handler",
"CodeSha256",
"CodeSize",
"Description",
"Timeout",
"Mem... | 203 | 204 | 682 | 70 | 133 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | update_function_config | update_function_config | 400 | 504 | 400 | 415 | 3d97f68d586aa5b789ba45b68a1d88e3a24b37fd | bigcode/the-stack | train |
52550bcc69773b34b693b571 | train | function | def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None):
"""
Given a function name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_function myfunction
"""
... | def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None):
| """
Given a function name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_function myfunction
"""
try:
func = _find_function(FunctionName, region=region, key=key, keyid=keyid, ... | conn.delete_function(FunctionName=FunctionName)
return {"deleted": True}
except ClientError as e:
return {"deleted": False, "error": __utils__["boto3.get_error"](e)}
def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None):
| 63 | 64 | 213 | 19 | 44 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | describe_function | describe_function | 361 | 397 | 361 | 361 | 7aece60e0dac7a579bca9a648504d5f6115282ec | bigcode/the-stack | train |
e0c2fe37e407dc5ae125397e | train | function | def create_alias(
FunctionName,
Name,
FunctionVersion,
Description="",
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given a valid config, create an alias to a function.
Returns {created: true} if the alias was created and returns
{created: False} if the alias ... | def create_alias(
FunctionName,
Name,
FunctionVersion,
Description="",
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Given a valid config, create an alias to a function.
Returns {created: true} if the alias was created and returns
{created: False} if the alias was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.create_alias my_function my_alias $LATEST "An alias"
""... | log.warning("No versions found")
return {"Versions": vers}
except ClientError as e:
return {"error": __utils__["boto3.get_error"](e)}
def create_alias(
FunctionName,
Name,
FunctionVersion,
Description="",
region=None,
key=None,
keyid=None,
profile=None,
):... | 75 | 76 | 255 | 37 | 38 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | create_alias | create_alias | 761 | 800 | 761 | 770 | e28cbc3210a00913136590e4b9a7f45cbfc5c500 | bigcode/the-stack | train |
62998a5c0b31207cd4be054f | train | function | def event_source_mapping_exists(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given an event source mapping ID or an event source ARN and FunctionName,
check whether the mapping exists.
Returns True if the given a... | def event_source_mapping_exists(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Given an event source mapping ID or an event source ARN and FunctionName,
check whether the mapping exists.
Returns True if the given alias exists and returns False if the given
alias does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.alias_exists myf... | as e:
return {"deleted": False, "error": __utils__["boto3.get_error"](e)}
def event_source_mapping_exists(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| 63 | 64 | 191 | 39 | 24 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | event_source_mapping_exists | event_source_mapping_exists | 1,083 | 1,118 | 1,083 | 1,091 | 84cd335aadc795c41ecf268c4fb64c595592ef17 | bigcode/the-stack | train |
b5e6e9255069709a1eb6c2f1 | train | function | def delete_event_source_mapping(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given an event source mapping ID or an event source ARN and FunctionName,
delete the event source mapping
Returns {deleted: true} if th... | def delete_event_source_mapping(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Given an event source mapping ID or an event source ARN and FunctionName,
delete the event source mapping
Returns {deleted: true} if the mapping was deleted and returns
{deleted: false} if the mapping was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_lambd... | Arn,
FunctionName=FunctionName,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
def delete_event_source_mapping(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| 72 | 72 | 242 | 39 | 33 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | delete_event_source_mapping | delete_event_source_mapping | 1,050 | 1,080 | 1,050 | 1,058 | 9e24564a7f77116614ad9723dac62109fc033284 | bigcode/the-stack | train |
95778b730bffbca5e851aff2 | train | function | def update_event_source_mapping(
UUID,
FunctionName=None,
Enabled=None,
BatchSize=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Update the event source mapping identified by the UUID.
Returns {updated: true} if the alias was updated and returns
{updated: ... | def update_event_source_mapping(
UUID,
FunctionName=None,
Enabled=None,
BatchSize=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Update the event source mapping identified by the UUID.
Returns {updated: true} if the alias was updated and returns
{updated: False} if the alias was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.update_event_source_mapping uuid FunctionName=new_functio... | TransitionReason",
)
return {"event_source_mapping": {k: desc.get(k) for k in keys}}
else:
return {"event_source_mapping": None}
except ClientError as e:
return {"error": __utils__["boto3.get_error"](e)}
def update_event_source_mapping(
UUID,
FunctionName=... | 100 | 101 | 337 | 41 | 59 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | update_event_source_mapping | update_event_source_mapping | 1,169 | 1,222 | 1,169 | 1,178 | e9a708e2f999545620cf4dbce9caf8fe11d6d55c | bigcode/the-stack | train |
f5fb77cfc102fe8503222799 | train | function | def update_function_code(
FunctionName,
ZipFile=None,
S3Bucket=None,
S3Key=None,
S3ObjectVersion=None,
Publish=False,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Upload the given code to the named lambda function.
Returns {updated: true} if the function w... | def update_function_code(
FunctionName,
ZipFile=None,
S3Bucket=None,
S3Key=None,
S3ObjectVersion=None,
Publish=False,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Upload the given code to the named lambda function.
Returns {updated: true} if the function was updated and returns
{updated: False} if the function was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip
... | "FunctionArn",
"LastModified",
"VpcConfig",
"Environment",
)
return {"updated": True, "function": {k: r.get(k) for k in keys}}
else:
log.warning("Function was not updated")
return {"updated": False}
... | 145 | 146 | 487 | 55 | 90 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | update_function_code | update_function_code | 507 | 576 | 507 | 518 | 9f56cde44686f876235dc1058b9c442a6f86bc2d | bigcode/the-stack | train |
17c46b57c4e23c26ea5bdfbc | train | function | def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith("arn:aws:iam:"):
return name
account_id = __salt__["boto_iam.get_account_id"](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and "region" in profile:
region = profile... | def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
| if name.startswith("arn:aws:iam:"):
return name
account_id = __salt__["boto_iam.get_account_id"](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and "region" in profile:
region = profile["region"]
if region is None:
region = "us-east-1"
return ... | , keyid=keyid, profile=profile)
return {"exists": bool(func)}
except ClientError as e:
return {"error": __utils__["boto3.get_error"](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
| 63 | 64 | 126 | 21 | 42 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | _get_role_arn | _get_role_arn | 165 | 176 | 165 | 165 | b2b22df1881d713f0c51508a8ee016e6962231d0 | bigcode/the-stack | train |
b7f718a739dc61dc5e9444d0 | train | function | def _find_alias(
FunctionName,
Name,
FunctionVersion=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given function name and alias name, find and return matching alias information.
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
a... | def _find_alias(
FunctionName,
Name,
FunctionVersion=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Given function name and alias name, find and return matching alias information.
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
args = {"FunctionName": FunctionName}
if FunctionVersion:
args["FunctionVersion"] = FunctionVersion
for aliases in __utils_... | except ClientError as e:
return {"deleted": False, "error": __utils__["boto3.get_error"](e)}
def _find_alias(
FunctionName,
Name,
FunctionVersion=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| 63 | 64 | 151 | 35 | 28 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | _find_alias | _find_alias | 826 | 848 | 826 | 834 | 893884ba57060d84bf82859f99f7d58b5b95d43a | bigcode/the-stack | train |
475e45621bcca1e29ecfbbbd | train | function | def list_functions(region=None, key=None, keyid=None, profile=None):
"""
List all Lambda functions visible in the current scope.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.list_functions
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | def list_functions(region=None, key=None, keyid=None, profile=None):
| """
List all Lambda functions visible in the current scope.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.list_functions
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = []
for funcs in __utils__["boto3.paged_call"](conn.list_fun... | __["boto3.get_error"](e)
if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException":
return {"permissions": None}
return {"permissions": None, "error": err}
def list_functions(region=None, key=None, keyid=None, profile=None):
| 64 | 64 | 109 | 16 | 48 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | list_functions | list_functions | 713 | 729 | 713 | 713 | 2341a9e4f6e09986aeb740a0d3466d69bdc6acf0 | bigcode/the-stack | train |
e360bd7de3f47d8c8c6fb3a7 | train | function | def alias_exists(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
"""
Given a function name and alias name, check to see if the given alias exists.
Returns True if the given alias exists and returns False if the given
alias does not exist.
CLI Example:
.. code-block:: bas... | def alias_exists(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
| """
Given a function name and alias name, check to see if the given alias exists.
Returns True if the given alias exists and returns False if the given
alias does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.alias_exists myfunction myalias
"""
try:... | utils__["boto3.paged_call"](conn.list_aliases, **args):
for alias in aliases.get("Aliases"):
if alias["Name"] == Name:
return alias
return None
def alias_exists(FunctionName, Name, region=None, key=None, keyid=None, profile=None):
| 64 | 64 | 156 | 21 | 42 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | alias_exists | alias_exists | 851 | 872 | 851 | 851 | db8df783d43e0a182a48e81c1eb73826d047dae4 | bigcode/the-stack | train |
e1f7df7086468ca5e1345711 | train | function | def _resolve_vpcconfig(conf, region=None, key=None, keyid=None, profile=None):
if isinstance(conf, str):
conf = salt.utils.json.loads(conf)
if not conf:
return None
if not isinstance(conf, dict):
raise SaltInvocationError("VpcConfig must be a dict.")
sns = [
__salt__["bot... | def _resolve_vpcconfig(conf, region=None, key=None, keyid=None, profile=None):
| if isinstance(conf, str):
conf = salt.utils.json.loads(conf)
if not conf:
return None
if not isinstance(conf, dict):
raise SaltInvocationError("VpcConfig must be a dict.")
sns = [
__salt__["boto_vpc.get_resource_id"](
"subnet", s, region=region, key=key, keyid... | aws:iam::{}:role/{}".format(account_id, name)
def _filedata(infile):
with salt.utils.files.fopen(infile, "rb") as f:
return f.read()
def _resolve_vpcconfig(conf, region=None, key=None, keyid=None, profile=None):
| 64 | 64 | 212 | 21 | 43 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | _resolve_vpcconfig | _resolve_vpcconfig | 184 | 205 | 184 | 184 | c8896a0d6f9e87e2b1e43fb3e65d20dcef8f4d12 | bigcode/the-stack | train |
72f56aa1e4b5144f31768175 | train | function | def remove_permission(
FunctionName,
StatementId,
Qualifier=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Remove a permission from a lambda function.
Returns {removed: true} if the permission was removed and returns
{removed: False} if the permission was not ... | def remove_permission(
FunctionName,
StatementId,
Qualifier=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| """
Remove a permission from a lambda function.
Returns {removed: true} if the permission was removed and returns
{removed: False} if the permission was not removed.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.remove_permission my_function my_id
"""
try:
... | except ClientError as e:
return {"updated": False, "error": __utils__["boto3.get_error"](e)}
def remove_permission(
FunctionName,
StatementId,
Qualifier=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| 63 | 64 | 204 | 35 | 28 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | remove_permission | remove_permission | 626 | 657 | 626 | 634 | ba4ec40aa0e7bce77436975beb53a7f8d0cb9066 | bigcode/the-stack | train |
ea12ce4074b1b46d1f82046c | train | function | def _filedata(infile):
with salt.utils.files.fopen(infile, "rb") as f:
return f.read()
| def _filedata(infile):
| with salt.utils.files.fopen(infile, "rb") as f:
return f.read()
| =profile
)
if profile and "region" in profile:
region = profile["region"]
if region is None:
region = "us-east-1"
return "arn:aws:iam::{}:role/{}".format(account_id, name)
def _filedata(infile):
| 64 | 64 | 28 | 7 | 57 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | _filedata | _filedata | 179 | 181 | 179 | 179 | 4f8f521ab6954e38a183d0ffcfbd2e54df49288d | bigcode/the-stack | train |
ac6dbc6d923cc5ddfda2f23c | train | function | def _find_function(name, region=None, key=None, keyid=None, profile=None):
"""
Given function name, find and return matching Lambda information.
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
for funcs in __utils__["boto3.paged_call"](conn.list_functions):
for fu... | def _find_function(name, region=None, key=None, keyid=None, profile=None):
| """
Given function name, find and return matching Lambda information.
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
for funcs in __utils__["boto3.paged_call"](conn.list_functions):
for func in funcs["Functions"]:
if func["FunctionName"] == name:
... | 2.5", botocore_ver="1.5.2"
)
def __init__(opts):
if HAS_BOTO:
__utils__["boto3.assign_funcs"](__name__, "lambda")
def _find_function(name, region=None, key=None, keyid=None, profile=None):
| 64 | 64 | 103 | 19 | 45 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | _find_function | _find_function | 130 | 140 | 130 | 130 | 6ecdd625eab74c154a84bc9bb0036366f5b9e255 | bigcode/the-stack | train |
53aae5432efd61ba3127fd72 | train | function | def _get_ids(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
if UUID:
if EventSourceArn or FunctionName:
raise SaltInvocationError(
"Either UUID must be specified, or "
"EventSourc... | def _get_ids(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| if UUID:
if EventSourceArn or FunctionName:
raise SaltInvocationError(
"Either UUID must be specified, or "
"EventSourceArn and FunctionName must be provided."
)
return [UUID]
else:
if not EventSourceArn or not FunctionName:
... | mappings
except ClientError as e:
return {"error": __utils__["boto3.get_error"](e)}
def _get_ids(
UUID=None,
EventSourceArn=None,
FunctionName=None,
region=None,
key=None,
keyid=None,
profile=None,
):
| 63 | 64 | 178 | 38 | 25 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | _get_ids | _get_ids | 1,018 | 1,047 | 1,018 | 1,026 | ed6c528229490d005a3a8544e932436ea9774712 | bigcode/the-stack | train |
8b724e2085301a2862634cf4 | train | function | def get_permissions(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
"""
Get resource permissions for the given lambda function
Returns dictionary of permissions, by statement ID
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.get_permissions my_... | def get_permissions(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
| """
Get resource permissions for the given lambda function
Returns dictionary of permissions, by statement ID
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.get_permissions my_function
permissions: {...}
"""
try:
conn = _get_conn(region=region, key=k... | try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if Qualifier is not None:
kwargs["Qualifier"] = Qualifier
conn.remove_permission(FunctionName=FunctionName, StatementId=StatementId, **kwargs)
return {"updated": True}
exce... | 125 | 126 | 423 | 23 | 102 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | get_permissions | get_permissions | 660 | 710 | 660 | 660 | 9cbcd753bf78e51aed134d362f14e2acc6fc99eb | bigcode/the-stack | train |
5703c312c2d3974109bf0734 | train | function | def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
"""
Given a function name and optional version qualifier, delete it.
Returns {deleted: true} if the function was deleted and returns
{deleted: false} if the function was not deleted.
CLI Example:
... | def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
| """
Given a function name and optional version qualifier, delete it.
Returns {deleted: true} if the function was deleted and returns
{deleted: false} if the function was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.delete_function myfunction
"""
... | Function was not created")
return {"created": False}
except ClientError as e:
return {"created": False, "error": __utils__["boto3.get_error"](e)}
def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
| 63 | 64 | 186 | 23 | 40 | major0/salt-aws-extension | src/saltext/aws/modules/boto_lambda.py | Python | delete_function | delete_function | 335 | 358 | 335 | 335 | 91f52ba266447915f8456ef5f21bfed7416f9a3d | bigcode/the-stack | train |
cd5c7f17b3a0c6918e679274 | train | class | class SequenceProcessor(object):
"""Process given input into Sequences.
"""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor.
"""
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
se... | class SequenceProcessor(object):
| """Process given input into Sequences.
"""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor.
"""
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = ProjectLogger... | # -*- coding: utf-8 -*-
"""
This module handles breaking down text into Sequence objects, which are
collections of at most four words.
The SequenceProcessor requires a database reader/writer to be initialized.
The most interesting method to the user is the process() method. This method
expects a single Sentence object... | 142 | 256 | 1,537 | 5 | 137 | Wordseer/wordseer | app/preprocessor/sequenceprocessor.py | Python | SequenceProcessor | SequenceProcessor | 24 | 208 | 24 | 24 | 9ba3725a9e7b8365abf97c4e90a4958d90b89e82 | bigcode/the-stack | train |
dae8466845d5e16a7e81808e | train | function | def join_words(words, attr):
"""Join either lemmas or surface words from a list of `WordInSentence`
objects.
:param list words: A list of WordInSentence objects.
:param str attr: Either sequenceprocessor.LEMMA to combine lemmas or
sequenceprocessor.WORD to combine words.
:return str: The co... | def join_words(words, attr):
| """Join either lemmas or surface words from a list of `WordInSentence`
objects.
:param list words: A list of WordInSentence objects.
:param str attr: Either sequenceprocessor.LEMMA to combine lemmas or
sequenceprocessor.WORD to combine words.
:return str: The combined sentence.
"""
... | _id": sentence.document_id,
"sequence": lemmatized_phrase_nostops,
"is_lemmatized": True,
"has_function_words": False,
"all_function_words": False,
"words": word_list_nostops})
return sequences
def join_words(words, attr):
| 64 | 64 | 131 | 7 | 56 | Wordseer/wordseer | app/preprocessor/sequenceprocessor.py | Python | join_words | join_words | 210 | 228 | 210 | 210 | 20e575e9723bb5a4061bbc0d351168bb73c28a3d | bigcode/the-stack | train |
32111510a978479d54c6bf8f | train | function | def convert_to_ascii(string):
return unidecode(string)
| def convert_to_ascii(string):
| return unidecode(string)
| [_pad, _start, _eos] + list(_special) + list(_punctuation) + list(_letters)
)
FORCE_ALIGNMENT_SYMBOLS = (
[_pad, _start, _eos] + list(_special) + list(_small_letters)
)
def convert_to_ascii(string):
| 64 | 64 | 13 | 6 | 58 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | convert_to_ascii | convert_to_ascii | 27 | 28 | 27 | 27 | 178f3799616ea408bb6f4cb25078dc42a8155a75 | bigcode/the-stack | train |
08d8184d4ce34e6b9a3159dd | train | class | class TextIDS:
def __init__(
self,
pad_to: int = 8,
understand_punct: bool = True,
normalizer=None,
sentence_tokenizer=None,
true_case_model=None,
):
self.normalizer = normalizer
self.pad_to = pad_to
self.sentence_tokenizer = sentence_token... | class TextIDS:
| def __init__(
self,
pad_to: int = 8,
understand_punct: bool = True,
normalizer=None,
sentence_tokenizer=None,
true_case_model=None,
):
self.normalizer = normalizer
self.pad_to = pad_to
self.sentence_tokenizer = sentence_tokenizer
se... | _sparse_correlation_matrix(A):
scaler = StandardScaler(with_mean=False)
scaled_A = scaler.fit_transform(A)
corr_matrix = (1 / scaled_A.shape[0]) * (scaled_A.T @ scaled_A)
return corr_matrix
def filter_splitted(s, t, threshold=0.001):
bow = CountVectorizer(token_pattern='[A-Za-z0-9]+').fit([s])
... | 217 | 217 | 724 | 4 | 212 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | TextIDS | TextIDS | 67 | 163 | 67 | 67 | 55140f2cb3abc8c757f94fb6405011f95a6b03ca | bigcode/the-stack | train |
3bd2f6e5af06121f0e6bb33f | train | function | def compute_sparse_correlation_matrix(A):
scaler = StandardScaler(with_mean=False)
scaled_A = scaler.fit_transform(A)
corr_matrix = (1 / scaled_A.shape[0]) * (scaled_A.T @ scaled_A)
return corr_matrix
| def compute_sparse_correlation_matrix(A):
| scaler = StandardScaler(with_mean=False)
scaled_A = scaler.fit_transform(A)
corr_matrix = (1 / scaled_A.shape[0]) * (scaled_A.T @ scaled_A)
return corr_matrix
| """
'ni1996' -> 'ni 1996'
"""
string = re.sub('[A-Za-z]+', lambda ele: ' ' + ele[0] + ' ', string)
return re.sub(r'[ ]+', ' ', string).strip()
def compute_sparse_correlation_matrix(A):
| 64 | 64 | 53 | 8 | 56 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | compute_sparse_correlation_matrix | compute_sparse_correlation_matrix | 43 | 47 | 43 | 43 | a82098b1dceb80aa29b02246590a02c9edfb6b62 | bigcode/the-stack | train |
29400a5ee2aa8b42d7d92462 | train | function | def filter_splitted(s, t, threshold=0.001):
bow = CountVectorizer(token_pattern='[A-Za-z0-9]+').fit([s])
s_bow = bow.transform([s] + t)
score = np.array(compute_sparse_correlation_matrix(s_bow.T).todense())[
0, 1:
]
r = [t[no] for no, s in enumerate(score) if s >= threshold]
return ' '.j... | def filter_splitted(s, t, threshold=0.001):
| bow = CountVectorizer(token_pattern='[A-Za-z0-9]+').fit([s])
s_bow = bow.transform([s] + t)
score = np.array(compute_sparse_correlation_matrix(s_bow.T).todense())[
0, 1:
]
r = [t[no] for no, s in enumerate(score) if s >= threshold]
return ' '.join(r)
| orrelation_matrix(A):
scaler = StandardScaler(with_mean=False)
scaled_A = scaler.fit_transform(A)
corr_matrix = (1 / scaled_A.shape[0]) * (scaled_A.T @ scaled_A)
return corr_matrix
def filter_splitted(s, t, threshold=0.001):
| 64 | 64 | 107 | 15 | 48 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | filter_splitted | filter_splitted | 50 | 57 | 50 | 50 | 82d45300ebd46c6845a19aa722ae86ab2d622a5e | bigcode/the-stack | train |
e53b8dbf4ea4b03db91b8abc | train | function | def put_spacing_num(string):
"""
'ni1996' -> 'ni 1996'
"""
string = re.sub('[A-Za-z]+', lambda ele: ' ' + ele[0] + ' ', string)
return re.sub(r'[ ]+', ' ', string).strip()
| def put_spacing_num(string):
| """
'ni1996' -> 'ni 1996'
"""
string = re.sub('[A-Za-z]+', lambda ele: ' ' + ele[0] + ' ', string)
return re.sub(r'[ ]+', ' ', string).strip()
| S = (
[_pad, _start, _eos] + list(_special) + list(_small_letters)
)
def convert_to_ascii(string):
return unidecode(string)
def collapse_whitespace(string):
return re.sub(_whitespace_re, ' ', string)
def put_spacing_num(string):
| 64 | 64 | 63 | 6 | 58 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | put_spacing_num | put_spacing_num | 35 | 40 | 35 | 35 | 36e8af7fa2271e2525359746c6d9859c6622b472 | bigcode/the-stack | train |
8da6a0869dd3c7a11811bbd6 | train | function | def tts_encode(string: str, vocab, add_eos: bool = True):
r = [vocab.index(c) for c in string]
if add_eos:
r = r + [vocab.index('eos')]
return r
| def tts_encode(string: str, vocab, add_eos: bool = True):
| r = [vocab.index(c) for c in string]
if add_eos:
r = r + [vocab.index('eos')]
return r
| (s_bow.T).todense())[
0, 1:
]
r = [t[no] for no, s in enumerate(score) if s >= threshold]
return ' '.join(r)
def tts_encode(string: str, vocab, add_eos: bool = True):
| 64 | 64 | 55 | 18 | 46 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | tts_encode | tts_encode | 60 | 64 | 60 | 60 | 6f5a741c88bd4cba7d37cc7fdef86af115acd0b5 | bigcode/the-stack | train |
82b7359b39651a9396c884a0 | train | function | def collapse_whitespace(string):
return re.sub(_whitespace_re, ' ', string)
| def collapse_whitespace(string):
| return re.sub(_whitespace_re, ' ', string)
| special) + list(_punctuation) + list(_letters)
)
FORCE_ALIGNMENT_SYMBOLS = (
[_pad, _start, _eos] + list(_special) + list(_small_letters)
)
def convert_to_ascii(string):
return unidecode(string)
def collapse_whitespace(string):
| 64 | 64 | 19 | 6 | 58 | ishine/malaya-speech | malaya_speech/utils/text.py | Python | collapse_whitespace | collapse_whitespace | 31 | 32 | 31 | 31 | f4eb546293c75f35b759a3d9e455ba1ba540047f | bigcode/the-stack | train |
dcdd8e34bb17cf1c20163957 | train | class | class BokehExample(flx.PyComponent):
def init(self):
with flx.HSplit(minsize=300) as self.widget:
self.plot1 = flx.BokehWidget.from_plot(p1, title='Scatter')
with flx.VFix(title='Sine'):
Controls()
with flx.PyWidget(style='overflow-y:auto;', flex=1):... | class BokehExample(flx.PyComponent):
| def init(self):
with flx.HSplit(minsize=300) as self.widget:
self.plot1 = flx.BokehWidget.from_plot(p1, title='Scatter')
with flx.VFix(title='Sine'):
Controls()
with flx.PyWidget(style='overflow-y:auto;', flex=1):
self.plot2 = flx.... | .5, 100)
p2 = figure(tools=TOOLS, sizing_mode='scale_width')
p2.line(t, np.sin(t))
p3 = figure(tools=TOOLS, sizing_mode='scale_width')
p3.line(t, np.cos(t))
class BokehExample(flx.PyComponent):
| 64 | 64 | 110 | 10 | 54 | levinbgu/flexx | flexxamples/howtos/bokehdemo.py | Python | BokehExample | BokehExample | 30 | 40 | 30 | 31 | 467e0fa1dc56e4aa25c719a190f5eb0c6d6cfc28 | bigcode/the-stack | train |
42b9e3c79c3e78f4f8d8a385 | train | class | class Controls(flx.FormLayout):
def init(self):
self.amp = flx.Slider(title='Amplitude', max=2, value=1)
self.freq = flx.Slider(title='Frequency', max=10, value=5)
self.phase = flx.Slider(title='Phase', max=3, value=1)
@flx.reaction
def _update_sine(self):
global window
... | class Controls(flx.FormLayout):
| def init(self):
self.amp = flx.Slider(title='Amplitude', max=2, value=1)
self.freq = flx.Slider(title='Frequency', max=10, value=5)
self.phase = flx.Slider(title='Phase', max=3, value=1)
@flx.reaction
def _update_sine(self):
global window
amp, freq, phase = self.amp... | with flx.VFix(title='Sine'):
Controls()
with flx.PyWidget(style='overflow-y:auto;', flex=1):
self.plot2 = flx.BokehWidget.from_plot(p2)
self.plot3 = flx.BokehWidget.from_plot(p3)
class Controls(flx.FormLayout):
| 67 | 67 | 224 | 7 | 60 | levinbgu/flexx | flexxamples/howtos/bokehdemo.py | Python | Controls | Controls | 43 | 68 | 43 | 44 | 534ceae411a1e8df45296c816d18e48ecc656433 | bigcode/the-stack | train |
1871300fc0fa96341ecda5b0 | train | function | def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'honour.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your... | def main():
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'honour.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH ... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 93 | 3 | 22 | oodennis20/Honours | manage.py | Python | main | main | 7 | 17 | 7 | 7 | baf2ed9310832b462b8a5ae32f21bc990e881417 | bigcode/the-stack | train |
e6744369f5f70ac8752d8eab | train | function | def balanceQueue(buffer, refillLevel=1):
# get the internal queue of the buffer
objectQueue = buffer.getActiveObjectQueue()
numInQueue = len(objectQueue)
print(("-" * 50))
print(("at time=", G.env.now))
# check if the buffer is empty and if yes fill it with 5 parts
if numInQueue == 0:
... | def balanceQueue(buffer, refillLevel=1):
# get the internal queue of the buffer
| objectQueue = buffer.getActiveObjectQueue()
numInQueue = len(objectQueue)
print(("-" * 50))
print(("at time=", G.env.now))
# check if the buffer is empty and if yes fill it with 5 parts
if numInQueue == 0:
print("buffer is starving, I will bring 5 parts")
for i in range(refillLev... | .simulation.imports import Machine, Queue, Exit, Part, EventGenerator
from manpy.simulation.Globals import runSimulation, setWIP, G
# method to check if the buffer is starving and refill it
def balanceQueue(buffer, refillLevel=1):
# get the internal queue of the buffer
| 66 | 66 | 222 | 20 | 45 | datarevenue-berlin/manpy | manpy/simulation/Examples/BalancingABuffer.py | Python | balanceQueue | balanceQueue | 5 | 25 | 5 | 6 | 0c46611a5698a4fa270e0e1b61bc6b73fac945ba | bigcode/the-stack | train |
9acb4dd308797a56897e9c61 | train | function | def main(test=0):
# add all the objects in a list
objectList = [Q, M, E, EV]
# set the length of the experiment
maxSimTime = 100.0
# call the runSimulation giving the objects and the length of the experiment
runSimulation(objectList, maxSimTime)
# calculate metrics
working_ratio = (M.to... | def main(test=0):
# add all the objects in a list
| objectList = [Q, M, E, EV]
# set the length of the experiment
maxSimTime = 100.0
# call the runSimulation giving the objects and the length of the experiment
runSimulation(objectList, maxSimTime)
# calculate metrics
working_ratio = (M.totalWorkingTime / maxSimTime) * 100
# return resul... | Parts = 0
# define predecessors and successors for the objects
Q.defineRouting(successorList=[M])
M.defineRouting(predecessorList=[Q], successorList=[E])
E.defineRouting(predecessorList=[M])
def main(test=0):
# add all the objects in a list
| 64 | 64 | 174 | 16 | 48 | datarevenue-berlin/manpy | manpy/simulation/Examples/BalancingABuffer.py | Python | main | main | 51 | 69 | 51 | 52 | 8a3c66d71d103569b184a2b546156276351a6fed | bigcode/the-stack | train |
d690a8baaa056e4c71199331 | train | class | @dataclass
class DbtCloud:
account_id: int
api_token: str = field(repr=False)
api_base: str = 'https://cloud.getdbt.com/api/v2'
def _construct_headers(self) -> Dict:
return {'Authorization': 'Token %s' % self.api_token}
def _get(self, url_suffix: str, params: Dict = None) -> Dict:
... | @dataclass
class DbtCloud:
| account_id: int
api_token: str = field(repr=False)
api_base: str = 'https://cloud.getdbt.com/api/v2'
def _construct_headers(self) -> Dict:
return {'Authorization': 'Token %s' % self.api_token}
def _get(self, url_suffix: str, params: Dict = None) -> Dict:
url = self.api_base + url_s... | import requests
from dataclasses import dataclass
from dataclasses import field
from typing import Dict
@dataclass
class DbtCloud:
| 29 | 256 | 923 | 8 | 20 | hans2520/py-dbt-cloud | pydbtcloud/client.py | Python | DbtCloud | DbtCloud | 7 | 88 | 7 | 8 | 2b8c309b464d96e732dd118939755ecdb8312c21 | bigcode/the-stack | train |
839e365b72b29f9455ac7d35 | train | class | @dataclass
class DbtCloudResponse:
client: DbtCloud
url_suffix: str
params: Dict = None
response: Dict = None
def __iter__(self):
self._iteration = 0
return self
def __next__(self):
self._iteration += 1
if self._iteration == 1:
return self
i... | @dataclass
class DbtCloudResponse:
| client: DbtCloud
url_suffix: str
params: Dict = None
response: Dict = None
def __iter__(self):
self._iteration = 0
return self
def __next__(self):
self._iteration += 1
if self._iteration == 1:
return self
if self.response.get('status').get('... | , url_suffix, params, response)
def cancel_run(self, run_id: int, params: Dict = None, data: Dict = None):
url_suffix = f"/accounts/{self.account_id}/runs/{run_id}/cancel/"
response = self._post(url_suffix, params, data)
return DbtCloudResponse(self, url_suffix, params, response)
@dataclass... | 87 | 87 | 291 | 9 | 78 | hans2520/py-dbt-cloud | pydbtcloud/client.py | Python | DbtCloudResponse | DbtCloudResponse | 91 | 127 | 91 | 92 | ae3cba0e5af8eab0d0b1345396ea6f99fb996124 | bigcode/the-stack | train |
69a19f327a945e1de061ca05 | train | function | @component
def print_op(msg: str, msg2: Optional[str] = None):
print(f'msg: {msg}, msg2: {msg2}')
| @component
def print_op(msg: str, msg2: Optional[str] = None):
| print(f'msg: {msg}, msg2: {msg2}')
| implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
from kfp.v2 import compiler, dsl
from kfp.v2.dsl import component
@component
def print_op(msg: str, msg2: Optional[str] = None):
| 64 | 64 | 35 | 19 | 44 | boarder7395/pipelines | sdk/python/kfp/v2/compiler_cli_tests/test_data/pipeline_with_nested_loops.py | Python | print_op | print_op | 21 | 23 | 21 | 22 | 929f5413e1bbe3c71d7f16e1a51ff7b0ba023d15 | bigcode/the-stack | train |
a8ae3ac0726839d1e98693f5 | train | function | @dsl.pipeline(name='pipeline-with-nested-loops')
def my_pipeline(loop_parameter: list = [
{
"p_a": [{
"q_a": 1
}, {
"q_a": 2
}],
"p_b": "hello",
},
{
"p_a": [{
"q_a": 11
}, {
"q_a": 22
}],
"p_b": ... | @dsl.pipeline(name='pipeline-with-nested-loops')
def my_pipeline(loop_parameter: list = [
{
"p_a": [{
"q_a": 1
}, {
"q_a": 2
}],
"p_b": "hello",
},
{
"p_a": [{
"q_a": 11
}, {
"q_a": 22
}],
"p_b": ... | with dsl.ParallelFor(loop_parameter) as item:
with dsl.ParallelFor(item.p_a) as item_p_a:
print_op(item_p_a.q_a)
# Nested loop with withItems loop args
with dsl.ParallelFor([1, 2]) as outter_item:
print_op(outter_item)
with dsl.ParallelFor([100, 200, 300]) as inner_item:... | @dsl.pipeline(name='pipeline-with-nested-loops')
def my_pipeline(loop_parameter: list = [
{
"p_a": [{
"q_a": 1
}, {
"q_a": 2
}],
"p_b": "hello",
},
{
"p_a": [{
"q_a": 11
}, {
"q_a": 22
}],
"p_b": ... | 110 | 64 | 213 | 110 | 0 | boarder7395/pipelines | sdk/python/kfp/v2/compiler_cli_tests/test_data/pipeline_with_nested_loops.py | Python | my_pipeline | my_pipeline | 26 | 54 | 26 | 45 | f0caa8a6d5170e027d094ccc5086a4515731a8b5 | bigcode/the-stack | train |
257262a3afa431e13f6dc509 | train | function | def graphql_to_message(message):
if message.get('message_sender') is None:
message['message_sender'] = {}
if message.get('message') is None:
message['message'] = {}
rtn = Message(
text=message.get('message').get('text'),
mentions=[Mention(m.get('entity', {}).get('id'), offset... | def graphql_to_message(message):
| if message.get('message_sender') is None:
message['message_sender'] = {}
if message.get('message') is None:
message['message'] = {}
rtn = Message(
text=message.get('message').get('text'),
mentions=[Mention(m.get('entity', {}).get('id'), offset=m.get('offset'), length=m.get('l... | audio_type')
)
elif _type == 'MessageFile':
return FileAttachment(
url=a.get('url'),
name=a.get('filename'),
is_malicious=a.get('is_malicious'),
uid=a.get('message_file_fbid')
)
else:
return Attachment(
uid=a.get('legacy... | 82 | 82 | 276 | 6 | 76 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_message | graphql_to_message | 131 | 152 | 131 | 131 | 90172b62fc435b4641c5d499fd6d1de380e522bb | bigcode/the-stack | train |
d0bb0b80bedbd2f5773fd73e | train | function | def graphql_response_to_json(content):
content = strip_to_json(content) # Usually only needed in some error cases
try:
j = json.loads(content, cls=ConcatJSONDecoder)
except Exception:
raise FBchatException('Error while parsing JSON: {}'.format(repr(content)))
rtn = [None]*(len(j))
f... | def graphql_response_to_json(content):
| content = strip_to_json(content) # Usually only needed in some error cases
try:
j = json.loads(content, cls=ConcatJSONDecoder)
except Exception:
raise FBchatException('Error while parsing JSON: {}'.format(repr(content)))
rtn = [None]*(len(j))
for x in j:
if 'error_results' i... | )
def graphql_queries_to_json(*queries):
"""
Queries should be a list of GraphQL objects
"""
rtn = {}
for i, query in enumerate(queries):
rtn['q{}'.format(i)] = query.value
return json.dumps(rtn)
def graphql_response_to_json(content):
| 64 | 64 | 161 | 7 | 57 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_response_to_json | graphql_response_to_json | 277 | 299 | 277 | 277 | d303968734961d142045f4f0c9172de2228f5409 | bigcode/the-stack | train |
6e8fc8c702656f7682f5c7dc | train | function | def graphql_to_room(room):
if room.get('image') is None:
room['image'] = {}
c_info = get_customization_info(room)
return Room(
room['thread_key']['thread_fbid'],
participants=set([node['messaging_actor']['id'] for node in room['all_participants']['nodes']]),
nicknames=c_info.... | def graphql_to_room(room):
| if room.get('image') is None:
room['image'] = {}
c_info = get_customization_info(room)
return Room(
room['thread_key']['thread_fbid'],
participants=set([node['messaging_actor']['id'] for node in room['all_participants']['nodes']]),
nicknames=c_info.get('nicknames'),
c... | names'),
color=c_info.get('color'),
emoji=c_info.get('emoji'),
photo=group['image'].get('uri'),
name=group.get('name'),
message_count=group.get('messages_count'),
last_message_timestamp=last_message_timestamp
)
def graphql_to_room(room):
| 64 | 64 | 214 | 6 | 58 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_room | graphql_to_room | 233 | 251 | 233 | 233 | 2b21c44bfd93bd811552f9cb28907e3ff4c62b60 | bigcode/the-stack | train |
a6100616aebca59fed297023 | train | function | def graphql_to_sticker(s):
if not s:
return None
sticker = Sticker(
uid=s['id']
)
if s.get('pack'):
sticker.pack = s['pack'].get('id')
if s.get('sprite_image'):
sticker.is_animated = True
sticker.medium_sprite_image = s['sprite_image'].get('uri')
stick... | def graphql_to_sticker(s):
| if not s:
return None
sticker = Sticker(
uid=s['id']
)
if s.get('pack'):
sticker.pack = s['pack'].get('id')
if s.get('sprite_image'):
sticker.is_animated = True
sticker.medium_sprite_image = s['sprite_image'].get('uri')
sticker.large_sprite_image = s['... | (pc) > 1:
if pc[1].get('participant_id') == uid:
rtn['nickname'] = pc[1].get('nickname')
else:
rtn['own_nickname'] = pc[1].get('nickname')
return rtn
def graphql_to_sticker(s):
| 64 | 64 | 180 | 7 | 56 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_sticker | graphql_to_sticker | 65 | 85 | 65 | 65 | 5d9db8ef233af3f2c5a5d699c6b7ac1eb42eb2a3 | bigcode/the-stack | train |
a89f93d0aca4fe5dc8d374c4 | train | class | class GraphQL(object):
def __init__(self, query=None, doc_id=None, params=None):
if params is None:
params = {}
if query is not None:
self.value = {
'priority': 0,
'q': query,
'query_params': params
}
elif do... | class GraphQL(object):
| def __init__(self, query=None, doc_id=None, params=None):
if params is None:
params = {}
if query is not None:
self.value = {
'priority': 0,
'q': query,
'query_params': params
}
elif doc_id is not None:
... | rtn['q{}'.format(i)] = query.value
return json.dumps(rtn)
def graphql_response_to_json(content):
content = strip_to_json(content) # Usually only needed in some error cases
try:
j = json.loads(content, cls=ConcatJSONDecoder)
except Exception:
raise FBchatException('Error while parsing J... | 184 | 184 | 615 | 5 | 178 | abhisharma404/fbchat | fbchat/graphql.py | Python | GraphQL | GraphQL | 301 | 428 | 301 | 301 | a76cd065c6a35ec4a0fedc867589d665202e194d | bigcode/the-stack | train |
54ea39de718d437eb27fe93e | train | function | def graphql_to_thread(thread):
if thread['thread_type'] == 'GROUP':
return graphql_to_group(thread)
elif thread['thread_type'] == 'ONE_TO_ONE':
if thread.get('big_image_src') is None:
thread['big_image_src'] = {}
c_info = get_customization_info(thread)
participants = ... | def graphql_to_thread(thread):
| if thread['thread_type'] == 'GROUP':
return graphql_to_group(thread)
elif thread['thread_type'] == 'ONE_TO_ONE':
if thread.get('big_image_src') is None:
thread['big_image_src'] = {}
c_info = get_customization_info(thread)
participants = [node['messaging_actor'] for no... | .get('last_name'),
is_friend=user.get('is_viewer_friend'),
gender=GENDERS.get(user.get('gender')),
affinity=user.get('affinity'),
nickname=c_info.get('nickname'),
color=c_info.get('color'),
emoji=c_info.get('emoji'),
own_nickname=c_info.get('own_nickname'),
... | 107 | 107 | 357 | 6 | 101 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_thread | graphql_to_thread | 175 | 212 | 175 | 175 | e1486e4a55182b6d69697f1fddecd30521ff4388 | bigcode/the-stack | train |
57720f7a9e904c76215e8937 | train | function | def graphql_to_user(user):
if user.get('profile_picture') is None:
user['profile_picture'] = {}
c_info = get_customization_info(user)
return User(
user['id'],
url=user.get('url'),
first_name=user.get('first_name'),
last_name=user.get('last_name'),
is_friend=us... | def graphql_to_user(user):
| if user.get('profile_picture') is None:
user['profile_picture'] = {}
c_info = get_customization_info(user)
return User(
user['id'],
url=user.get('url'),
first_name=user.get('first_name'),
last_name=user.get('last_name'),
is_friend=user.get('is_viewer_friend'),... | ')}
if message.get('blob_attachments') is not None:
rtn.attachments = [graphql_to_attachment(attachment) for attachment in message['blob_attachments']]
# TODO: This is still missing parsing:
# message.get('extensible_attachment')
return rtn
def graphql_to_user(user):
| 64 | 64 | 165 | 6 | 57 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_user | graphql_to_user | 154 | 173 | 154 | 154 | 95753ac8906e1f9968c7b2c1702d7ae38aef23a3 | bigcode/the-stack | train |
eb8e079af3524cf82cf7c5f6 | train | function | def graphql_color_to_enum(color):
if color is None:
return None
if len(color) == 0:
return ThreadColor.MESSENGER_BLUE
try:
return ThreadColor('#{}'.format(color[2:].lower()))
except ValueError:
raise FBchatException('Could not get ThreadColor from color: {}'.format(color)... | def graphql_color_to_enum(color):
| if color is None:
return None
if len(color) == 0:
return ThreadColor.MESSENGER_BLUE
try:
return ThreadColor('#{}'.format(color[2:].lower()))
except ValueError:
raise FBchatException('Could not get ThreadColor from color: {}'.format(color))
| end = 0
while end != s_len:
obj, end = self.raw_decode(s, idx=_w(s, end).end())
end = _w(s, end).end()
objs.append(obj)
return objs
# End shameless copy
def graphql_color_to_enum(color):
| 64 | 64 | 75 | 7 | 56 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_color_to_enum | graphql_color_to_enum | 26 | 34 | 26 | 26 | 37e3164d77655ac8662270a9c920b96323b6c9e8 | bigcode/the-stack | train |
a62f76d167ca2cc3672dc676 | train | function | def graphql_queries_to_json(*queries):
"""
Queries should be a list of GraphQL objects
"""
rtn = {}
for i, query in enumerate(queries):
rtn['q{}'.format(i)] = query.value
return json.dumps(rtn)
| def graphql_queries_to_json(*queries):
| """
Queries should be a list of GraphQL objects
"""
rtn = {}
for i, query in enumerate(queries):
rtn['q{}'.format(i)] = query.value
return json.dumps(rtn)
| ('url'),
city=page.get('city').get('name'),
category=page.get('category_type'),
photo=page['profile_picture'].get('uri'),
name=page.get('name'),
message_count=page.get('messages_count')
)
def graphql_queries_to_json(*queries):
| 64 | 64 | 56 | 8 | 56 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_queries_to_json | graphql_queries_to_json | 268 | 275 | 268 | 268 | 01bf5a69982d4b24dc539fb06d548d04844eb3ec | bigcode/the-stack | train |
af03aaf0e66ee741b930fa55 | train | function | def get_customization_info(thread):
if thread is None or thread.get('customization_info') is None:
return {}
info = thread['customization_info']
rtn = {
'emoji': info.get('emoji'),
'color': graphql_color_to_enum(info.get('outgoing_bubble_color'))
}
if thread.get('thread_type... | def get_customization_info(thread):
| if thread is None or thread.get('customization_info') is None:
return {}
info = thread['customization_info']
rtn = {
'emoji': info.get('emoji'),
'color': graphql_color_to_enum(info.get('outgoing_bubble_color'))
}
if thread.get('thread_type') in ('GROUP', 'ROOM') or thread.ge... |
# End shameless copy
def graphql_color_to_enum(color):
if color is None:
return None
if len(color) == 0:
return ThreadColor.MESSENGER_BLUE
try:
return ThreadColor('#{}'.format(color[2:].lower()))
except ValueError:
raise FBchatException('Could not get ThreadColor from c... | 89 | 89 | 298 | 7 | 82 | abhisharma404/fbchat | fbchat/graphql.py | Python | get_customization_info | get_customization_info | 36 | 62 | 36 | 36 | dc7f7acd48274c3c53c9247aabbff24a22803912 | bigcode/the-stack | train |
3dd2c00135df95d0e5ddaeef | train | class | class ConcatJSONDecoder(json.JSONDecoder):
def decode(self, s, _w=WHITESPACE.match):
s_len = len(s)
objs = []
end = 0
while end != s_len:
obj, end = self.raw_decode(s, idx=_w(s, end).end())
end = _w(s, end).end()
objs.append(obj)
return ob... | class ConcatJSONDecoder(json.JSONDecoder):
| def decode(self, s, _w=WHITESPACE.match):
s_len = len(s)
objs = []
end = 0
while end != s_len:
obj, end = self.raw_decode(s, idx=_w(s, end).end())
end = _w(s, end).end()
objs.append(obj)
return objs
| import *
from .utils import *
# Shameless copy from https://stackoverflow.com/a/8730674
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
class ConcatJSONDecoder(json.JSONDecoder):
| 64 | 64 | 87 | 9 | 55 | abhisharma404/fbchat | fbchat/graphql.py | Python | ConcatJSONDecoder | ConcatJSONDecoder | 13 | 23 | 13 | 13 | ee65efe11cfd23c634f3d57314d6b014d8e32396 | bigcode/the-stack | train |
99e823dee997f64b267f3fa7 | train | function | def graphql_to_page(page):
if page.get('profile_picture') is None:
page['profile_picture'] = {}
if page.get('city') is None:
page['city'] = {}
return Page(
page['id'],
url=page.get('url'),
city=page.get('city').get('name'),
category=page.get('category_type'),
... | def graphql_to_page(page):
| if page.get('profile_picture') is None:
page['profile_picture'] = {}
if page.get('city') is None:
page['city'] = {}
return Page(
page['id'],
url=page.get('url'),
city=page.get('city').get('name'),
category=page.get('category_type'),
photo=page['profile... | _mode')),
approval_requests = set(node.get('id') for node in room['thread_queue_metadata'].get('approval_requests', {}).get('nodes')),
join_link = room['joinable_mode'].get('link'),
privacy_mode = bool(room.get('privacy_mode')),
)
def graphql_to_page(page):
| 64 | 64 | 112 | 6 | 58 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_page | graphql_to_page | 253 | 266 | 253 | 253 | b29460f42bea27dc269571743648947fd9a23d18 | bigcode/the-stack | train |
a2ff5a7ec8ec7c4346c156aa | train | function | def graphql_to_attachment(a):
_type = a['__typename']
if _type in ['MessageImage', 'MessageAnimatedImage']:
return ImageAttachment(
original_extension=a.get('original_extension') or (a['filename'].split('-')[0] if a.get('filename') else None),
width=a.get('original_dimensions', {... | def graphql_to_attachment(a):
| _type = a['__typename']
if _type in ['MessageImage', 'MessageAnimatedImage']:
return ImageAttachment(
original_extension=a.get('original_extension') or (a['filename'].split('-')[0] if a.get('filename') else None),
width=a.get('original_dimensions', {}).get('width'),
h... | _image'].get('uri')
sticker.large_sprite_image = s['sprite_image_2x'].get('uri')
sticker.frames_per_row = s.get('frames_per_row')
sticker.frames_per_col = s.get('frames_per_column')
sticker.frame_rate = s.get('frame_rate')
sticker.url = s.get('url')
sticker.width = s.get('width')... | 113 | 113 | 379 | 6 | 106 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_attachment | graphql_to_attachment | 87 | 129 | 87 | 87 | 7aeb6051b17baf937c9842d0c5a1d3d3149ed460 | bigcode/the-stack | train |
fd5ccd79c8c7baa64f19caaa | train | function | def graphql_to_group(group):
if group.get('image') is None:
group['image'] = {}
c_info = get_customization_info(group)
last_message_timestamp = None
if 'last_message' in group:
last_message_timestamp = group['last_message']['nodes'][0]['timestamp_precise']
return Group(
group... | def graphql_to_group(group):
| if group.get('image') is None:
group['image'] = {}
c_info = get_customization_info(group)
last_message_timestamp = None
if 'last_message' in group:
last_message_timestamp = group['last_message']['nodes'][0]['timestamp_precise']
return Group(
group['thread_key']['thread_fbid']... | =user['big_image_src'].get('uri'),
message_count=thread.get('messages_count'),
last_message_timestamp=last_message_timestamp
)
else:
raise FBchatException('Unknown thread type: {}, with data: {}'.format(thread.get('thread_type'), thread))
def graphql_to_group(group):
| 64 | 64 | 171 | 6 | 58 | abhisharma404/fbchat | fbchat/graphql.py | Python | graphql_to_group | graphql_to_group | 214 | 231 | 214 | 214 | 59279dd448450490b957f66d0521d65199a1bc6d | bigcode/the-stack | train |
d6c3f3edd274b5297156b76c | train | function | def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'creativeApi.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on... | def main():
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'creativeApi.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHON... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 93 | 3 | 22 | Alsaheem/temp-creative-api | creativeApi/manage.py | Python | main | main | 7 | 17 | 7 | 7 | 52b6919d7f98b870a7ae4801deccccadbed66f9f | bigcode/the-stack | train |
3d8c6186ecbd3f9a0aa7c753 | train | class | class ExpressionSpecBasedComputationNoRaiseMixin(object):
# Mixins are not allow to specify slots.
__slots__ = ()
builtin_spec = None
def computeBuiltinSpec(self, trace_collection, given_values):
assert self.builtin_spec is not None, self
if not self.builtin_spec.isCompileTimeComputab... | class ExpressionSpecBasedComputationNoRaiseMixin(object):
# Mixins are not allow to specify slots.
| __slots__ = ()
builtin_spec = None
def computeBuiltinSpec(self, trace_collection, given_values):
assert self.builtin_spec is not None, self
if not self.builtin_spec.isCompileTimeComputable(given_values):
return self, None, None
return trace_collection.getCompileTimeCo... | ,
computation=lambda: self.builtin_spec.simulateCall(given_values),
description="Built-in call to '%s' pre-computed."
% (self.builtin_spec.getName()),
)
class ExpressionSpecBasedComputationNoRaiseMixin(object):
# Mixins are not allow to specify slots.
| 64 | 64 | 139 | 22 | 42 | fleimgruber/Nuitka | nuitka/nodes/ExpressionBases.py | Python | ExpressionSpecBasedComputationNoRaiseMixin | ExpressionSpecBasedComputationNoRaiseMixin | 1,500 | 1,517 | 1,500 | 1,501 | cf01aa03ceb7ff5943a4ef438e541881bbecb117 | bigcode/the-stack | train |
3570dec7aa6477cb2c2b00f2 | train | class | class ExpressionSpecBasedComputationMixin(object):
# Mixins are not allow to specify slots.
__slots__ = ()
builtin_spec = None
def computeBuiltinSpec(self, trace_collection, given_values):
assert self.builtin_spec is not None, self
if not self.builtin_spec.isCompileTimeComputable(give... | class ExpressionSpecBasedComputationMixin(object):
# Mixins are not allow to specify slots.
| __slots__ = ()
builtin_spec = None
def computeBuiltinSpec(self, trace_collection, given_values):
assert self.builtin_spec is not None, self
if not self.builtin_spec.isCompileTimeComputable(given_values):
trace_collection.onExceptionRaiseExit(BaseException)
return ... | _" + self.named_child
value = getattr(self, attr_name)
values = {self.named_child: tuple(v.makeClone() for v in value)}
values.update(self.getDetails())
return values
class ExpressionSpecBasedComputationMixin(object):
# Mixins are not allow to specify slots.
| 64 | 64 | 147 | 20 | 43 | fleimgruber/Nuitka | nuitka/nodes/ExpressionBases.py | Python | ExpressionSpecBasedComputationMixin | ExpressionSpecBasedComputationMixin | 1,478 | 1,497 | 1,478 | 1,479 | ea5e0d23f7cffe9cbc52f2519d9ca0cb55d485bf | bigcode/the-stack | train |
9b5a043dc18f1d3d63bd1a49 | train | class | class ExpressionChildTupleHavingBase(ExpressionBase):
checker = None
def __init__(self, value, source_ref):
ExpressionBase.__init__(self, source_ref=source_ref)
if self.checker is not None:
value = self.checker(value) # False alarm, pylint: disable=not-callable
assert typ... | class ExpressionChildTupleHavingBase(ExpressionBase):
| checker = None
def __init__(self, value, source_ref):
ExpressionBase.__init__(self, source_ref=source_ref)
if self.checker is not None:
value = self.checker(value) # False alarm, pylint: disable=not-callable
assert type(value) is tuple, self.named_child
assert Non... | = getattr(self, attr_name)
yield self.named_child, value
def replaceChild(self, old_node, new_node):
if new_node is not None and not isinstance(new_node, NodeBase):
raise AssertionError(
"Cannot replace with", new_node, "old", old_node, "in", self
)
... | 256 | 256 | 999 | 9 | 246 | fleimgruber/Nuitka | nuitka/nodes/ExpressionBases.py | Python | ExpressionChildTupleHavingBase | ExpressionChildTupleHavingBase | 1,337 | 1,475 | 1,337 | 1,337 | 11550fe3ba0e1de09794095d22740e7d84bf5c59 | bigcode/the-stack | train |
c2318a36ca58af1e33d4dff8 | train | class | class ExpressionChildHavingBase(ExpressionBase):
checker = None
def __init__(self, value, source_ref):
ExpressionBase.__init__(self, source_ref=source_ref)
if self.checker is not None:
value = self.checker(value) # False alarm, pylint: disable=not-callable
if value is not... | class ExpressionChildHavingBase(ExpressionBase):
| checker = None
def __init__(self, value, source_ref):
ExpressionBase.__init__(self, source_ref=source_ref)
if self.checker is not None:
value = self.checker(value) # False alarm, pylint: disable=not-callable
if value is not None:
value.parent = self
... | init__(self, source_ref=source_ref)
ChildrenHavingMixin.__init__(self, values=values)
def computeExpressionRaw(self, trace_collection):
"""Compute an expression.
Default behavior is to just visit the child expressions first, and
then the node "computeExpression". For a few cases t... | 256 | 256 | 1,026 | 8 | 248 | fleimgruber/Nuitka | nuitka/nodes/ExpressionBases.py | Python | ExpressionChildHavingBase | ExpressionChildHavingBase | 1,189 | 1,334 | 1,189 | 1,189 | d2bc148f7ac393a624fe38d6968d3a63d96ceb00 | bigcode/the-stack | train |
41900811ddd8874cc0ada187 | train | class | class ExpressionBase(NodeBase):
# TODO: Maybe we can do this only for debug mode.
__slots__ = ("code_generated",)
@staticmethod
def getTypeShape():
return tshape_unknown
def getValueShape(self):
return self
@staticmethod
def isCompileTimeConstant():
"""Has a value ... | class ExpressionBase(NodeBase):
# TODO: Maybe we can do this only for debug mode.
| __slots__ = ("code_generated",)
@staticmethod
def getTypeShape():
return tshape_unknown
def getValueShape(self):
return self
@staticmethod
def isCompileTimeConstant():
"""Has a value that we can use at compile time.
Yes or no. If it has such a value, simulatio... | Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations unde... | 256 | 256 | 5,476 | 20 | 235 | fleimgruber/Nuitka | nuitka/nodes/ExpressionBases.py | Python | ExpressionBase | ExpressionBase | 45 | 847 | 45 | 46 | 3b32b695847bfc9240739328ff8abfb6e3ed44b2 | bigcode/the-stack | train |
14886ebb5d4029a659c83335 | train | class | class ExpressionBuiltinSingleArgBase(
ExpressionSpecBasedComputationMixin, ExpressionChildHavingBase
):
named_child = "value"
def __init__(self, value, source_ref):
ExpressionChildHavingBase.__init__(self, value=value, source_ref=source_ref)
def computeExpression(self, trace_collection):
... | class ExpressionBuiltinSingleArgBase(
ExpressionSpecBasedComputationMixin, ExpressionChildHavingBase
):
| named_child = "value"
def __init__(self, value, source_ref):
ExpressionChildHavingBase.__init__(self, value=value, source_ref=source_ref)
def computeExpression(self, trace_collection):
value = self.subnode_value
if value is None:
return self.computeBuiltinSpec(
... | =self,
computation=lambda: self.builtin_spec.simulateCall(given_values),
description="Built-in call to '%s' pre-computed."
% (self.builtin_spec.getName()),
)
class ExpressionBuiltinSingleArgBase(
ExpressionSpecBasedComputationMixin, ExpressionChildHavingBase
):
| 64 | 64 | 126 | 21 | 43 | fleimgruber/Nuitka | nuitka/nodes/ExpressionBases.py | Python | ExpressionBuiltinSingleArgBase | ExpressionBuiltinSingleArgBase | 1,520 | 1,538 | 1,520 | 1,522 | c106fe40a7d85ee5ccd49bfe9d613d00b8694736 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.