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
9a80fda71975b5c2e20668b9
train
function
@api.route('/files', defaults={'api_version': 'v1'}, methods=['POST', 'OPTIONS']) @api.route('/<api_version>/files', methods=['POST', 'OPTIONS']) @crossdomain(origin='*', headers='authentication-token') @auth_token_required def upload_file(api_version): jsonContent = None try: if('content' in request.v...
@api.route('/files', defaults={'api_version': 'v1'}, methods=['POST', 'OPTIONS']) @api.route('/<api_version>/files', methods=['POST', 'OPTIONS']) @crossdomain(origin='*', headers='authentication-token') @auth_token_required def upload_file(api_version):
jsonContent = None try: if('content' in request.values): if(api_version == 'v1'): return make_response(jsonify( { 'error': "You need to use the version 1.1 of the api to pass json content to this call." } ), 500) else: jsonContent = json.loads(requ...
3FT28' @apiSuccessExample Success-Response (example): HTTP/1.0 200 OK Content-Type: application/json { "created_at": "02-06-2014 09:56:26", "duration": 69, "filename": "lcp_q_gov.wav", "generated_filename": "lcp_q_gov_a94b9c74_fa07_4d9a_a937_b2aeeddb3830.wav", "id": 3, "processes": [], "size": 2217030, ...
215
215
718
62
153
voxolab/voxo-dashboard
api/views/files_views.py
Python
upload_file
upload_file
229
315
229
234
b46e07067652e9fcec8a1b243ba77fd5083e554f
bigcode/the-stack
train
b494e1ee4c7bd0b14b77039d
train
class
class Site(OralArgumentSite): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ d = date.today() # d = date(month=5, day=1, year=2014) self.url = "http://www.cadc.uscourts.gov/recordings/recordings.nsf/DocsByRDate...
class Site(OralArgumentSite):
def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ d = date.today() # d = date(month=5, day=1, year=2014) self.url = "http://www.cadc.uscourts.gov/recordings/recordings.nsf/DocsByRDate?OpenView&count=100&SKey={year...
"""Scraper for D.C. Circuit of Appeals CourtID: cadc Court Short Name: cadc Author: Andrei Chelaru Reviewer: mlr Date created: 18 July 2014 """ from datetime import datetime, date from juriscraper.OralArgumentSite import OralArgumentSite class Site(OralArgumentSite):
76
159
530
8
67
drewsilcock/juriscraper
juriscraper/oral_args/united_states/federal_appellate/cadc.py
Python
Site
Site
14
62
14
14
83378cc05a9577a3d9325af29b5a0bdaf145ffd5
bigcode/the-stack
train
48eb0f65488c404b49bb127d
train
function
def ma_antpos(rot): """ MiniArray rotation in degrees """ nenufar_antpos = np.array( [ -5.50000000e+00, -9.52627850e+00, 0.00000000e+00, 0.00000000e+00, -9.52627850e+00, 0.00000000e+00, 5.50000000e+00, -9.52627850e+00, 0.00000000e+00, -8.25000000e...
def ma_antpos(rot):
""" MiniArray rotation in degrees """ nenufar_antpos = np.array( [ -5.50000000e+00, -9.52627850e+00, 0.00000000e+00, 0.00000000e+00, -9.52627850e+00, 0.00000000e+00, 5.50000000e+00, -9.52627850e+00, 0.00000000e+00, -8.25000000e+00, -4.76313877e+00...
nenufar_loc', 'analog_pointing', 'desquint_elevation', 'nenufar_ant_gain', 'read_cal_table', 'effective_area', 'sky_temperature', 'inst_temperature', 'sefd', 'sensitivity', 'resolution', 'confusion_noise', 'data_rate', 'freq2sb', 'sb2freq', 'lnaGain' ] from ...
220
220
734
6
214
AlanLoh/nenupy
nenupy/instru/instru.py
Python
ma_antpos
ma_antpos
86
120
86
86
02979e967d66ae05c74764c7670cf54eaf691ecc
bigcode/the-stack
train
8389f6607b8740119244c8e9
train
function
def effective_area(freq=50, antennas=None, miniarrays=None): """ Computes the NenuFAR array effective area. :param freq: Frequency at which computing the effective area. In MHz if no unit is provided. Default is ``50 MHz``. :type freq: `float` or :class:`~astropy.units.Quan...
def effective_area(freq=50, antennas=None, miniarrays=None):
""" Computes the NenuFAR array effective area. :param freq: Frequency at which computing the effective area. In MHz if no unit is provided. Default is ``50 MHz``. :type freq: `float` or :class:`~astropy.units.Quantity` :param antennas: Mini-Array antenna...
(calfile is None) or (calfile.lower() == 'default'): calfile = join( dirname(__file__), 'cal_pz_2_multi_2019-02-23.dat', ) with open(calfile, 'rb') as f: log.info( 'Loading calibration table {}'.format( calfile ) ) ...
256
256
970
14
242
AlanLoh/nenupy
nenupy/instru/instru.py
Python
effective_area
effective_area
630
743
630
630
d4bc19649bcc4075f8a8d07ec0745227562cb674
bigcode/the-stack
train
1fec72badecad81594605471
train
function
def analog_pointing(azimuth, elevation): """ NenuFAR Mini-Array pointing is performed using analogical delays between antennas. Therefore, the pointing directions follow a discrete distribution. This function allows for finding the actual pointing order given an aziumuth and an eleva...
def analog_pointing(azimuth, elevation):
""" NenuFAR Mini-Array pointing is performed using analogical delays between antennas. Therefore, the pointing directions follow a discrete distribution. This function allows for finding the actual pointing order given an aziumuth and an elevation as requests. .. image:: ./_...
.deg, lon=2.1924002 * u.deg, height=135.834 * u.m ) # ============================================================= # # ============================================================= # # -------------------------- getMAL93 ------------------------- # # ==========================================================...
146
146
488
10
136
AlanLoh/nenupy
nenupy/instru/instru.py
Python
analog_pointing
analog_pointing
282
328
282
282
41e8f85fd08f843fb27ae64d0c98bbb121de9f71
bigcode/the-stack
train
2a96266e30844ff2855d1192
train
function
def sb2freq(sb): r""" Conversion between NenuFAR sub-band index :math:`n_{\rm SB}` to sub-band starting frequency :math:`\nu_{\rm start}`: .. math:: \nu_{\rm start} = \frac{n_{\rm SB} \times \Delta \nu}{512} Each NenuFAR sub-band has a bandwidth of :math:`\Delta \nu = 1...
def sb2freq(sb):
r""" Conversion between NenuFAR sub-band index :math:`n_{\rm SB}` to sub-band starting frequency :math:`\nu_{\rm start}`: .. math:: \nu_{\rm start} = \frac{n_{\rm SB} \times \Delta \nu}{512} Each NenuFAR sub-band has a bandwidth of :math:`\Delta \nu = 195.3125\, \rm{kHz...
(freq, u.Quantity): freq *= u.MHz if (freq.min() < 0 * u.MHz) or (freq.max() > 100 * u.MHz): raise ValueError( 'freq should be between 0 and 100 MHz.' ) freq = freq.to(u.MHz) sb_width = 100. * u.MHz sb_idx = np.floor((freq * 512) / sb_width) return sb_idx.astype(i...
133
133
445
6
127
AlanLoh/nenupy
nenupy/instru/instru.py
Python
sb2freq
sb2freq
1,267
1,310
1,267
1,267
848aff6c485a69b72785d3c48ee6ea03c5a06b90
bigcode/the-stack
train
eb5707771a66b9d0a258faeb
train
function
def sensitivity(mode='imaging', freq=50, antennas=None, miniarrays=None, dt=1, df=1): r""" Returns the sensitivity of NenuFAR. For the imaging mode: .. math:: \Delta S_{\rm im} = \frac{S_{\rm sys}}{ \sqrt{N(N-1) 2 \delta \nu \delta t} } For the beam...
def sensitivity(mode='imaging', freq=50, antennas=None, miniarrays=None, dt=1, df=1):
r""" Returns the sensitivity of NenuFAR. For the imaging mode: .. math:: \Delta S_{\rm im} = \frac{S_{\rm sys}}{ \sqrt{N(N-1) 2 \delta \nu \delta t} } For the beamforming mode: .. math:: \Delta S_{\rm bf} = \frac{S_{\rm sys}}{ ...
far-array/sensiti>`_, :func:`~nenupy.instru.instru.sky_temperature` for :math:`T_{\rm sky}`, :func:`~nenupy.instru.instru.inst_temperature` for :math:`T_{\rm inst}`, :func:`~nenupy.instru.instru.effective_area` for :math:`A_{\rm eff}`. """ efficiency = 1. aeff = effectiv...
217
217
726
26
191
AlanLoh/nenupy
nenupy/instru/instru.py
Python
sensitivity
sensitivity
871
951
871
871
fc6a6676e8acfa459e5ca753e8248e73b9090722
bigcode/the-stack
train
8fa25b9e10cf634635e2f506
train
function
def read_cal_table(calfile=None): """ Reads NenuFAR antenna delays calibration file. :param calfile: Name of the calibration file to read. If ``None`` or ``'default'`` the standard calibration file is read. :type calfile: `str` :returns: Antenna delays...
def read_cal_table(calfile=None):
""" Reads NenuFAR antenna delays calibration file. :param calfile: Name of the calibration file to read. If ``None`` or ``'default'`` the standard calibration file is read. :type calfile: `str` :returns: Antenna delays shaped as (frequency...
', 'C'], inv=True ) with _HiddenPrints(): gain = rot.rotate_map_alms(gain) # Convert HEALPix map to required nside gain = ud_grade(gain, nside_out=nside) return gain / gain.max() if normalize else gain # ============================================================= # ...
96
96
323
8
88
AlanLoh/nenupy
nenupy/instru/instru.py
Python
read_cal_table
read_cal_table
579
623
579
579
6b13c5b6e4c1254ba9aa1bda7b1f82b6f7049f9d
bigcode/the-stack
train
62fedb0b43e5c3cb2a09e41c
train
function
def nenufar_ant_gain(freq, polar='NW', nside=64, time=None, normalize=True): """ Get NenuFAR elementary antenna gain with respect to the frequency ``freq``, the polarization ``polar`` and convert it to HEALPix representation with a given ``nside`` that defines pixel number. The map is initia...
def nenufar_ant_gain(freq, polar='NW', nside=64, time=None, normalize=True):
""" Get NenuFAR elementary antenna gain with respect to the frequency ``freq``, the polarization ``polar`` and convert it to HEALPix representation with a given ``nside`` that defines pixel number. The map is initially in horizontal coordinates, conversion to equatorial coord...
if not isinstance(opt_freq, Quantity): opt_freq *= u.MHz elevation = elevation.to(u.deg) opt_freq = opt_freq.to(u.MHz) squint = readsav( join( dirname(__file__), 'squint_table.sav' ) ) freq_idx = np.argmin( np.abs(squint['freq'] - opt_freq.val...
256
256
1,472
23
233
AlanLoh/nenupy
nenupy/instru/instru.py
Python
nenufar_ant_gain
nenufar_ant_gain
402
572
402
402
8778c3e59adc3080fcab72ec325057a509cb5a5d
bigcode/the-stack
train
e4b2122e3dde35ff55f238dc
train
function
def data_rate(mode='imaging', mas=96, dt=1, nchan=64, bandwidth=75, nb=1): r""" Estimates the NenuFAR data rate product. To get the total observation size, a simple multiplication with a :class:`~astropy.units.Quantity` time instance, corresponding to total exposure time, is needed. To conve...
def data_rate(mode='imaging', mas=96, dt=1, nchan=64, bandwidth=75, nb=1):
r""" Estimates the NenuFAR data rate product. To get the total observation size, a simple multiplication with a :class:`~astropy.units.Quantity` time instance, corresponding to total exposure time, is needed. To convert bytes in binary base (i.e. 1 kB = 1024 B), use `astropy` ...
>>> from nenupy.instru import confusion_noise >>> confusion_noise( freq=50, miniarrays=None ) 4663.202 mJy .. see also:: `NRAO lecture <https://www.cv.nrao.edu/course/astr534/Radiometers.html>`_ (eq. 3E6), ...
256
256
1,570
29
227
AlanLoh/nenupy
nenupy/instru/instru.py
Python
data_rate
data_rate
1,087
1,216
1,087
1,087
4bddbbd5c3797f123f0ecf7ebe14acbf7ed8cc5a
bigcode/the-stack
train
26e3e0d9f0d691de2522a7d1
train
function
def sky_temperature(freq=50): r""" Sky temperature at a given frequency ``freq`` (strongly dominated by Galactic emission). .. math:: T_{\rm sky} = T_0 \lambda^{2.55} with :math:`T_0 = 60 \pm 20\,\rm{K}` for Galactic latitudes between 10 and 90 degrees. :param ...
def sky_temperature(freq=50):
r""" Sky temperature at a given frequency ``freq`` (strongly dominated by Galactic emission). .. math:: T_{\rm sky} = T_0 \lambda^{2.55} with :math:`T_0 = 60 \pm 20\,\rm{K}` for Galactic latitudes between 10 and 90 degrees. :param freq: Frequency at...
a_radius] += 1 grid[grid != 0] = 1 ma_ea = (grid * dx * dy).sum() * (u.m**2) # NenuFAR Effective Area return ma_ea * miniarrays.size # ============================================================= # # ============================================================= # # ---------------------- sky_tempera...
87
87
292
7
80
AlanLoh/nenupy
nenupy/instru/instru.py
Python
sky_temperature
sky_temperature
750
777
750
750
c9ad72c548aeea624ff06c4defebef34bbc55bee
bigcode/the-stack
train
87f72e037529737e8dc722c4
train
function
def freq2sb(freq): r""" Conversion between the frequency :math:`\nu` and the NenuFAR sub-band index :math:`n_{\rm SB}`. Each NenuFAR sub-band has a bandwidth of :math:`\Delta \nu = 195.3125\, \rm{kHz}`: .. math:: n_{\rm SB} = \frac{512 \times \nu}{\Delta \nu} :p...
def freq2sb(freq):
r""" Conversion between the frequency :math:`\nu` and the NenuFAR sub-band index :math:`n_{\rm SB}`. Each NenuFAR sub-band has a bandwidth of :math:`\Delta \nu = 195.3125\, \rm{kHz}`: .. math:: n_{\rm SB} = \frac{512 \times \nu}{\Delta \nu} :param freq: ...
== 'waveform': rate_sb = 4*nb*sb_width.to(u.Hz).value rate = rate_sb * n_sb * u.byte / u.s elif mode == 'tbb': rate = 4*nb*sb_width.to(u.Hz).value*1024*mas * u.byte / u.s return rate # ============================================================= # # ================================...
107
107
357
6
101
AlanLoh/nenupy
nenupy/instru/instru.py
Python
freq2sb
freq2sb
1,223
1,260
1,223
1,223
2a488182b5ad29e062189a5889c229e9211e9bf9
bigcode/the-stack
train
d4724a05de8e93016de9d2b4
train
function
def desquint_elevation(elevation, opt_freq=30): """ Radio phased array are affected by beam squint. Combination of antenna response (maximal at zenith) and array factor of antenna distribution can shift maximal sensitivity towards greater elevations. This function allows for correcti...
def desquint_elevation(elevation, opt_freq=30):
""" Radio phased array are affected by beam squint. Combination of antenna response (maximal at zenith) and array factor of antenna distribution can shift maximal sensitivity towards greater elevations. This function allows for correcting this effect by shifting pointing elev...
0.5) theta_idx = int((90. - elevation.value)/0.05 - 0.5) else: phi_idx = (azimuth.value/0.05 - 0.5).astype(int) theta_idx = ((90. - elevation.value)/0.05 - 0.5).astype(int) t, p = thph[:, theta_idx, phi_idx] azimuth = p * u.deg elevation = (90. - t) * u.deg return azimuth, el...
155
155
517
14
141
AlanLoh/nenupy
nenupy/instru/instru.py
Python
desquint_elevation
desquint_elevation
335
395
335
335
03f153b0163dea32b464bff16043267ad0400bd5
bigcode/the-stack
train
645fbc968c12486b47e0b21a
train
function
def sefd(freq=50, antennas=None, miniarrays=None): r""" Computes the System Equivalent Flux Density (SEFD or system sensitivity). .. math:: S_{\rm sys} = \frac{2 \eta k_{\rm B}}{ A_{\rm eff}} T_{\rm sys} with :math:`T_{\rm sys} = T_{\rm sky} + T_{\rm inst}`, ...
def sefd(freq=50, antennas=None, miniarrays=None):
r""" Computes the System Equivalent Flux Density (SEFD or system sensitivity). .. math:: S_{\rm sys} = \frac{2 \eta k_{\rm B}}{ A_{\rm eff}} T_{\rm sys} with :math:`T_{\rm sys} = T_{\rm sky} + T_{\rm inst}`, the efficiency :math:`\eta = 1` and :math:`k_{...
0.2783,0.3040,0.3390,0.3846, 0.4425,0.5167,0.6183,0.7689,1.0086,1.4042,2.0732 ]) freqs = (np.arange(71) + 15) # MHz tsky = sky_temperature(freq=freq) tinst = tsky * lna_sky[ np.abs(freqs - freq).argmin() ] return tinst # ============================================================= # # ===...
149
149
497
14
135
AlanLoh/nenupy
nenupy/instru/instru.py
Python
sefd
sefd
822
864
822
822
cf757e784c3f8239cca7f48cc6e603be9a58833a
bigcode/the-stack
train
e28e65418c14c8dbc9d51b77
train
function
def lnaGain(freq, filter25=False): """ Returns the NenuFAR Low Noise Amplifier (LNA) gains with at given frequencies ``freq``. LNA gains values are linearly interpolated between 15 and 85 MHz. :param freq: Frequency at which the LNA gain must be returned. :type freq: ...
def lnaGain(freq, filter25=False):
""" Returns the NenuFAR Low Noise Amplifier (LNA) gains with at given frequencies ``freq``. LNA gains values are linearly interpolated between 15 and 85 MHz. :param freq: Frequency at which the LNA gain must be returned. :type freq: `int`, `float`, :class:`~n...
sb = np.array(sb) if sb.dtype.name not in ['int32', 'int64']: raise TypeError( 'sb should be integers.' ) if (sb.min() < 0) or (sb.max() > 511): raise ValueError( 'sb should be between 0 and 511.' ) sb_width = 100. * u.MHz freq_start = (sb * sb_wi...
136
136
456
10
126
AlanLoh/nenupy
nenupy/instru/instru.py
Python
lnaGain
lnaGain
1,317
1,361
1,317
1,317
d42337b6aac6349ed13a134add3e8e89e1439e93
bigcode/the-stack
train
9d6a1e1bc592a90f85368f3f
train
function
def resolution(freq=50, miniarrays=None): """ Returns the resolution for a given NenuFAR configuration. :param freq: Frequency at which computing the resolution. In MHz if no unit is provided. Default is ``50 MHz``. :type freq: `float` or :class:`~astropy.units.Quantity` ...
def resolution(freq=50, miniarrays=None):
""" Returns the resolution for a given NenuFAR configuration. :param freq: Frequency at which computing the resolution. In MHz if no unit is provided. Default is ``50 MHz``. :type freq: `float` or :class:`~astropy.units.Quantity` :param miniarrays: Mini-...
arrays, list): miniarrays = np.array(miniarrays) if max(miniarrays) > ma_info.size: raise ValueError( 'Only {} Mini-Arrays'.format(ma_info.size) ) nant = miniarrays.size if mode.lower() == 'imaging': sensitivity = ssys / np.sqrt(nant*(nant-1) *...
163
163
544
10
153
AlanLoh/nenupy
nenupy/instru/instru.py
Python
resolution
resolution
958
1,023
958
958
c695a9a5e0edae10ac7c7d9527c347087468e861
bigcode/the-stack
train
fb5b07e65e41ae0998b3c447
train
class
class _HiddenPrints: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout
class _HiddenPrints:
def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout
0, 1] ] ) ma_pos = np.dot( np.array([aa.tolist() for aa in ma_info['pos']]), rotation ) # ============================================================= # # ============================================================= # # ----------------------- HiddenPrints ------------------------ # # =======...
64
64
64
6
58
AlanLoh/nenupy
nenupy/instru/instru.py
Python
_HiddenPrints
_HiddenPrints
244
251
244
244
775ee6b6000123ad786ce0f4ef6f519363209409
bigcode/the-stack
train
9f728b1dce7a5d07384f1a46
train
function
def confusion_noise(freq=50, miniarrays=None): r""" Confusion rms noise :math:`\sigma_{\rm c}` (parameter used for specifying the width of the confusion distribution) computed as: .. math:: \left( \frac{\sigma_{\rm c}}{\rm{mJy}\, \rm{beam}^{-1}} \right) \simeq 0.2 \l...
def confusion_noise(freq=50, miniarrays=None):
r""" Confusion rms noise :math:`\sigma_{\rm c}` (parameter used for specifying the width of the confusion distribution) computed as: .. math:: \left( \frac{\sigma_{\rm c}}{\rm{mJy}\, \rm{beam}^{-1}} \right) \simeq 0.2 \left( \frac{\nu}{\rm GHz} \right)^{-0.7} ...
, list): miniarrays = np.array(miniarrays) if max(miniarrays) > ma_info.size: raise ValueError( 'Only {} Mini-Arrays'.format(ma_info.size) ) positions = ma_pos[miniarrays] size = np.sqrt( np.sum( (positions - np.mean...
156
156
520
11
145
AlanLoh/nenupy
nenupy/instru/instru.py
Python
confusion_noise
confusion_noise
1,030
1,080
1,030
1,030
55302ca210719da28c0176a7935a4c23310e697b
bigcode/the-stack
train
7ec579565114e72c4c815a71
train
function
def inst_temperature(freq=50): """ Instrument temperature at a given frequency ``freq``. This depends on the Low Noise Amplifier characteristics. :param freq: Frequency at which computing the esky temperature. In MHz if no unit is provided. Default is ``50 MHz``. :ty...
def inst_temperature(freq=50):
""" Instrument temperature at a given frequency ``freq``. This depends on the Low Noise Amplifier characteristics. :param freq: Frequency at which computing the esky temperature. In MHz if no unit is provided. Default is ``50 MHz``. :type freq: `float` or :class:`~as...
:rtype: :class:`~astropy.units.Quantity` .. seealso:: `LOFAR website <http://old.astron.nl/radio-observatory/astronomers/lofar-imaging-capabilities-sensitivity/sensitivity-lofar-array/sensiti>`_, Haslam et al. (1982) and Mozdzen et al. (2017, 2019) """ if not isinstance(freq, ...
174
174
582
7
167
AlanLoh/nenupy
nenupy/instru/instru.py
Python
inst_temperature
inst_temperature
784
815
784
784
00aac718650825004b144fb8b5461ebc457f153a
bigcode/the-stack
train
f275dc8ea7275e04e065c433
train
function
def getMAL93(m): """ """ ma_pos = np.array([a.tolist() for a in ma_info['pos']]) available_mas = np.arange(ma_pos.shape[0]) antpos = ma_pos[np.isin(available_mas, m)] return antpos
def getMAL93(m):
""" """ ma_pos = np.array([a.tolist() for a in ma_info['pos']]) available_mas = np.arange(ma_pos.shape[0]) antpos = ma_pos[np.isin(available_mas, m)] return antpos
=47.376511 * u.deg, lon=2.1924002 * u.deg, height=135.834 * u.m ) # ============================================================= # # ============================================================= # # -------------------------- getMAL93 ------------------------- # # ============================================...
64
64
64
7
57
AlanLoh/nenupy
nenupy/instru/instru.py
Python
getMAL93
getMAL93
269
275
269
269
bfb58208779cfc5b5de211e946eb084804457a05
bigcode/the-stack
train
dbdaf2238845a9968036faf6
train
class
class ResourceListOfPortfolioCashLadder(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value i...
class ResourceListOfPortfolioCashLadder(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ LUSID API FINBOURNE Technology # noqa: E501 The version of the OpenAPI document: 0.11.3923 Contact: info@finbourne.com Generated by: https://openapi-generator.tech """ try: from inspect import getfullargspec except ImportError: from inspect import getargspec as getf...
127
256
1,801
10
116
finbourne/lusid-sdk-python-asyncio-preview
sdk/lusid_asyncio/models/resource_list_of_portfolio_cash_ladder.py
Python
ResourceListOfPortfolioCashLadder
ResourceListOfPortfolioCashLadder
25
266
25
25
c243357e401c7a1c44180b7b4fe544ad5f13e0f9
bigcode/the-stack
train
c770cbd36e9aeec0dda854ab
train
class
class FleetDistRunnerBase(object): """ run_pserver,run_trainer : after init role, using transpiler split program net : implment by child class, the network of model do training : exe run program """ def generate_strategy(self, args): self.strategy = None if args.mode...
class FleetDistRunnerBase(object):
""" run_pserver,run_trainer : after init role, using transpiler split program net : implment by child class, the network of model do training : exe run program """ def generate_strategy(self, args): self.strategy = None if args.mode == "async": self.strat...
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 under the License. from __future__ import print_function """ high lev...
256
256
976
7
248
grasswolfs/Paddle
python/paddle/fluid/tests/unittests/test_dist_fleet_base.py
Python
FleetDistRunnerBase
FleetDistRunnerBase
49
178
49
49
5ac86eb8a751c904a44d13748e3350ca80cbc7bc
bigcode/the-stack
train
ab3638fdbdad4fdcbb1514df
train
function
def runtime_main(test_class): parser = argparse.ArgumentParser(description='Run Fleet test.') parser.add_argument( '--role', type=str, required=True, choices=['pserver', 'trainer']) parser.add_argument('--endpoints', type=str, required=False, default="") parser.add_argument('--current_id', type=...
def runtime_main(test_class):
parser = argparse.ArgumentParser(description='Run Fleet test.') parser.add_argument( '--role', type=str, required=True, choices=['pserver', 'trainer']) parser.add_argument('--endpoints', type=str, required=False, default="") parser.add_argument('--current_id', type=int, required=False, default=0...
_envs) if check_error_log: required_envs["GLOG_v"] = "3" required_envs["GLOG_logtostderr"] = "1" tr0_losses, tr1_losses = self._run_cluster(model_file, required_envs) def runtime_main(test_class):
64
64
211
6
58
grasswolfs/Paddle
python/paddle/fluid/tests/unittests/test_dist_fleet_base.py
Python
runtime_main
runtime_main
358
378
358
358
5b3dd70242b86a839f47304c2661c68499f6c04d
bigcode/the-stack
train
1d5f6be85b2a4dc648287fd2
train
class
class TestFleetBase(unittest.TestCase): """ start_pserver,start_trainer : add start cmd to test run_cluster : using multi process to test distribute program """ def _setup_config(self): raise NotImplementedError("tests should have _setup_config implemented") def setUp(self): ...
class TestFleetBase(unittest.TestCase):
""" start_pserver,start_trainer : add start cmd to test run_cluster : using multi process to test distribute program """ def _setup_config(self): raise NotImplementedError("tests should have _setup_config implemented") def setUp(self): self._mode = "sync" self._...
() != "TRAINER": raise ValueError("args role must be TRAINER") role = role_maker.UserDefinedRoleMaker( current_id=args.current_id, role=role_maker.Role.WORKER, worker_num=args.trainers, server_endpoints=args.endpoints.split(",")) fleet.init(r...
255
256
1,594
8
247
grasswolfs/Paddle
python/paddle/fluid/tests/unittests/test_dist_fleet_base.py
Python
TestFleetBase
TestFleetBase
181
355
181
181
f0a4f841d23f715f7e9bc9582de44f61cb8116f3
bigcode/the-stack
train
285bb4c18508ae8fe501db6a
train
class
class Rot90(data.Dataset): def __init__(self, dataset, p=-1, batch_size_down=8e4): self.dataset = dataset self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats_new = self.dataset.num_cats ...
class Rot90(data.Dataset):
def __init__(self, dataset, p=-1, batch_size_down=8e4): self.dataset = dataset self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats_new = self.dataset.num_cats * 3 self.num_cats =...
of categories (both novel and base). Returns: images: a tensor of shape [nExamples, Height, Width, 3] with the example images, where nExamples is the number of examples (i.e., nExamples = len(examples)). labels: a tensor of shape [...
248
248
829
6
241
erprashu/Metal_erning
metadatas/taskaug.py
Python
Rot90
Rot90
279
357
279
279
57005b29f089be7621c49d26bbae7689fe64c592
bigcode/the-stack
train
4808115f43ca16502947e1d1
train
class
class Solarize(data.Dataset): def __init__(self, dataset, p=1): self.dataset = dataset self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats self.p = p @staticmethod def random_solarize(data): solarize = K.RandomSolarize(0.1, 0.1, same_on...
class Solarize(data.Dataset):
def __init__(self, dataset, p=1): self.dataset = dataset self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats self.p = p @staticmethod def random_solarize(data): solarize = K.RandomSolarize(0.1, 0.1, same_on_batch=True) out = sol...
if len(labels_2) > 0: uni_l2 = torch.unique(labels_2) for i, l2 in enumerate(uni_l2): for j in range(len(images[labels == l2])): bbx1, bby1, bbx2, bby2, mean = self.rand_bbox(self.dataset.img_size) images[labels == l2][j][0, bb...
247
247
825
6
240
erprashu/Metal_erning
metadatas/taskaug.py
Python
Solarize
Solarize
683
767
683
683
5368b121c353182359834bd8de0083913e2ed2dd
bigcode/the-stack
train
90e998da2ec479b395ebc277
train
class
class TaskAug(data.Dataset): def __init__(self, dataset, method, p=-1, batch_size_down=8e4): self.dataset = dataset self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats = self.dataset.num...
class TaskAug(data.Dataset):
def __init__(self, dataset, method, p=-1, batch_size_down=8e4): self.dataset = dataset self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats self.method = ...
], where nK is the total number of categories (both novel and base). Returns: images: a tensor of shape [nExamples, Height, Width, 3] with the example images, where nExamples is the number of examples (i.e., nExamples = len(examples)). ...
256
256
1,602
6
249
erprashu/Metal_erning
metadatas/taskaug.py
Python
TaskAug
TaskAug
438
575
438
438
87e139eb3e3dc319050780dd01be7afaffddb924
bigcode/the-stack
train
472480db489191275893e3d9
train
class
class DropChannels(data.Dataset): def __init__(self, dataset, p=-1): self.dataset = dataset self.phase = self.dataset.phase self.num_cats_new = self.dataset.num_cats * 6 self.num_cats = self.dataset.num_cats + self.num_cats_new self.orders = (torch.LongTensor([1, 1,...
class DropChannels(data.Dataset):
def __init__(self, dataset, p=-1): self.dataset = dataset self.phase = self.dataset.phase self.num_cats_new = self.dataset.num_cats * 6 self.num_cats = self.dataset.num_cats + self.num_cats_new self.orders = (torch.LongTensor([1, 1, 1]), torch.LongTensor([0, 1, 0]), ...
, nK - 1], where nK is the total number of categories (both novel and base). Returns: images: a tensor of shape [nExamples, Height, Width, 3] with the example images, where nExamples is the number of examples (i.e., nExamples = len(examples)). ...
251
251
838
6
244
erprashu/Metal_erning
metadatas/taskaug.py
Python
DropChannels
DropChannels
197
276
197
197
fe9189b3b01d5e8e9468721c79a25c1a65f95d14
bigcode/the-stack
train
36aab8069de660de2dde49a0
train
class
class AddNoise(data.Dataset): def __init__(self, dataset, p=-1, batch_size_down=8e4): self.dataset = dataset self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats ...
class AddNoise(data.Dataset):
def __init__(self, dataset, p=-1, batch_size_down=8e4): self.dataset = dataset self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats if p == -1: ...
(i.e., nExamples = len(examples)). labels: a tensor of shape [nExamples] with the category label of each example. """ dataset = self.dataset images = torch.stack( [torch.rot90(dataset[img_idx[1]][0], img_idx[0], [1, 2]) for img_id...
235
235
785
6
228
erprashu/Metal_erning
metadatas/taskaug.py
Python
AddNoise
AddNoise
360
436
360
360
20eaac37f5e11011854a813ddb850c186beae8f7
bigcode/the-stack
train
a52f3d9742288d8c15a5fbb2
train
class
class DualCategories(data.Dataset): def __init__(self, dataset, p=0.5, std=0.1, batch_size_down=4e4): self.dataset = dataset self.std = std self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase ...
class DualCategories(data.Dataset):
def __init__(self, dataset, p=0.5, std=0.1, batch_size_down=4e4): self.dataset = dataset self.std = std self.batch_num = multiprocessing.Value("d", -1.) self.batch_size_down = batch_size_down self.phase = self.dataset.phase self.num_cats_new = self.dataset.num...
from __future__ import print_function import numpy as np import random import math import multiprocessing import pdb from PIL import Image import torch import torch.utils.data as data import torchvision.transforms.functional as TranF from .utils import ProtoData class DualCategories(data.Dataset):
61
256
1,093
6
54
erprashu/Metal_erning
metadatas/taskaug.py
Python
DualCategories
DualCategories
17
114
17
17
392d4c48c3cd5d6552fc06ebe2d7c02b86d00d99
bigcode/the-stack
train
8944a18db6f9e11d00c571b9
train
class
class PermuteChannels(data.Dataset): def __init__(self, dataset, p=-1, ): self.dataset = dataset self.phase = self.dataset.phase self.num_cats_new = self.dataset.num_cats * 5 self.num_cats = self.dataset.num_cats + self.num_cats_new self.orders = (torch.LongTensor([...
class PermuteChannels(data.Dataset):
def __init__(self, dataset, p=-1, ): self.dataset = dataset self.phase = self.dataset.phase self.num_cats_new = self.dataset.num_cats * 5 self.num_cats = self.dataset.num_cats + self.num_cats_new self.orders = (torch.LongTensor([0, 1, 2]), torch.LongTensor([1, 2, 0])...
1 = dataset[img_idx[0]][0] image2 = dataset[img_idx[1]][0] shift = np.random.normal(loc=0, scale=self.std) return image1 * (shift / 2.) + image2 * ((1 - shift) / 2.) else: return dataset[img_idx[1]][0] images = torch.stack( ...
244
244
816
7
236
erprashu/Metal_erning
metadatas/taskaug.py
Python
PermuteChannels
PermuteChannels
117
194
117
117
0710efb7b105b937145fb68590632439c2efff7f
bigcode/the-stack
train
7e3db3ba72df845d0589fb2f
train
class
class RE(data.Dataset): def __init__(self, dataset, p=1): self.dataset = dataset self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats self.p = p @staticmethod def rand_bbox(size, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0.4914, 0.4822, 0.4465]): ...
class RE(data.Dataset):
def __init__(self, dataset, p=1): self.dataset = dataset self.phase = self.dataset.phase self.num_cats = self.dataset.num_cats self.p = p @staticmethod def rand_bbox(size, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0.4914, 0.4822, 0.4465]): for attempt in ran...
2, bby2 = self.rand_bbox(self.dataset.img_size, lam) images[labels == l2][j][:, bbx1:bbx2, bby1:bby2] = images_3[labels_3 == len(uni_l) + i][j][:, bbx1:bbx2, bby1:bby2] elif self.method == "Combine": for i, l2 in enumerate(uni_l2): new_images =...
256
256
1,104
5
250
erprashu/Metal_erning
metadatas/taskaug.py
Python
RE
RE
578
680
578
578
d88c7cf9eef27277a9b112cde4409cfab3661481
bigcode/the-stack
train
680f99409fea7ab5a236cfd2
train
class
class RasterCellDistance(QgsProcessingAlgorithm): INPUT = 'INPUT' RASTER = 'RASTER' VALUE = 'VALUE' NODATA = 'NODATA' METHOD = 'METHOD' DATA_TYPE = 'DATA_TYPE' OUTPUT_COLUMN = 'OUTPUT_COLUMN' OUTPUT = 'OUTPUT' def tr(self, string, context=''): if context == '': c...
class RasterCellDistance(QgsProcessingAlgorithm):
INPUT = 'INPUT' RASTER = 'RASTER' VALUE = 'VALUE' NODATA = 'NODATA' METHOD = 'METHOD' DATA_TYPE = 'DATA_TYPE' OUTPUT_COLUMN = 'OUTPUT_COLUMN' OUTPUT = 'OUTPUT' def tr(self, string, context=''): if context == '': context = self.__class__.__name__ return QC...
import sys import os from PyQt5.QtCore import QCoreApplication from qgis.core import (QgsProcessing, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource, QgsProcessingParameterRasterLayer, QgsProcessingParameterEnum, Qgs...
85
256
1,192
9
75
ChangjieChen/lucis_qgis
algorithms/cell_dist.py
Python
RasterCellDistance
RasterCellDistance
14
181
14
14
9b539268f7e99f329638b24d496c0bb0a5f8bbce
bigcode/the-stack
train
ce9974ef2aa5dcbf7af5246e
train
class
class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) filt...
class UserProfileViewSet(viewsets.ModelViewSet):
"""Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) filter_backends = (filters.SearchFilter,) search_...
(self, request, pk=None): """Handle updating part of an object""" return Response({'http_method':'PATCH'}) def destroy(self, request, pk=None): """Handle removing an object""" return Response({'http_method':'DELETE'}) class UserProfileViewSet(viewsets.ModelViewSet):
63
64
76
11
52
abhishekmandloi95/profiles-rest-api
profile_api/views.py
Python
UserProfileViewSet
UserProfileViewSet
106
114
106
106
49b705f154c2b523e5aeb8d3f3544df3c1d17928
bigcode/the-stack
train
94b3d44e3f9ac45a64c97673
train
class
class UserProfileFeedViewSet(viewsets.ModelViewSet): """Handles creating, reading and updating profile items""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.ProfileFeedItemSerializer queryset = models.ProfileFeedItem.objects.all() permission_classes = (permissions.U...
class UserProfileFeedViewSet(viewsets.ModelViewSet):
"""Handles creating, reading and updating profile items""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.ProfileFeedItemSerializer queryset = models.ProfileFeedItem.objects.all() permission_classes = (permissions.UpdateOwnStatus, IsAuthenticated) def perform_crea...
,) filter_backends = (filters.SearchFilter,) search_fields = ('name', 'email',) class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class UserProfileFeedViewSet(viewsets.ModelViewSet):
64
64
93
12
51
abhishekmandloi95/profiles-rest-api
profile_api/views.py
Python
UserProfileFeedViewSet
UserProfileFeedViewSet
120
128
120
120
a8dc0c91fe5569bea197922f7d602beffed0535e
bigcode/the-stack
train
cc200bb6f9b73cb620b3f6a2
train
class
class HelloApiView(APIView): """Test API view""" serializer_class = serializers.HelloSerializer def get(self, request, format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'Is simila...
class HelloApiView(APIView):
"""Test API view""" serializer_class = serializers.HelloSerializer def get(self, request, format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'Is similar to a traditional Django vie...
import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from rest_framework.permissi...
83
83
279
7
75
abhishekmandloi95/profiles-rest-api
profile_api/views.py
Python
HelloApiView
HelloApiView
15
55
15
15
38ab0a44cfa6c6cd341014092f42b7103429cac7
bigcode/the-stack
train
383d7649548fcceef8f89cf7
train
class
class HelloViewSet(viewsets.ViewSet): """Test API ViewSet""" serializer_class = serializers.HelloSerializer def list(self, request): """Return a Hello message""" a_viewset = [ 'Uses action(list, create, retrieve, update, partial_update)', 'Automatically maps to URLs...
class HelloViewSet(viewsets.ViewSet):
"""Test API ViewSet""" serializer_class = serializers.HelloSerializer def list(self, request): """Return a Hello message""" a_viewset = [ 'Uses action(list, create, retrieve, update, partial_update)', 'Automatically maps to URLs using Routers', 'Provides...
def put(self, request, pk=None): """Handle updating an object""" return Response({'method':'PUT'}) def patch(self, request, pk=None): """Handle partial update of an object""" return Response({'method':'PATCH'}) def delete(self, request, pk=None): """Delete an object"""...
86
87
291
9
77
abhishekmandloi95/profiles-rest-api
profile_api/views.py
Python
HelloViewSet
HelloViewSet
57
104
57
57
8e26a0f37f70efed2a4065d1aca889252aeff175
bigcode/the-stack
train
57c91371606037f47a4551ce
train
class
class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class UserLoginApiView(ObtainAuthToken):
"""Handle creating user authentication tokens""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) filter_backends = (filters.SearchFilter,) search_fields = ('name', 'email',) class UserLoginApiView(ObtainAuthToken):
64
64
30
11
53
abhishekmandloi95/profiles-rest-api
profile_api/views.py
Python
UserLoginApiView
UserLoginApiView
116
118
116
116
e78b5ede069ee017e824707a13843bce296e14e0
bigcode/the-stack
train
214f34d5961ca4ecfc697259
train
class
class AccountUserLicense(Model): """AccountUserLicense. :param license: :type license: int :param source: :type source: object """ _attribute_map = { 'license': {'key': 'license', 'type': 'int'}, 'source': {'key': 'source', 'type': 'object'} } def __i...
class AccountUserLicense(Model):
"""AccountUserLicense. :param license: :type license: int :param source: :type source: object """ _attribute_map = { 'license': {'key': 'license', 'type': 'int'}, 'source': {'key': 'source', 'type': 'object'} } def __init__(self, license=None, source=N...
. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------...
64
64
117
6
57
amcclead7336/Enterprise_Data_Science_Final
venv/lib/python3.8/site-packages/vsts/licensing/v4_1/models/account_user_license.py
Python
AccountUserLicense
AccountUserLicense
12
29
12
12
7795f49518f9f0024a69580f1b72c84cbe14ff9c
bigcode/the-stack
train
68982f5f7c59e2b84fd75d13
train
class
class LabeledParagraph(Component): """ A paragraph with a label on its left. """ def __init__( self, label, text, padding=2, aligned=True ): # type: (str, str, int, bool) -> None self._label = label self._text = text self._padding = padding self._aligned = a...
class LabeledParagraph(Component):
""" A paragraph with a label on its left. """ def __init__( self, label, text, padding=2, aligned=True ): # type: (str, str, int, bool) -> None self._label = label self._text = text self._padding = padding self._aligned = aligned self._alignment = No...
from __future__ import unicode_literals import re import textwrap from clikit.api.io import IO from clikit.ui import Component class LabeledParagraph(Component):
36
137
459
6
29
finswimmer/clikit
src/clikit/ui/components/labeled_paragraph.py
Python
LabeledParagraph
LabeledParagraph
10
71
10
10
1d769a37fcf2c86111d37c343862158e97676864
bigcode/the-stack
train
a5b840b614c2b1207a2d2af8
train
function
def triplets_get_data(config, net, dataloader, sobel): num_batches = len(dataloader) flat_targets_all = torch.zeros((num_batches * config.batch_sz), dtype=torch.int32).cuda() flat_preds_all = torch.zeros((num_batches * config.batch_sz), dty...
def triplets_get_data(config, net, dataloader, sobel):
num_batches = len(dataloader) flat_targets_all = torch.zeros((num_batches * config.batch_sz), dtype=torch.int32).cuda() flat_preds_all = torch.zeros((num_batches * config.batch_sz), dtype=torch.int32).cuda() num_test = 0 for b_i, b...
vised, assign dataloader = test dataloader dataloader_test = \ _create_mapping_loader(config, dataset_class, tf3, partitions=config.mapping_test_partitions, target_transform=target_transform) return dataloader_original, dataloader_positive, ...
87
87
291
16
70
MihaiAnton/tudelft-iic-reproduction
src/utils/cluster/baselines/triplets.py
Python
triplets_get_data
triplets_get_data
97
132
97
97
e1e958fc534af526b077511a44ee6557008e447b
bigcode/the-stack
train
e29270a8e29b2784624cfcef
train
function
def triplets_eval(config, net, dataloader_test, sobel): net.eval() if not config.kmeans_on_features: flat_preds_all, flat_targets_all = triplets_get_data(config, net, dataloader_test, sobel) assert (config.output_k == config.gt_k) ...
def triplets_eval(config, net, dataloader_test, sobel):
net.eval() if not config.kmeans_on_features: flat_preds_all, flat_targets_all = triplets_get_data(config, net, dataloader_test, sobel) assert (config.output_k == config.gt_k) else: flat_preds_all, flat_targets_all = triple...
_curr), :] = x_outs.cpu().numpy() flat_targets_all[start_i:(start_i + num_test_curr) ] = flat_targets.cuda() features_all = features_all[:num_test, :] flat_targets_all = flat_targets_all[:num_test] kmeans = KMeans(n_clusters=config.gt_k).fit(features_a...
139
139
465
16
122
MihaiAnton/tudelft-iic-reproduction
src/utils/cluster/baselines/triplets.py
Python
triplets_eval
triplets_eval
179
231
179
179
6bb4d8d7ed56c4ad4a43cf035f3ebdd67f7619f6
bigcode/the-stack
train
71e07f7e3330ae82b6496c67
train
function
def triplets_get_data_kmeans_on_features(config, net, dataloader, sobel): # ouput of network is features (not softmaxed) num_batches = len(dataloader) flat_targets_all = torch.zeros((num_batches * config.batch_sz), dtype=torch.int32).cuda() features_all = np.zeros((num...
def triplets_get_data_kmeans_on_features(config, net, dataloader, sobel): # ouput of network is features (not softmaxed)
num_batches = len(dataloader) flat_targets_all = torch.zeros((num_batches * config.batch_sz), dtype=torch.int32).cuda() features_all = np.zeros((num_batches * config.batch_sz, config.output_k), dtype=np.float32) num_test = 0 for b_i, ba...
[start_i:(start_i + num_test_curr)] = flat_preds_curr flat_targets_all[start_i:(start_i + num_test_curr) ] = flat_targets.cuda() flat_preds_all = flat_preds_all[:num_test] flat_targets_all = flat_targets_all[:num_test] return flat_preds_all, flat_targets_all def triplets_...
104
104
349
34
69
MihaiAnton/tudelft-iic-reproduction
src/utils/cluster/baselines/triplets.py
Python
triplets_get_data_kmeans_on_features
triplets_get_data_kmeans_on_features
135
176
135
136
a5985abbce985b4bf74e54ff01baf7293ccb64a1
bigcode/the-stack
train
1ccf2ea8b387aa09154456fb
train
function
def make_triplets_data(config): target_transform = None if "CIFAR" in config.dataset: config.train_partitions_head_A = [True, False] config.train_partitions_head_B = config.train_partitions_head_A config.mapping_assignment_partitions = [True, False] config.mapping_test_partitio...
def make_triplets_data(config):
target_transform = None if "CIFAR" in config.dataset: config.train_partitions_head_A = [True, False] config.train_partitions_head_B = config.train_partitions_head_A config.mapping_assignment_partitions = [True, False] config.mapping_test_partitions = [True, False] if c...
import numpy as np import torch import torch.nn.functional as F import torchvision from sklearn.cluster import KMeans from src.utils.cluster.data import _cifar100_to_cifar20, \ _create_dataloaders, _create_mapping_loader from src.utils.cluster.eval_metrics import _hungarian_match, _acc from src.utils.cluster.trans...
107
201
672
7
99
MihaiAnton/tudelft-iic-reproduction
src/utils/cluster/baselines/triplets.py
Python
make_triplets_data
make_triplets_data
15
94
15
15
f04423f59ccfab429ffcf972e1a7e0a770fdf197
bigcode/the-stack
train
e0931fa59b7db2d706ad1a93
train
function
def triplets_loss(outs_orig, outs_pos, outs_neg): orig = F.log_softmax(outs_orig, dim=1) pos = F.softmax(outs_pos, dim=1) neg = F.softmax(outs_neg, dim=1) # loss is minimised return F.kl_div(orig, pos, reduction="elementwise_mean") - \ F.kl_div(orig, neg, reduction="elementwise_mean")
def triplets_loss(outs_orig, outs_pos, outs_neg):
orig = F.log_softmax(outs_orig, dim=1) pos = F.softmax(outs_pos, dim=1) neg = F.softmax(outs_neg, dim=1) # loss is minimised return F.kl_div(orig, pos, reduction="elementwise_mean") - \ F.kl_div(orig, neg, reduction="elementwise_mean")
else: config.masses = np.concatenate((config.masses, mass), axis=0) config.per_class_acc = np.concatenate( (config.per_class_acc, per_class_acc), axis=0) return is_best def triplets_loss(outs_orig, outs_pos, outs_neg):
64
64
95
14
49
MihaiAnton/tudelft-iic-reproduction
src/utils/cluster/baselines/triplets.py
Python
triplets_loss
triplets_loss
234
241
234
234
12f6effd8bab0e0426a3c663d6475100b1df7ef0
bigcode/the-stack
train
5ea8010ba1d305f77b540b43
train
class
class MoTagRef(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict...
class MoTagRef(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute ...
# coding: utf-8 """ Intersight REST API This is Intersight REST API OpenAPI spec version: 1.0.9-255 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class MoTagRef(object):
76
216
721
6
69
gumpcraca/intersight-python
intersight/models/mo_tag_ref.py
Python
MoTagRef
MoTagRef
19
149
19
19
0e3b27eff214940387346208493e3cbc5d3638c7
bigcode/the-stack
train
f7ec35a5489af30dfa17d205
train
class
class LyricUtils(object): @staticmethod def parseLyrics(lyricsText: str) -> Dict[int, str]: lyricsLogger = logging.getLogger("lyricUtils") lyricsLogger.setLevel(logging.INFO) lyricsLogger.info("Parsing lyrics ...") lyricRegex = re.compile(r"^((?:\[\d+:[\d.]+])+)(.*)$") ly...
class LyricUtils(object): @staticmethod
def parseLyrics(lyricsText: str) -> Dict[int, str]: lyricsLogger = logging.getLogger("lyricUtils") lyricsLogger.setLevel(logging.INFO) lyricsLogger.info("Parsing lyrics ...") lyricRegex = re.compile(r"^((?:\[\d+:[\d.]+])+)(.*)$") lyricDict: typing.Dict[int, str] = dict() ...
# Created by BaiJiFeiLong@gmail.com at 2022/1/8 23:11 from __future__ import annotations import logging import re import typing if typing.TYPE_CHECKING: from typing import * class LyricUtils(object): @staticmethod
60
124
415
10
50
baijifeilong/rawsteelp
IceSpringMusicPlayer/utils/lyricUtils.py
Python
LyricUtils
LyricUtils
13
48
13
14
76e024b35ee2a96ff950759017eece34ca28e725
bigcode/the-stack
train
6220829a0be0ddcadb2f36f2
train
class
class Quest (JQuest) : def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) self.isSpawned = 0 self.questItemIds = [Starstone,Detector,Detector2,Letter,Starstone2] def activateDetector(self, npc, player, st) : for obj in npc.getKnownList().getKnownObjects().values() : if obj...
class Quest (JQuest) :
def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) self.isSpawned = 0 self.questItemIds = [Starstone,Detector,Detector2,Letter,Starstone2] def activateDetector(self, npc, player, st) : for obj in npc.getKnownList().getKnownObjects().values() : if obj != None : if o...
import sys from com.l2jfrozen.gameserver.ai import CtrlIntention from com.l2jfrozen.gameserver.model.quest import State from com.l2jfrozen.gameserver.model.quest import QuestState from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest from com.l2jfrozen.gameserver.network.serverpackets import Cre...
180
256
3,208
8
171
DigitalCoin1/L2SPERO
datapack/data/scripts/quests/114_ResurrectionOfAnOldManager/__init__.py
Python
Quest
Quest
27
354
27
28
486e836b890ab62fdc734b98636b8422666e4c87
bigcode/the-stack
train
9cc0e4079e0152022da8c4db
train
class
class Decoder(nn.Module): ''' Decoder class. It does not perform any form of normalization. Args: dim (int): input dimension c_dim (int): dimension of latent conditioned code c hidden_size (int): hidden size of Decoder network leaky (bool): whether to use leaky ReLUs ''...
class Decoder(nn.Module):
''' Decoder class. It does not perform any form of normalization. Args: dim (int): input dimension c_dim (int): dimension of latent conditioned code c hidden_size (int): hidden size of Decoder network leaky (bool): whether to use leaky ReLUs ''' def __init__(self, ...
num_points, k, num_dims) x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1) feature = torch.cat((feature-x, x), dim=3).permute(0, 3, 1, 2).contiguous() return feature # (batch_size, 2*num_dims, num_points, k) def maxpool(x, dim=-1, keepdim=False): out, _ = x.max(dim=dim, keep...
127
127
426
5
121
xnozero/sapcu
fn/coder.py
Python
Decoder
Decoder
125
187
125
125
6f4838f46b08b7de86963222eb77983153e3d138
bigcode/the-stack
train
8db362f34cc4881743959597
train
function
def get_graph_feature(x, k=20, idx=None, dim9=False): batch_size = x.size(0) num_points = x.size(2) x = x.view(batch_size, -1, num_points) if idx is None: if dim9 == False: idx = knn(x, k=k) # (batch_size, num_points, k) else: idx = knn(x[:, 6:], k=k) devi...
def get_graph_feature(x, k=20, idx=None, dim9=False):
batch_size = x.size(0) num_points = x.size(2) x = x.view(batch_size, -1, num_points) if idx is None: if dim9 == False: idx = knn(x, k=k) # (batch_size, num_points, k) else: idx = knn(x[:, 6:], k=k) device = torch.device('cuda') idx_base = torch.arange...
) -> (batch_size, emb_dims) x2 = F.adaptive_avg_pool1d(x, 1).view(batch_size, -1) # (batch_size, emb_dims, num_points) -> (batch_size, emb_dims) x = torch.cat((x1, x2), 1) # (batch_size, emb_dims*2) return x def get_graph_feature(x, k=20, idx=None, dim9=False):
99
99
330
17
81
xnozero/sapcu
fn/coder.py
Python
get_graph_feature
get_graph_feature
85
116
85
85
42f0771204fd77783b500afbf85eba025f236a60
bigcode/the-stack
train
04d6b278a9e1eab3136b284f
train
class
class pyramid_Decoder3(nn.Module): def __init__(self): super().__init__() # Submodules self.fc_c = nn.Linear(2048, 1024) self.bn0 = nn.BatchNorm1d(1024) self.block1 = nn.Linear(1024, 512) self.bn1 = nn.BatchNorm1d(512) self.block2 = nn.Linear(512, 12...
class pyramid_Decoder3(nn.Module):
def __init__(self): super().__init__() # Submodules self.fc_c = nn.Linear(2048, 1024) self.bn0 = nn.BatchNorm1d(1024) self.block1 = nn.Linear(1024, 512) self.bn1 = nn.BatchNorm1d(512) self.block2 = nn.Linear(512, 128) self.bn2 = nn.BatchNorm1d(128)...
= self.block0(net) net = self.block1(net) net = self.block2(net) net = self.block3(net) net = self.block4(net) #print(net.shape) out = self.fc_out(self.actvn(net)) return out class pyramid_Decoder3(nn.Module):
69
69
232
10
58
xnozero/sapcu
fn/coder.py
Python
pyramid_Decoder3
pyramid_Decoder3
190
218
190
192
5648dad0d9b6ae72228659f96f630a0b2f9103ff
bigcode/the-stack
train
8c1968a8bf31189517004d15
train
function
def maxpool(x, dim=-1, keepdim=False): out, _ = x.max(dim=dim, keepdim=keepdim) return out
def maxpool(x, dim=-1, keepdim=False):
out, _ = x.max(dim=dim, keepdim=keepdim) return out
feature = torch.cat((feature-x, x), dim=3).permute(0, 3, 1, 2).contiguous() return feature # (batch_size, 2*num_dims, num_points, k) def maxpool(x, dim=-1, keepdim=False):
64
64
34
13
51
xnozero/sapcu
fn/coder.py
Python
maxpool
maxpool
120
122
120
120
716d98db68eff6a604a5a6d46f940a8cae37298d
bigcode/the-stack
train
d13253f9e702b05d66744ea7
train
function
def knn(x, k): inner = -2*torch.matmul(x.transpose(2, 1), x) xx = torch.sum(x**2, dim=1, keepdim=True) pairwise_distance = -xx - inner - xx.transpose(2, 1) idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k) return idx
def knn(x, k):
inner = -2*torch.matmul(x.transpose(2, 1), x) xx = torch.sum(x**2, dim=1, keepdim=True) pairwise_distance = -xx - inner - xx.transpose(2, 1) idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k) return idx
.nn as nn import torch import torch.nn.functional as F import numpy as np from fn.layers import ResnetBlockFC, CResnetBlockConv1d, CBatchNorm1d, CBatchNorm1d_legacy, ResnetBlockConv1d def knn(x, k):
64
64
93
7
56
xnozero/sapcu
fn/coder.py
Python
knn
knn
7
13
7
7
a91c20e44f8b3a40cb747d548f93b3c50221709d
bigcode/the-stack
train
ab8d7171e8093161e8e863c7
train
class
class DGCNN_cls(nn.Module): def __init__(self, k, emb_dims): super(DGCNN_cls, self).__init__() self.k = k self.emb_dims = emb_dims self.bn1 = nn.BatchNorm2d(64) self.bn2 = nn.BatchNorm2d(64) self.bn3 = nn.BatchNorm2d(128) self.bn4 = nn.BatchNorm2d(256) ...
class DGCNN_cls(nn.Module):
def __init__(self, k, emb_dims): super(DGCNN_cls, self).__init__() self.k = k self.emb_dims = emb_dims self.bn1 = nn.BatchNorm2d(64) self.bn2 = nn.BatchNorm2d(64) self.bn3 = nn.BatchNorm2d(128) self.bn4 = nn.BatchNorm2d(256) self.bn5 = nn.BatchNorm1d(s...
import torch.nn as nn import torch import torch.nn.functional as F import numpy as np from fn.layers import ResnetBlockFC, CResnetBlockConv1d, CBatchNorm1d, CBatchNorm1d_legacy, ResnetBlockConv1d def knn(x, k): inner = -2*torch.matmul(x.transpose(2, 1), x) xx = torch.sum(x**2, dim=1, keepdim=True) pairwise...
199
256
1,186
8
191
xnozero/sapcu
fn/coder.py
Python
DGCNN_cls
DGCNN_cls
17
82
17
17
b564e6e0b4802f52d83bd446f51c70727d9688a7
bigcode/the-stack
train
7409155ad208ee2e23aca979
train
function
def cos_sim(x1, x2): scores = torch.acos(torch.cosine_similarity(x1, x2, dim=1))/np.pi*180 return scores.mean()
def cos_sim(x1, x2):
scores = torch.acos(torch.cosine_similarity(x1, x2, dim=1))/np.pi*180 return scores.mean()
keepdim=True) pairwise_distance = -xx - inner - xx.transpose(2, 1) idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k) return idx def cos_sim(x1, x2):
64
64
39
9
54
xnozero/sapcu
fn/coder.py
Python
cos_sim
cos_sim
14
16
14
14
4db5652faec81597bb3f169ee624228cd226f34e
bigcode/the-stack
train
e06c4dba66c1e90d76b23dc8
train
class
class OccupancyNetwork(nn.Module): def __init__(self, decoder, encoder, device): super().__init__() decoder=nn.DataParallel(decoder) encoder=nn.DataParallel(encoder) self.decoder = decoder.to(device) self.encoder = encoder.to(device) self._device = device def f...
class OccupancyNetwork(nn.Module):
def __init__(self, decoder, encoder, device): super().__init__() decoder=nn.DataParallel(decoder) encoder=nn.DataParallel(encoder) self.decoder = decoder.to(device) self.encoder = encoder.to(device) self._device = device def forward(self, inputs): c = s...
.relu(self.bn1(self.block1(x))) x=F.relu(self.bn2(self.block2(x))) # bnumber,512 -> # bnumber,128 x=F.normalize(self.bn3(self.fc_out(x)),dim=1) return x class OccupancyNetwork(nn.Module):
63
64
179
7
55
xnozero/sapcu
fn/coder.py
Python
OccupancyNetwork
OccupancyNetwork
222
253
222
223
28503b39a7eee208b20783f7ab979e7bf5eea478
bigcode/the-stack
train
fe1167360c3625c39a0f7ffd
train
class
@dataclass(frozen=True) class CopyTargetMixin: src_task_id: str dest_task_id: str
@dataclass(frozen=True) class CopyTargetMixin:
src_task_id: str dest_task_id: str
.cli import ( COMMAND_LINE_ERROR_STATUS_CODE, AbstractCommandLineInterface, AbstractCommandLineWithConfirmInterface, ArgumentParser, build_annofabapi_resource_and_login, get_list_from_args, ) logger = logging.getLogger(__name__) @dataclass(frozen=True) class CopyTargetMixin:
64
64
25
11
53
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
CopyTargetMixin
CopyTargetMixin
28
31
28
29
d1d4352678462d7e2d5040342328268d75d445f0
bigcode/the-stack
train
e93fbeac1ae41381e4ef11fb
train
class
class CopyTarget(CopyTargetMixin, ABC): @property @abstractmethod def src(self): pass @property @abstractmethod def dest(self): pass
class CopyTarget(CopyTargetMixin, ABC): @property @abstractmethod
def src(self): pass @property @abstractmethod def dest(self): pass
api_resource_and_login, get_list_from_args, ) logger = logging.getLogger(__name__) @dataclass(frozen=True) class CopyTargetMixin: src_task_id: str dest_task_id: str class CopyTarget(CopyTargetMixin, ABC): @property @abstractmethod
64
64
44
19
44
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
CopyTarget
CopyTarget
34
43
34
36
1659dca172fa848d4ee3f5b8ee5559d263dc073c
bigcode/the-stack
train
2141499a075744694252c210
train
class
@dataclass(frozen=True) class CopyTargetByInputData(CopyTarget): src_input_data_id: str dest_input_data_id: str @property def src(self): return f"{self.src_task_id}/{self.src_input_data_id}" @property def dest(self): return f"{self.dest_task_id}/{self.dest_input_data_id}"
@dataclass(frozen=True) class CopyTargetByInputData(CopyTarget):
src_input_data_id: str dest_input_data_id: str @property def src(self): return f"{self.src_task_id}/{self.src_input_data_id}" @property def dest(self): return f"{self.dest_task_id}/{self.dest_input_data_id}"
=True) class CopyTargetByTask(CopyTarget): @property def src(self): return f"{self.src_task_id}" @property def dest(self): return f"{self.dest_task_id}" @dataclass(frozen=True) class CopyTargetByInputData(CopyTarget):
63
64
80
16
47
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
CopyTargetByInputData
CopyTargetByInputData
57
68
57
58
b9c06e2166bb022cef54bc7272f48f9fee4d2acf
bigcode/the-stack
train
cda01e1ba7a246b8f3612b48
train
function
def parse_args(parser: argparse.ArgumentParser): argument_parser = ArgumentParser(parser) argument_parser.add_project_id() INPUT_HELP_MESSAGE = """アノテーションのコピー元とコピー先を':'で区切って指定します。 タスク単位でコピーする場合の例: ``src_task_id:dest_task_id`` 入力データ単位でコピーする場合: ``src_task_id/src_input_data_id:dest_task_id/dest_input_...
def parse_args(parser: argparse.ArgumentParser):
argument_parser = ArgumentParser(parser) argument_parser.add_project_id() INPUT_HELP_MESSAGE = """アノテーションのコピー元とコピー先を':'で区切って指定します。 タスク単位でコピーする場合の例: ``src_task_id:dest_task_id`` 入力データ単位でコピーする場合: ``src_task_id/src_input_data_id:dest_task_id/dest_input_data_id`` ``file://`` を先頭に付けると、コピー元とコピー先が記載され...
(copy_target_list): print(f"{self.COMMON_MESSAGE} argument '--input' の値が不正です。", file=sys.stderr) sys.exit(COMMAND_LINE_ERROR_STATUS_CODE) main_obj = CopyAnnotationMain( self.service, all_yes=self.all_yes, overwrite=args.overwrite, merge=args.merge, force=args.force )...
131
131
438
9
122
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
parse_args
parse_args
303
331
303
303
0b76b68c544a1546ed5c49640068a16aa8a56750
bigcode/the-stack
train
299b709457e3f0df31ba5895
train
function
def main(args): service = build_annofabapi_resource_and_login(args) facade = AnnofabApiFacade(service) CopyAnnotation(service, facade, args).main()
def main(args):
service = build_annofabapi_resource_and_login(args) facade = AnnofabApiFacade(service) CopyAnnotation(service, facade, args).main()
", file=sys.stderr) sys.exit(COMMAND_LINE_ERROR_STATUS_CODE) main_obj = CopyAnnotationMain( self.service, all_yes=self.all_yes, overwrite=args.overwrite, merge=args.merge, force=args.force ) main_obj.copy_annotations(project_id, copy_target_list) def main(args):
64
64
38
4
60
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
main
main
297
300
297
297
a2a053e460f65f76dfeea0ef9a4febe5ff35ed11
bigcode/the-stack
train
f63a046969b33fbb70a5835e
train
function
def get_copy_target_list(str_copy_target_list: list[str]) -> list[CopyTarget]: """コマンドラインから受けとった文字列のlistから、コピー対象のlistを取得する。""" copy_target_list: list[CopyTarget] = [] for str_copy_target in str_copy_target_list: try: copy_target = parse_copy_target(str_copy_target) copy_targ...
def get_copy_target_list(str_copy_target_list: list[str]) -> list[CopyTarget]:
"""コマンドラインから受けとった文字列のlistから、コピー対象のlistを取得する。""" copy_target_list: list[CopyTarget] = [] for str_copy_target in str_copy_target_list: try: copy_target = parse_copy_target(str_copy_target) copy_target_list.append(copy_target) except ValueError as e: logger....
: return CopyTargetByTask(src_task_id=src_task_id, dest_task_id=dest_task_id) else: raise ValueError(f"'{str_copy_target}' の形式が間違っています。") def get_copy_target_list(str_copy_target_list: list[str]) -> list[CopyTarget]:
64
64
108
19
45
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
get_copy_target_list
get_copy_target_list
114
124
114
114
944b40442e4dffc27356f06ba787b4a46759ea06
bigcode/the-stack
train
92a6151ea7842f9db7b64701
train
class
class CopyAnnotationMain(AbstractCommandLineWithConfirmInterface): def __init__(self, service: annofabapi.Resource, *, all_yes: bool, overwrite: bool, merge: bool, force: bool): self.service = service self.overwrite = overwrite self.merge = merge self.force = force Abstract...
class CopyAnnotationMain(AbstractCommandLineWithConfirmInterface):
def __init__(self, service: annofabapi.Resource, *, all_yes: bool, overwrite: bool, merge: bool, force: bool): self.service = service self.overwrite = overwrite self.merge = merge self.force = force AbstractCommandLineWithConfirmInterface.__init__(self, all_yes) def co...
= _parse_with_slash(str_dest) if src_input_data_id is not None and dest_input_data_id is not None: return CopyTargetByInputData( src_task_id=src_task_id, src_input_data_id=src_input_data_id, dest_task_id=dest_task_id, dest_input_data_id=dest_input_data_id, ...
256
256
1,593
11
244
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
CopyAnnotationMain
CopyAnnotationMain
127
275
127
127
aa120beec16a0ad9a6b86d2de30d9561d0d71329
bigcode/the-stack
train
1963a766e6de4d0dedf97467
train
class
@dataclass(frozen=True) class CopyTargetByTask(CopyTarget): @property def src(self): return f"{self.src_task_id}" @property def dest(self): return f"{self.dest_task_id}"
@dataclass(frozen=True) class CopyTargetByTask(CopyTarget): @property
def src(self): return f"{self.src_task_id}" @property def dest(self): return f"{self.dest_task_id}"
class CopyTarget(CopyTargetMixin, ABC): @property @abstractmethod def src(self): pass @property @abstractmethod def dest(self): pass @dataclass(frozen=True) class CopyTargetByTask(CopyTarget): @property
64
64
51
19
44
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
CopyTargetByTask
CopyTargetByTask
46
54
46
48
f739b806b435b99d3029eabc4509205faa1b8e21
bigcode/the-stack
train
2922edc876f68a363f968fdb
train
class
class CopyAnnotation(AbstractCommandLineInterface): COMMON_MESSAGE = "annofabcli annotation copy: error:" def main(self): args = self.args project_id = args.project_id str_copy_target_list = get_list_from_args(args.input) copy_target_list = get_copy_target_list(str_copy_target_...
class CopyAnnotation(AbstractCommandLineInterface):
COMMON_MESSAGE = "annofabcli annotation copy: error:" def main(self): args = self.args project_id = args.project_id str_copy_target_list = get_list_from_args(args.input) copy_target_list = get_copy_target_list(str_copy_target_list) if len(str_copy_target_list) != len(co...
InputData): self.copy_annotation_by_input_data(project_id, copy_target) # 担当者を元に戻す if changed_operator: self.service.wrapper.change_task_operator(project_id, copy_target.dest_task_id, original_operator) return True class CopyAnnotation(AbstractCommandLine...
64
64
163
8
55
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
CopyAnnotation
CopyAnnotation
278
294
278
278
629b5aec2fa16810e821590c671e30304f3dfc29
bigcode/the-stack
train
56e2e24ed8dac2847a592824
train
function
def add_parser(subparsers: Optional[argparse._SubParsersAction] = None): subcommand_name = "copy" subcommand_help = "アノテーションをコピーします." description = "アノテーションをコピーします。" parser = annofabcli.common.cli.add_parser(subparsers, subcommand_name, subcommand_help, description) parse_args(parser) return par...
def add_parser(subparsers: Optional[argparse._SubParsersAction] = None):
subcommand_name = "copy" subcommand_help = "アノテーションをコピーします." description = "アノテーションをコピーします。" parser = annofabcli.common.cli.add_parser(subparsers, subcommand_name, subcommand_help, description) parse_args(parser) return parser
自分自身でない場合、タスクの担当者を一時的に自分自身に変更してからアノテーションをコピーします。" ) parser.set_defaults(subcommand_func=main) def add_parser(subparsers: Optional[argparse._SubParsersAction] = None):
64
64
89
19
45
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
add_parser
add_parser
334
340
334
334
fa68c2847359b5fbcc373b2d8e7cbdeb05a24db0
bigcode/the-stack
train
2f86ad9df3a7e43b84472e2a
train
function
def parse_copy_target(str_copy_target: str) -> CopyTarget: """ コピー対象の文字列をパースします。 以下の文字列をサポートします。 * `task1:task2` * `task1/input5:task2/input6` """ def _parse_with_slash(target: str) -> Tuple[str, Optional[str]]: tmp = target.split("/") if len(tmp) == 1: return (t...
def parse_copy_target(str_copy_target: str) -> CopyTarget:
""" コピー対象の文字列をパースします。 以下の文字列をサポートします。 * `task1:task2` * `task1/input5:task2/input6` """ def _parse_with_slash(target: str) -> Tuple[str, Optional[str]]: tmp = target.split("/") if len(tmp) == 1: return (tmp[0], None) elif len(tmp) == 2: return...
(frozen=True) class CopyTargetByInputData(CopyTarget): src_input_data_id: str dest_input_data_id: str @property def src(self): return f"{self.src_task_id}/{self.src_input_data_id}" @property def dest(self): return f"{self.dest_task_id}/{self.dest_input_data_id}" # CopyTarget ...
110
110
367
14
96
kurusugawa-computer/annofab-cli
annofabcli/annotation/copy_annotation.py
Python
parse_copy_target
parse_copy_target
74
111
74
74
292ed56077a27eb79de304855276325f532cddef
bigcode/the-stack
train
37a6c23c57dce668d536d590
train
function
def test_keplerian_light_curve(): t = np.linspace(50, 1000, 1045) r = np.array([0.04, 0.02]) args = dict( period=[50.0, 87.5], t0=[1.55, 10.6], ecc=[0.28, 0.01], omega=[-4.56, 1.5], m_planet=[0.0, 0.0], b=[0.51, 0.21], m_star=1.51, r_star=1.0, ...
def test_keplerian_light_curve():
t = np.linspace(50, 1000, 1045) r = np.array([0.04, 0.02]) args = dict( period=[50.0, 87.5], t0=[1.55, 10.6], ecc=[0.28, 0.01], omega=[-4.56, 1.5], m_planet=[0.0, 0.0], b=[0.51, 0.21], m_star=1.51, r_star=1.0, ) orbit0 = KeplerianOrbit(...
.allclose(x0, x02) assert np.allclose(y0, y02) assert np.allclose(z0, z02) assert np.allclose(x, x2) assert np.allclose(y, y2) assert np.allclose(z, z2) def test_keplerian_light_curve():
68
68
228
8
60
ericagol/exoplanet
src/exoplanet/orbits/rebound_test.py
Python
test_keplerian_light_curve
test_keplerian_light_curve
104
124
104
104
b153814fc70d6011631d0d6c0e1a60971ad76e68
bigcode/the-stack
train
dadaf7a9a95f5b8c722bd447
train
function
@pytest.mark.parametrize( "orbit", ( ReboundOrbit( period=50.0, t0=1.55, ecc=0.28, omega=-4.56, m_planet=0.12, b=0.51, m_star=1.51, r_star=1.0, ), ReboundOrbit( period=[50.0, 87.5]...
@pytest.mark.parametrize( "orbit", ( ReboundOrbit( period=50.0, t0=1.55, ecc=0.28, omega=-4.56, m_planet=0.12, b=0.51, m_star=1.51, r_star=1.0, ), ReboundOrbit( period=[50.0, 87.5]...
t = np.linspace(50, 1000, 1045) x, y, z = theano.function([], orbit.get_relative_position(t))() x0, y0, z0 = theano.function( [], super(ReboundOrbit, orbit).get_relative_position(t) )() assert np.allclose(x, x0) assert np.allclose(y, y0) assert np.allclose(z, z0) x, y, z = thea...
@pytest.mark.parametrize( "orbit", ( ReboundOrbit( period=50.0, t0=1.55, ecc=0.28, omega=-4.56, m_planet=0.12, b=0.51, m_star=1.51, r_star=1.0, ), ReboundOrbit( period=[50.0, 87.5]...
188
151
506
188
0
ericagol/exoplanet
src/exoplanet/orbits/rebound_test.py
Python
test_keplerian
test_keplerian
12
67
12
37
73a7fac0fccdef64586fc2cde60e98f79f28233d
bigcode/the-stack
train
264d7195798b97d6f02afd6f
train
function
@pytest.mark.xfail(reason="I don't understand Theano sometimes") def test_tensor_bug(): orbit = ReboundOrbit( period=50.0, t0=0.0, ecc=0.5, omega=0.1, b=0.2, m_planet=0.5 ) orbit2 = ReboundOrbit( period=50.0, t0=0.0, ecc=0.5 + 1e-9, omega=0.1, b=0.2, m...
@pytest.mark.xfail(reason="I don't understand Theano sometimes") def test_tensor_bug():
orbit = ReboundOrbit( period=50.0, t0=0.0, ecc=0.5, omega=0.1, b=0.2, m_planet=0.5 ) orbit2 = ReboundOrbit( period=50.0, t0=0.0, ecc=0.5 + 1e-9, omega=0.1, b=0.2, m_planet=0.5 - 1e-9, ) t = np.linspace(50, 1000, 1045) x, y, z = theano.func...
(x, np.sum(x0, axis=-1)) assert np.allclose(y, np.sum(y0, axis=-1)) assert np.allclose(z, np.sum(z0, axis=-1)) else: assert np.allclose(x, x0) assert np.allclose(y, y0) assert np.allclose(z, z0) @pytest.mark.xfail(reason="I don't understand Theano sometimes") def test_tensor_...
94
94
316
18
76
ericagol/exoplanet
src/exoplanet/orbits/rebound_test.py
Python
test_tensor_bug
test_tensor_bug
70
101
70
71
6467f38d34e24326b62c594d47843cf69809fc20
bigcode/the-stack
train
d5f9ec597a23f1f480d9135f
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_queries(database_url): """ Test that the basic `execute()`, `execute_many()`, `fetch_all()``, and `fetch_one()` interfaces are all supported (using SQLAlchemy core). """ async with Database(database...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_queries(database_url):
""" Test that the basic `execute()`, `execute_many()`, `fetch_all()``, and `fetch_one()` interfaces are all supported (using SQLAlchemy core). """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): # execute() query = ...
mysql", "mysql+aiomysql", "mysql+asyncmy"]: url = str(database_url.replace(driver="pymysql")) elif database_url.scheme in [ "postgresql+aiopg", "sqlite+aiosqlite", "postgresql+asyncpg", ]: url = str(database_url.replace(driver=None)) en...
188
188
627
26
161
irulast/databases
tests/test_databases.py
Python
test_queries
test_queries
148
223
148
151
fa36890a0e308c43d7d20f3b901ec5a902674a62
bigcode/the-stack
train
d96d6ab2f58a29d71855b02c
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_queries_with_expose_backend_connection(database_url): """ Replication of `execute()`, `execute_many()`, `fetch_all()``, and `fetch_one()` using the raw driver interface. """ async with Database(data...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_queries_with_expose_backend_connection(database_url):
""" Replication of `execute()`, `execute_many()`, `fetch_all()``, and `fetch_one()` using the raw driver interface. """ async with Database(database_url) as database: async with database.connection() as connection: async with connection.transaction(force_rollback=True): ...
() async def get_connection_2(): nonlocal connection_2 async with database.connection() as connection: connection_2 = connection await test_complete.wait() loop = asyncio.get_event_loop() task_1 = loop.create_task(get_connection_1()) ...
256
256
880
31
224
irulast/databases
tests/test_databases.py
Python
test_queries_with_expose_backend_connection
test_queries_with_expose_backend_connection
891
995
891
894
fa6400e269cf88d90984398af7573752ee64ed3e
bigcode/the-stack
train
05923263a7e0f6bcb885fb36
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_database_url_interface(database_url): """ Test that Database instances expose a `.url` attribute. """ async with Database(database_url) as database: assert isinstance(database.url, DatabaseURL) ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_database_url_interface(database_url):
""" Test that Database instances expose a `.url` attribute. """ async with Database(database_url) as database: assert isinstance(database.url, DatabaseURL) assert database.url == database_url
result = await cursor.fetchone() # Raw output for the raw request assert result[1] == "example1" assert result[2] == True @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_database_url_interface(data...
64
64
71
28
35
irulast/databases
tests/test_databases.py
Python
test_database_url_interface
test_database_url_interface
998
1,007
998
1,001
4070b9cc2f90bb0c332277003ac7d985b7835977
bigcode/the-stack
train
d37cb8c4f0b0b6a4ac3eada0
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_decimal_field(database_url): """ Test Decimal (NUMERIC) columns, to ensure records are coerced to/from proper Python types. """ async with Database(database_url) as database: async with databas...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_decimal_field(database_url):
""" Test Decimal (NUMERIC) columns, to ensure records are coerced to/from proper Python types. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): price = decimal.Decimal("0.700000000000001") # execute() q...
(query=query) assert len(results) == 1 assert results[0]["title"] == "Hello, world" assert results[0]["published"] == now @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_decimal_field(database_url):
64
64
198
27
36
irulast/databases
tests/test_databases.py
Python
test_decimal_field
test_decimal_field
686
711
686
689
daaa0d0096e25d1b87821d111d6c24a0fa95602f
bigcode/the-stack
train
0ea7c457fc9320d636a6aabd
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @async_adapter async def test_posgres_interface(database_url): """ Since SQLAlchemy 1.4, `Row.values()` is removed and `Row.keys()` is deprecated. Custom postgres interface mimics more or less this behaviour by deprecating those two methods """...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @async_adapter async def test_posgres_interface(database_url):
""" Since SQLAlchemy 1.4, `Row.values()` is removed and `Row.keys()` is deprecated. Custom postgres interface mimics more or less this behaviour by deprecating those two methods """ database_url = DatabaseURL(database_url) if database_url.scheme not in ["postgresql", "postgresql+asyncpg"]: ...
): """ Test parallel transaction execution. """ async def test_task(db): async with db.transaction(): await db.fetch_one("SELECT 1") async with Database(database_url) as database: await database.fetch_one("SELECT 1") tasks = [test_task(database) for i in range(...
101
101
339
24
77
irulast/databases
tests/test_databases.py
Python
test_posgres_interface
test_posgres_interface
1,148
1,191
1,148
1,150
32c714053de0509dc60806e8702c2a3854be6418
bigcode/the-stack
train
51b3b20954de5cc42bb0d9d5
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_rollback_low_level(database_url): """ Ensure that an explicit `await transaction.rollback()` is supported. """ async with Database(database_url) as database: async with database.tra...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_rollback_low_level(database_url):
""" Ensure that an explicit `await transaction.rollback()` is supported. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): transaction = await database.transaction() try: query = notes.insert().values...
() else: await transaction.commit() query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 1 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_rollback_...
64
64
151
30
33
irulast/databases
tests/test_databases.py
Python
test_transaction_rollback_low_level
test_transaction_rollback_low_level
605
627
605
608
5ec331bbaf263fd9056b1fb4154ddb2ee77fdb01
bigcode/the-stack
train
889907020935797ec1490d54
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_decorator(database_url): """ Ensure that @database.transaction() is supported. """ database = Database(database_url, force_rollback=True) @database.transaction() async def insert_da...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_decorator(database_url):
""" Ensure that @database.transaction() is supported. """ database = Database(database_url, force_rollback=True) @database.transaction() async def insert_data(raise_exception): query = notes.insert().values(text="example", completed=True) await database.execute(query) if...
# pragma: no cover await transaction.commit() query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 0 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_decorator(...
64
64
178
28
35
irulast/databases
tests/test_databases.py
Python
test_transaction_decorator
test_transaction_decorator
630
658
630
633
bf2f2a268fa472d08b1199d4795a8eb40b0e358e
bigcode/the-stack
train
581640d864edce9159176fa2
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_datetime_field(database_url): """ Test DataTime columns, to ensure records are coerced to/from proper Python types. """ async with Database(database_url) as database: async with database.transa...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_datetime_field(database_url):
""" Test DataTime columns, to ensure records are coerced to/from proper Python types. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): now = datetime.datetime.now().replace(microsecond=0) # execute() qu...
0 await insert_data(raise_exception=False) query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 1 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_datetime_field(database_url):
64
64
172
27
36
irulast/databases
tests/test_databases.py
Python
test_datetime_field
test_datetime_field
661
683
661
664
2d94d5a30477c8005e969c037f4cc9fbdc8a17ea
bigcode/the-stack
train
b878576896fda7804cd2483c
train
function
@async_adapter async def test_should_maintain_ref_when_cache_param(): async with Database("sqlite:///file::memory:?cache=shared", uri=True) as database: query = sqlalchemy.schema.CreateTable(notes) await database.execute(query) query = notes.insert() values = {"text": "example1", "c...
@async_adapter async def test_should_maintain_ref_when_cache_param():
async with Database("sqlite:///file::memory:?cache=shared", uri=True) as database: query = sqlalchemy.schema.CreateTable(notes) await database.execute(query) query = notes.insert() values = {"text": "example1", "completed": True} await database.execute(query, values) ...
(notes) await database.execute(query) query = notes.insert() values = {"text": "example1", "completed": True} with pytest.raises(sqlite3.OperationalError): await database.execute(query, values) @async_adapter async def test_should_maintain_ref_when_cache_param():
64
64
122
16
48
irulast/databases
tests/test_databases.py
Python
test_should_maintain_ref_when_cache_param
test_should_maintain_ref_when_cache_param
1,240
1,253
1,240
1,241
2c1fadd2087f8ceb0f13961e03f573711bef28ec
bigcode/the-stack
train
3fd5b702501c3333a135eafa
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connection_context(database_url): """ Test connection contexts are task-local. """ async with Database(database_url) as database: async with database.connection() as connection_1: as...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connection_context(database_url):
""" Test connection contexts are task-local. """ async with Database(database_url) as database: async with database.connection() as connection_1: async with database.connection() as connection_2: assert connection_1 is connection_2 async with Database(database_ur...
await database.disconnect() assert not database.is_connected # connect and disconnect idempotence await database.connect() await database.connect() assert database.is_connected await database.disconnect() await database.disconnect() assert not database.is_connected @pytest.mark.para...
81
81
272
27
53
irulast/databases
tests/test_databases.py
Python
test_connection_context
test_connection_context
835
874
835
838
5138359dccddb142f0193f094719613d511aa9c0
bigcode/the-stack
train
b7bb27cbeea161f8cf47f780
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_parallel_transactions(database_url): """ Test parallel transaction execution. """ async def test_task(db): async with db.transaction(): await db.fetch_one("SELECT 1") async wit...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_parallel_transactions(database_url):
""" Test parallel transaction execution. """ async def test_task(db): async with db.transaction(): await db.fetch_one("SELECT 1") async with Database(database_url) as database: await database.fetch_one("SELECT 1") tasks = [test_task(database) for i in range(4)]...
mapping.keys()) == ["completed", "id", "text"] assert results[0]["text"] == "example1" assert results[0]["completed"] == True @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_parallel_transactions(database_url):
64
64
103
27
36
irulast/databases
tests/test_databases.py
Python
test_parallel_transactions
test_parallel_transactions
1,129
1,145
1,129
1,132
12ba15b41868e1406b30425f1b21bb10cca55fe4
bigcode/the-stack
train
d43f995e868d8a90bce46e39
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit_serializable(database_url): """ Ensure that serializable transaction commit via extra parameters is supported. """ database_url = DatabaseURL(database_url) if database_url.schem...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit_serializable(database_url):
""" Ensure that serializable transaction commit via extra parameters is supported. """ database_url = DatabaseURL(database_url) if database_url.scheme not in ["postgresql", "postgresql+asyncpg"]: pytest.skip("Test (currently) only supports asyncpg") if database_url.scheme == "postgres...
async with database.transaction(): query = notes.insert().values(text="example1", completed=True) await database.execute(query) query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 1 @pytest.mark.pa...
81
81
273
29
51
irulast/databases
tests/test_databases.py
Python
test_transaction_commit_serializable
test_transaction_commit_serializable
513
555
513
516
8dc92a983b86dd43d949f1afd34926b258f3936d
bigcode/the-stack
train
65c28398a1a237c05588092e
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_results_support_mapping_interface(database_url): """ Casting results to a dict should work, since the interface defines them as supporting the mapping interface. """ async with Database(database_ur...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_results_support_mapping_interface(database_url):
""" Casting results to a dict should work, since the interface defines them as supporting the mapping interface. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): # execute() query = notes.insert() va...
): with pytest.raises(DBException): query = notes.select() await database.fetch_all(query) query = notes.select() await database.fetch_all(query) @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_res...
64
64
213
29
35
irulast/databases
tests/test_databases.py
Python
test_results_support_mapping_interface
test_results_support_mapping_interface
332
358
332
335
070cfe3648ffc9898e509441b99e14f1e30dc747
bigcode/the-stack
train
4d5f292d3d2dd211cbe7cd6b
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_queries_after_error(database_url): """ Test that the basic `execute()` works after a previous error. """ class DBException(Exception): pass async with Database(database_url) as database: ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_queries_after_error(database_url):
""" Test that the basic `execute()` works after a previous error. """ class DBException(Exception): pass async with Database(database_url) as database: with patch.object( database.connection()._connection, "acquire", new=AsyncMock(side_effect=DBE...
() query = sqlalchemy.schema.DropTable(notes) await database.execute(query) # CreateTable() query = sqlalchemy.schema.CreateTable(notes) await database.execute(query) @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async...
64
64
128
28
36
irulast/databases
tests/test_databases.py
Python
test_queries_after_error
test_queries_after_error
307
329
307
310
37e783e6dd50a1e3c2ac8fcc48a170e531a87e5f
bigcode/the-stack
train
30d6c5b0ada98e84001ed4db
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connection_context_with_raw_connection(database_url): """ Test connection contexts with respect to the raw connection. """ async with Database(database_url) as database: async with database.conn...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connection_context_with_raw_connection(database_url):
""" Test connection contexts with respect to the raw connection. """ async with Database(database_url) as database: async with database.connection() as connection_1: async with database.connection() as connection_2: assert connection_1 is connection_2 ...
(0.000001) assert connection_1 is not connection_2 test_complete.set() await task_1 await task_2 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connection_context_with_raw_connection(database_url):
64
64
101
30
33
irulast/databases
tests/test_databases.py
Python
test_connection_context_with_raw_connection
test_connection_context_with_raw_connection
877
888
877
880
6758cbe7ad0462541a8d987b7528bc2a1a91d77d
bigcode/the-stack
train
4f37a5d5167bd0b60fd9c841
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connect_and_disconnect(database_url): """ Test explicit connect() and disconnect(). """ database = Database(database_url) assert not database.is_connected await database.connect() assert da...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connect_and_disconnect(database_url):
""" Test explicit connect() and disconnect(). """ database = Database(database_url) assert not database.is_connected await database.connect() assert database.is_connected await database.disconnect() assert not database.is_connected # connect and disconnect idempotence await...
.select() results = await database.fetch_all(query=query) assert len(results) == 1 finally: query = notes.delete() await database.execute(query) @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connect_and_disco...
64
64
119
28
36
irulast/databases
tests/test_databases.py
Python
test_connect_and_disconnect
test_connect_and_disconnect
811
832
811
814
3974ba349abfe27d6fc649dffb1d89d6b77e4353
bigcode/the-stack
train
00ceab546e11801c1a7911d5
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connections_isolation(database_url): """ Ensure that changes are visible between different connections. To check this we have to not create a transaction, so that each query ends up on a different conne...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connections_isolation(database_url):
""" Ensure that changes are visible between different connections. To check this we have to not create a transaction, so that each query ends up on a different connection from the pool. """ async with Database(database_url) as database: try: query = notes.insert().values(tex...
=query) assert len(results) == 1 assert results[0]["title"] == "Hello, world" assert results[0]["published"] == today @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_connections_isolation(database_url):
64
64
144
28
35
irulast/databases
tests/test_databases.py
Python
test_connections_isolation
test_connections_isolation
763
783
763
766
f6226174962640e6eda7eb47f5fed6f582476fdc
bigcode/the-stack
train
9b3fa7508a3bd759e793c89d
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_result_named_access(database_url): async with Database(database_url) as database: query = notes.insert() values = {"text": "example1", "completed": True} await database.execute(query, values...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_result_named_access(database_url):
async with Database(database_url) as database: query = notes.insert() values = {"text": "example1", "completed": True} await database.execute(query, values) query = notes.select().where(notes.c.text == "example1") result = await database.fetch_one(query=query) asser...
query = notes.select().where(notes.c.id.in_([2, 3])) results = await database.fetch_all(query=query) assert len(results) == 0 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_result_named_access(database_url):
64
64
108
28
35
irulast/databases
tests/test_databases.py
Python
test_result_named_access
test_result_named_access
1,212
1,225
1,212
1,215
ce6fab9f1c18b02b903945ba1bd2a8a82fefaeb9
bigcode/the-stack
train
902c3ecca28a0133aa9f581c
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_ddl_queries(database_url): """ Test that the built-in DDL elements such as `DropTable()`, `CreateTable()` are supported (using SQLAlchemy core). """ async with Database(database_url) as database: ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_ddl_queries(database_url):
""" Test that the built-in DDL elements such as `DropTable()`, `CreateTable()` are supported (using SQLAlchemy core). """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): # DropTable() query = sqlalchemy.schema.DropT...
iterate_results[1]["completed"] == False assert iterate_results[2]["text"] == "example3" assert iterate_results[2]["completed"] == True @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_ddl_queries(database_url):
64
64
121
28
35
irulast/databases
tests/test_databases.py
Python
test_ddl_queries
test_ddl_queries
288
304
288
291
4f7903f0757f955debdc5709e5e0e9f74c1baf0a
bigcode/the-stack
train
bfc3901506cb6eddc55e83d1
train
function
@pytest.fixture(autouse=True, scope="function") def create_test_database(): # Create test databases with tables creation for url in DATABASE_URLS: database_url = DatabaseURL(url) if database_url.scheme in ["mysql", "mysql+aiomysql", "mysql+asyncmy"]: url = str(database_url.replace(dr...
@pytest.fixture(autouse=True, scope="function") def create_test_database(): # Create test databases with tables creation
for url in DATABASE_URLS: database_url = DatabaseURL(url) if database_url.scheme in ["mysql", "mysql+aiomysql", "mysql+asyncmy"]: url = str(database_url.replace(driver="pymysql")) elif database_url.scheme in [ "postgresql+aiopg", "sqlite+aiosqlite", ...
EpochType), ) # Used to test Numeric prices = sqlalchemy.Table( "prices", metadata, sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), sqlalchemy.Column("price", sqlalchemy.Numeric(precision=30, scale=20)), ) @pytest.fixture(autouse=True, scope="function") def create_test_database(): # ...
78
78
263
25
53
irulast/databases
tests/test_databases.py
Python
create_test_database
create_test_database
100
131
100
102
af6cf9687b63280851672c07bbf9c4426372f168
bigcode/the-stack
train
2c2d70113f5f47add2039f31
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit_low_level(database_url): """ Ensure that an explicit `await transaction.commit()` is supported. """ async with Database(database_url) as database: async with database.transac...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit_low_level(database_url):
""" Ensure that an explicit `await transaction.commit()` is supported. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): transaction = await database.transaction() try: query = notes.insert().values(t...
Error() except RuntimeError: pass query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 0 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit_low_...
64
64
145
29
34
irulast/databases
tests/test_databases.py
Python
test_transaction_commit_low_level
test_transaction_commit_low_level
581
602
581
584
98cc058563a7cfc4794a9ca496c98c47d154aa07
bigcode/the-stack
train
62765d8d2ddda48dfb414958
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_iterate_outside_transaction_with_temp_table(database_url): """ Same as test_iterate_outside_transaction_with_values but uses a temporary table instead of a list of values. """ database_url = Databa...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_iterate_outside_transaction_with_temp_table(database_url):
""" Same as test_iterate_outside_transaction_with_values but uses a temporary table instead of a list of values. """ database_url = DatabaseURL(database_url) if database_url.dialect == "sqlite": pytest.skip("SQLite interface does not work with temporary tables.") async with Databas...
_results = [] async for result in database.iterate(query=query): iterate_results.append(result) assert len(iterate_results) == 5 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_iterate_outside_transaction_with_temp_table(database_url):
64
64
202
33
30
irulast/databases
tests/test_databases.py
Python
test_iterate_outside_transaction_with_temp_table
test_iterate_outside_transaction_with_temp_table
1,077
1,103
1,077
1,080
7ab4b832d6ea96035ff7d2cf095413dde39e62c2
bigcode/the-stack
train
b6e2bffc43b9dc78eb2c23a0
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @async_adapter async def test_concurrent_access_on_single_connection(database_url): database_url = DatabaseURL(database_url) if database_url.dialect != "postgresql": pytest.skip("Test requires `pg_sleep()`") async with Database(database_url, f...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @async_adapter async def test_concurrent_access_on_single_connection(database_url):
database_url = DatabaseURL(database_url) if database_url.dialect != "postgresql": pytest.skip("Test requires `pg_sleep()`") async with Database(database_url, force_rollback=True) as database: async def db_lookup(): await database.fetch_one("SELECT pg_sleep(1)") await a...
instances expose a `.url` attribute. """ async with Database(database_url) as database: assert isinstance(database.url, DatabaseURL) assert database.url == database_url @pytest.mark.parametrize("database_url", DATABASE_URLS) @async_adapter async def test_concurrent_access_on_single_connection(d...
64
64
103
27
36
irulast/databases
tests/test_databases.py
Python
test_concurrent_access_on_single_connection
test_concurrent_access_on_single_connection
1,010
1,022
1,010
1,012
89631d42e3954a398126eee986c6473873d76a00
bigcode/the-stack
train
7d85d984ab0cb068051d676e
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit(database_url): """ Ensure that transaction commit is supported. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_commit(database_url):
""" Ensure that transaction commit is supported. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): async with database.transaction(): query = notes.insert().values(text="example1", completed=True) ...
database: # Ensure INSERT operations have been rolled back. query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 0 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_transaction_c...
64
64
111
27
36
irulast/databases
tests/test_databases.py
Python
test_transaction_commit
test_transaction_commit
495
510
495
498
d851a6631f55d8fcbc8b659281fd6ba6b1c14d4f
bigcode/the-stack
train
7e4bd54a9710a439340b8da0
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_postcompile_queries(database_url): """ Since SQLAlchemy 1.4, IN operators needs to do render_postcompile """ async with Database(database_url) as database: query = notes.insert() values ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_postcompile_queries(database_url):
""" Since SQLAlchemy 1.4, IN operators needs to do render_postcompile """ async with Database(database_url) as database: query = notes.insert() values = {"text": "example1", "completed": True} await database.execute(query, values) query = notes.select().where(notes.c.id....
# avoid checking `id` at index 0 since it may change depending on the launched tests assert list(result.values())[1:] == ["example1", True] @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_postcompile_queries(database_url):
64
64
126
28
36
irulast/databases
tests/test_databases.py
Python
test_postcompile_queries
test_postcompile_queries
1,194
1,209
1,194
1,197
0c486073f305151e5d843d88a57421b7cbd2e0ae
bigcode/the-stack
train
25eaea8cbc22933df6a3285c
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @pytest.mark.parametrize("select_query", [notes.select(), "SELECT * FROM notes"]) @mysql_versions @async_adapter async def test_column_names(database_url, select_query): """ Test that column names are exposed correctly through `._mapping.keys()` on each ro...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @pytest.mark.parametrize("select_query", [notes.select(), "SELECT * FROM notes"]) @mysql_versions @async_adapter async def test_column_names(database_url, select_query):
""" Test that column names are exposed correctly through `._mapping.keys()` on each row. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): # insert values query = notes.insert() values = {"text": "example1...
iterate_results.append(result) assert len(iterate_results) == 5 @pytest.mark.parametrize("database_url", DATABASE_URLS) @pytest.mark.parametrize("select_query", [notes.select(), "SELECT * FROM notes"]) @mysql_versions @async_adapter async def test_column_names(database_url, select_query):
64
64
193
47
16
irulast/databases
tests/test_databases.py
Python
test_column_names
test_column_names
1,106
1,126
1,106
1,110
d06afe99a3934457b69069537725f7295f693559
bigcode/the-stack
train
b61c4030964fb468d4597440
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_commit_on_root_transaction(database_url): """ Because our tests are generally wrapped in rollback-islation, they don't have coverage for commiting the root transaction. Deal with this here, and delete ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_commit_on_root_transaction(database_url):
""" Because our tests are generally wrapped in rollback-islation, they don't have coverage for commiting the root transaction. Deal with this here, and delete the records rather than rolling back. """ async with Database(database_url) as database: try: async with database.t...
() results = await database.fetch_all(query=query) assert len(results) == 1 finally: query = notes.delete() await database.execute(query) @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_commit_on_root_transacti...
64
64
153
29
35
irulast/databases
tests/test_databases.py
Python
test_commit_on_root_transaction
test_commit_on_root_transaction
786
808
786
789
877ec2d2c775d38bf1432bff69ecc39e166f7c91
bigcode/the-stack
train
1d9b483bb9df3ac86f243945
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_rollback_isolation_with_contextmanager(database_url): """ Ensure that `database.force_rollback()` provides strict isolation. """ database = Database(database_url) with database.force_rollback(): ...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_rollback_isolation_with_contextmanager(database_url):
""" Ensure that `database.force_rollback()` provides strict isolation. """ database = Database(database_url) with database.force_rollback(): async with database: # Perform some INSERT operations on the database. query = notes.insert().values(text="example1", complet...
INSERT operations have been rolled back. query = notes.select() results = await database.fetch_all(query=query) assert len(results) == 0 @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_rollback_isolation_with_contextmanager(database_url):
64
64
139
32
31
irulast/databases
tests/test_databases.py
Python
test_rollback_isolation_with_contextmanager
test_rollback_isolation_with_contextmanager
472
492
472
475
bc4f7a1274773451f8d7b691bc5321b0dfd6db44
bigcode/the-stack
train
d3db5b4885713376ad5ea9b6
train
function
def mysql_versions(wrapped_func): """ Decorator used to handle multiple versions of Python for mysql drivers """ @functools.wraps(wrapped_func) def check(*args, **kwargs): url = DatabaseURL(kwargs["database_url"]) if url.scheme in ["mysql", "mysql+aiomysql"] and sys.version_info >= ...
def mysql_versions(wrapped_func):
""" Decorator used to handle multiple versions of Python for mysql drivers """ @functools.wraps(wrapped_func) def check(*args, **kwargs): url = DatabaseURL(kwargs["database_url"]) if url.scheme in ["mysql", "mysql+aiomysql"] and sys.version_info >= (3, 10): pytest.skip("...
import pytest import sqlalchemy from databases import Database, DatabaseURL assert "TEST_DATABASE_URLS" in os.environ, "TEST_DATABASE_URLS is not set." DATABASE_URLS = [url.strip() for url in os.environ["TEST_DATABASE_URLS"].split(",")] def mysql_versions(wrapped_func):
63
64
148
7
56
irulast/databases
tests/test_databases.py
Python
mysql_versions
mysql_versions
21
35
21
21
1c8808fbd9a89ae803927bb29a8b09995c411ff3
bigcode/the-stack
train
e06d8549d05a543afd2c8b12
train
function
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_json_field(database_url): """ Test JSON columns, to ensure correct cross-database support. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True...
@pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_json_field(database_url):
""" Test JSON columns, to ensure correct cross-database support. """ async with Database(database_url) as database: async with database.transaction(force_rollback=True): # execute() data = {"text": "hello", "boolean": True, "int": 1} values = {"data": data} ...
--> a roud-off error is expected assert results[0]["price"] == pytest.approx(price) else: assert results[0]["price"] == price @pytest.mark.parametrize("database_url", DATABASE_URLS) @mysql_versions @async_adapter async def test_json_field(database_url):
64
64
166
27
36
irulast/databases
tests/test_databases.py
Python
test_json_field
test_json_field
714
734
714
717
0ba36e2e818442a141051502ad72cbfa6320f1dd
bigcode/the-stack
train