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
294e4bc538430ec5ee72b634
train
class
class MyOtherNode(SharedNodeFields, ObjectType): extra_field = String() class Meta: interfaces = (Node,) def resolve_extra_field(self, *_): return "extra field info." @staticmethod def get_node(info, id): return MyOtherNode(shared=str(id))
class MyOtherNode(SharedNodeFields, ObjectType):
extra_field = String() class Meta: interfaces = (Node,) def resolve_extra_field(self, *_): return "extra field info." @staticmethod def get_node(info, id): return MyOtherNode(shared=str(id))
omething_else(*_): return "----" class MyNode(ObjectType): class Meta: interfaces = (Node,) name = String() @staticmethod def get_node(info, id): return MyNode(name=str(id)) class MyOtherNode(SharedNodeFields, ObjectType):
64
64
66
12
52
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
MyOtherNode
MyOtherNode
30
41
30
30
bd1cb043746a977508cba12a8094225190dab300
bigcode/the-stack
train
eb16e97342115502aa45854c
train
function
def test_node_field_only_type(): executed = schema.execute( '{ onlyNode(id:"%s") { __typename, name } } ' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"onlyNode": {"__typename": "MyNode", "name": "1"}}
def test_node_field_only_type():
executed = schema.execute( '{ onlyNode(id:"%s") { __typename, name } } ' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"onlyNode": {"__typename": "MyNode", "name": "1"}}
"description": "my_custom_description", "deprecation_reason": "my_custom_deprecation_reason", } node_field = Node.Field(**field_args) for field_arg, value in field_args.items(): assert getattr(node_field, field_arg) == value def test_node_field_only_type():
64
64
74
7
56
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
test_node_field_only_type
test_node_field_only_type
136
141
136
136
49e6a6ccb705d4a0e6e4d1a2a84f3ee06089d32e
bigcode/the-stack
train
f76ff567e29c83c99da524fb
train
function
def test_node_requesting_non_node(): executed = schema.execute( '{ node(id:"%s") { __typename } } ' % Node.to_global_id("RootQuery", 1) ) assert executed.errors assert re.match( r"ObjectType .* does not implement the .* interface.", executed.errors[0].message, ) assert ex...
def test_node_requesting_non_node():
executed = schema.execute( '{ node(id:"%s") { __typename } } ' % Node.to_global_id("RootQuery", 1) ) assert executed.errors assert re.match( r"ObjectType .* does not implement the .* interface.", executed.errors[0].message, ) assert executed.data == {"node": None}
("MyOtherNode", 1) ) assert not executed.errors assert executed.data == { "node": { "shared": "1", "extraField": "extra field info.", "somethingElse": "----", } } def test_node_requesting_non_node():
64
64
85
8
56
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
test_node_requesting_non_node
test_node_requesting_non_node
83
92
83
83
26b2e7487f02aaccc06ca99db2570dd1fd83f1d0
bigcode/the-stack
train
a2aa02c633a98772c05a4c0b
train
function
def test_subclassed_node_query(): executed = schema.execute( '{ node(id:"%s") { ... on MyOtherNode { shared, extraField, somethingElse } } }' % to_global_id("MyOtherNode", 1) ) assert not executed.errors assert executed.data == { "node": { "shared": "1", "...
def test_subclassed_node_query():
executed = schema.execute( '{ node(id:"%s") { ... on MyOtherNode { shared, extraField, somethingElse } } }' % to_global_id("MyOtherNode", 1) ) assert not executed.errors assert executed.data == { "node": { "shared": "1", "extraField": "extra field info.", ...
.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"node": {"name": "1"}} def test_subclassed_node_query():
64
64
101
8
55
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
test_subclassed_node_query
test_subclassed_node_query
68
80
68
68
1ce450c0dff76b6efe4c517f0cc605270f435b8f
bigcode/the-stack
train
5f41d2205409b20873c6265a
train
class
class SharedNodeFields: shared = String() something_else = String() def resolve_something_else(*_): return "----"
class SharedNodeFields:
shared = String() something_else = String() def resolve_something_else(*_): return "----"
import re from graphql_relay import to_global_id from graphql.pyutils import dedent from ...types import ObjectType, Schema, String from ..node import Node, is_node class SharedNodeFields:
45
64
30
5
39
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
SharedNodeFields
SharedNodeFields
10
16
10
11
a553586cfa4402c96e38ba83406f1e9b90a9ae9d
bigcode/the-stack
train
0e568dcb49e52d48acbc4e64
train
function
def test_node_query_incorrect_id(): executed = schema.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % "something:2" ) assert executed.errors assert re.match(r"Unable to parse global ID .*", executed.errors[0].message) assert executed.data == {"node": None}
def test_node_query_incorrect_id():
executed = schema.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % "something:2" ) assert executed.errors assert re.match(r"Unable to parse global ID .*", executed.errors[0].message) assert executed.data == {"node": None}
{ __typename } } ' % Node.to_global_id("UnknownType", 1) ) assert executed.errors assert re.match(r"Relay Node .* not found in schema", executed.errors[0].message) assert executed.data == {"node": None} def test_node_query_incorrect_id():
64
64
76
8
56
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
test_node_query_incorrect_id
test_node_query_incorrect_id
104
110
104
104
fe237519bac9d5c5061d60cabccc5d447cf61f7b
bigcode/the-stack
train
aeb735304e663d30023601f9
train
function
def test_node_requesting_unknown_type(): executed = schema.execute( '{ node(id:"%s") { __typename } } ' % Node.to_global_id("UnknownType", 1) ) assert executed.errors assert re.match(r"Relay Node .* not found in schema", executed.errors[0].message) assert executed.data == {"node": None}
def test_node_requesting_unknown_type():
executed = schema.execute( '{ node(id:"%s") { __typename } } ' % Node.to_global_id("UnknownType", 1) ) assert executed.errors assert re.match(r"Relay Node .* not found in schema", executed.errors[0].message) assert executed.data == {"node": None}
Node.to_global_id("RootQuery", 1) ) assert executed.errors assert re.match( r"ObjectType .* does not implement the .* interface.", executed.errors[0].message, ) assert executed.data == {"node": None} def test_node_requesting_unknown_type():
64
64
78
8
56
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
test_node_requesting_unknown_type
test_node_requesting_unknown_type
95
101
95
95
01dfa4661fe30fa6809d41f1c55800653487c8e1
bigcode/the-stack
train
c7433889d4f44b043a564e5f
train
function
def test_node_query(): executed = schema.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"node": {"name": "1"}}
def test_node_query():
executed = schema.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"node": {"name": "1"}}
only_node_lazy = Node.Field(lambda: MyNode) schema = Schema(query=RootQuery, types=[MyNode, MyOtherNode]) def test_node_good(): assert "id" in MyNode._meta.fields assert is_node(MyNode) assert not is_node(object) def test_node_query():
64
64
65
5
59
ko-lem/graphene
graphene/relay/tests/test_node.py
Python
test_node_query
test_node_query
60
65
60
60
e1c38e3baf7c2dee6082e3abef38e00ca401a6bb
bigcode/the-stack
train
e6463e7ab0de0be06d522c08
train
function
def prepare_files_map(path): log = [] # uwzgledniam zarowno htm jak i html - uwzgledniam podfoldery lista_plikow = [{name: root} for root, dirs, files in os.walk(path) for name in files if name.endswith((".html", ".htm"))] # generowanie id w oparciu o nazwe pliku # wszystkie znaki nie alfanumeryc...
def prepare_files_map(path):
log = [] # uwzgledniam zarowno htm jak i html - uwzgledniam podfoldery lista_plikow = [{name: root} for root, dirs, files in os.walk(path) for name in files if name.endswith((".html", ".htm"))] # generowanie id w oparciu o nazwe pliku # wszystkie znaki nie alfanumeryczne sa zamieniane na pauze (-)...
_rodzaj', 'h7_suma', 'h7_waluta', 'h7_osoba_prawna', 'h8_rodzaj', 'h8_suma', 'h8_waluta', 'h8_osoba_prawna', 'h9_rodzaj', 'h9_suma', 'h9_waluta', 'h9_osoba_prawna', 'h10_rodzaj', 'h10_suma', 'h10_walu...
132
132
440
6
125
mguomanila/johnCrawlerNewProject
extract_data.py
Python
prepare_files_map
prepare_files_map
150
176
150
151
f38d69ccb8312dd764bfdc0a2102dc01d7065551
bigcode/the-stack
train
de0ff48ed91e5e3af7c60d0f
train
function
def read_previous_results(path): log = [] if os.path.isfile(path): results = pd.read_csv(path, low_memory=False, encoding='utf-8', sep=';') else: log += logger('', '', '', 'nie odnaleziono pliku z wynikami poprzednich ekstrakcji - zostanie utworzony nowy plik') results = pd.DataFram...
def read_previous_results(path):
log = [] if os.path.isfile(path): results = pd.read_csv(path, low_memory=False, encoding='utf-8', sep=';') else: log += logger('', '', '', 'nie odnaleziono pliku z wynikami poprzednich ekstrakcji - zostanie utworzony nowy plik') results = pd.DataFrame({'id': [], ...
.makedirs('/'.join(sciezka_do_pliku_wyjsciowego.split('/')[:-1])) if not os.path.exists(sciezka_do_katalogu_z_logami): os.makedirs(sciezka_do_katalogu_z_logami) typy_nieruchomosci_in = [u'STANOWIĄCY ODRĘBNĄ NIERUCHOMOŚĆ', u'PRAWO DO LOKALU', u'NIERUCHOMOŚĆ GRUNTOWA', u'GRUNT ODDANY W UŻYT...
255
256
1,527
6
249
mguomanila/johnCrawlerNewProject
extract_data.py
Python
read_previous_results
read_previous_results
40
147
40
40
3cdb9daba0ed97006da6430a2cc898bb4bc066b5
bigcode/the-stack
train
1aa5490b65405a045ea25c23
train
function
def extract_from_io(html): czy_lokal = find_tags_with_text(u'Lokal', html) if czy_lokal: miejscowosc = find_tags_with_text(u'Położenie', html) if miejscowosc: miejscowosc = miejscowosc[3].text.split(', ') if len(miejscowosc) > 3 else [None] miejscowosc = miejscowosc[0]...
def extract_from_io(html):
czy_lokal = find_tags_with_text(u'Lokal', html) if czy_lokal: miejscowosc = find_tags_with_text(u'Położenie', html) if miejscowosc: miejscowosc = miejscowosc[3].text.split(', ') if len(miejscowosc) > 3 else [None] miejscowosc = miejscowosc[0] if len(miejscowosc) <= 3 el...
]} html_iv_summary = {'numery_ksiag': [x['numer_ksiegi_wieczystej'] for x in html_iv if x['numer_ksiegi_wieczystej']], 'typy_nieruchomosci': [x['typ_nieruchomosci'] for x in html_iv if x['typ_nieruchomosci']]} return html_io, html_ii, html_iv, html_io_summary, html_ii_summary, html_iv_su...
196
196
654
6
189
mguomanila/johnCrawlerNewProject
extract_data.py
Python
extract_from_io
extract_from_io
250
293
250
251
423d2a25c3de400d83c3aa6d29e0b515cdb140bc
bigcode/the-stack
train
fd1396f597944c0a91c6fb9f
train
function
def analyse_pliki_powiazane(pliki_powiazane): html_io = [] html_ii = [] html_iv = [] log = [] for t in pliki_powiazane: with open(t.values()[0] + '/' + t.keys()[0], 'r', encoding='utf-8') as f: html = BeautifulSoup(f.read(), 'html.parser') try: typ_pliku = ...
def analyse_pliki_powiazane(pliki_powiazane):
html_io = [] html_ii = [] html_iv = [] log = [] for t in pliki_powiazane: with open(t.values()[0] + '/' + t.keys()[0], 'r', encoding='utf-8') as f: html = BeautifulSoup(f.read(), 'html.parser') try: typ_pliku = html.select('.csTTytul') typ_pliku ...
', '-', re.sub('[^a-zA-Z0-9]', '-', x.keys()[0].replace('NR ', '')))).split('-')[:3]).upper() slownik_nazw_plikow.update({x.keys()[0]: {'id': id, 'root': x.values()[0]}}) except: log += logger('', x.keys()[0], '', u'nie mozna wczytac pliku ({})'.format(x.values()[0]), 'ERROR') lista...
256
256
1,045
13
242
mguomanila/johnCrawlerNewProject
extract_data.py
Python
analyse_pliki_powiazane
analyse_pliki_powiazane
179
238
179
180
786c9dd3c73f8841772ebaf81547feb6ea802a5d
bigcode/the-stack
train
cdaed9fbf5caf4863ba1513d
train
function
def extract_podmiot(podmiot): if podmiot: nazwa_podmiotu = podmiot[0] miejscowosc_podmiotu = podmiot[1] if len(podmiot) > 1 else None regon = podmiot[2] if len(podmiot) > 2 else None else: nazwa_podmiotu = None miejscowosc_podmiotu = None regon = None return ...
def extract_podmiot(podmiot):
if podmiot: nazwa_podmiotu = podmiot[0] miejscowosc_podmiotu = podmiot[1] if len(podmiot) > 1 else None regon = podmiot[2] if len(podmiot) > 2 else None else: nazwa_podmiotu = None miejscowosc_podmiotu = None regon = None return nazwa_podmiotu, miejscowosc_po...
ciec = None matka = None pesel = None data_urodzenia = None return imie1, imie2, nazwisko, ojciec, matka, pesel, data_urodzenia def extract_podmiot(podmiot):
64
64
124
9
54
mguomanila/johnCrawlerNewProject
extract_data.py
Python
extract_podmiot
extract_podmiot
327
337
327
327
1e2af2eed5dbd136fbb066d4bb2d5375424b542b
bigcode/the-stack
train
04dcbc020f1771fa3e36a8a1
train
function
def extract_from_ii(html): osoby_fizyczne = find_tags_with_text(u'Osoba fizyczna', html) if osoby_fizyczne: if not isinstance(osoby_fizyczne[0], list): osoby_fizyczne = [osoby_fizyczne] osoby_fizyczne = [extract_osoba_fizyczna(x[1].text.split(', ')) for x in osoby_fizyczne] ...
def extract_from_ii(html):
osoby_fizyczne = find_tags_with_text(u'Osoba fizyczna', html) if osoby_fizyczne: if not isinstance(osoby_fizyczne[0], list): osoby_fizyczne = [osoby_fizyczne] osoby_fizyczne = [extract_osoba_fizyczna(x[1].text.split(', ')) for x in osoby_fizyczne] rodzaj_wspolnosci = find_ta...
nazwisko = None ojciec = None matka = None pesel = None data_urodzenia = None return imie1, imie2, nazwisko, ojciec, matka, pesel, data_urodzenia def extract_podmiot(podmiot): if podmiot: nazwa_podmiotu = podmiot[0] miejscowosc_podmiotu = podmiot[1] if...
195
195
650
7
187
mguomanila/johnCrawlerNewProject
extract_data.py
Python
extract_from_ii
extract_from_ii
340
385
340
340
209398afd5278ab6cbaa36336d8acca820967036
bigcode/the-stack
train
05afc59c983bb4f76f74b865
train
function
def extract_form_iv(html): rodzaj_hipoteki = find_tags_with_text(u'Rodzaj hipoteki', html) if rodzaj_hipoteki: rodzaj_hipoteki = [rodzaj_hipoteki] if not isinstance(rodzaj_hipoteki[0], list) else rodzaj_hipoteki rodzaj_hipoteki = [x[1].text for x in rodzaj_hipoteki] # if len(x) > 1] suma = ...
def extract_form_iv(html):
rodzaj_hipoteki = find_tags_with_text(u'Rodzaj hipoteki', html) if rodzaj_hipoteki: rodzaj_hipoteki = [rodzaj_hipoteki] if not isinstance(rodzaj_hipoteki[0], list) else rodzaj_hipoteki rodzaj_hipoteki = [x[1].text for x in rodzaj_hipoteki] # if len(x) > 1] suma = find_tags_with_text(u'Suma'...
odmioty_3[0], list): podmioty_3 = [podmioty_3] podmioty_3 = [extract_podmiot(x[1].text.split(', ')) for x in podmioty_3] else: podmioty_3 = [] podmioty = podmioty_1 + podmioty_2 + podmioty_3 return osoby_fizyczne, rodzaj_wspolnosci, rozdzielnosc_majatkowa, podmioty def extract_...
124
124
414
6
117
mguomanila/johnCrawlerNewProject
extract_data.py
Python
extract_form_iv
extract_form_iv
388
414
388
388
1d8addb9f320cd70fe2a00d1ea0234f42c0d2c81
bigcode/the-stack
train
3d2ffe51d8a7964fb22fdd3a
train
function
def find_tags_with_text(text, html): try: el = [x.find_all('td') for x in html.find_all(lambda tag: tag.name == 'tr' and text in tag.text)] el = el[0] if len(el) == 1 else None if len(el) == 0 else el except: el = None return el
def find_tags_with_text(text, html):
try: el = [x.find_all('td') for x in html.find_all(lambda tag: tag.name == 'tr' and text in tag.text)] el = el[0] if len(el) == 1 else None if len(el) == 0 else el except: el = None return el
ci': [x['typ_nieruchomosci'] for x in html_iv if x['typ_nieruchomosci']]} return html_io, html_ii, html_iv, html_io_summary, html_ii_summary, html_iv_summary, log def find_tags_with_text(text, html):
64
64
81
9
54
mguomanila/johnCrawlerNewProject
extract_data.py
Python
find_tags_with_text
find_tags_with_text
241
247
241
241
72fe94fa4736550fa734962b493b71677a53518b
bigcode/the-stack
train
ef3113027f60d598fbf63471
train
function
def extract_osoba_fizyczna(osoba_fizyczna): if osoba_fizyczna: imie_nazwisko = osoba_fizyczna[0].split(' ') imie1 = imie_nazwisko[0] imie2 = imie_nazwisko[1] if len(imie_nazwisko) > 1 else None nazwisko = imie_nazwisko[-1] if imie1 == imie2 or imie2 == nazwisko: i...
def extract_osoba_fizyczna(osoba_fizyczna):
if osoba_fizyczna: imie_nazwisko = osoba_fizyczna[0].split(' ') imie1 = imie_nazwisko[0] imie2 = imie_nazwisko[1] if len(imie_nazwisko) > 1 else None nazwisko = imie_nazwisko[-1] if imie1 == imie2 or imie2 == nazwisko: imie2 = None if len(osoba_fizyczna) >...
\ numer_lokalu, przeznaczenie_lokalu, liczba_pokoi, \ kondygnacja, pole_powierzchni_uzytkowej = None, None, None, None, None, None, None, None, return miejscowosc, ulica, numer_budynku, numer_lokalu, przeznaczenie_lokalu, liczba_pokoi, kondygnacja, pole_powierzchni_uzytkowej def extract_osoba_fizy...
117
117
390
15
101
mguomanila/johnCrawlerNewProject
extract_data.py
Python
extract_osoba_fizyczna
extract_osoba_fizyczna
296
324
296
296
ce729b62be8b63e9a4d01abf39796e72a15862c1
bigcode/the-stack
train
35bedefefdc7284ec8499599
train
function
def logger(id, fn, numer, text, type='INFO'): print(u'{} : {} : {} : {} : {}'.format(type, id, fn, numer, text)) return [{'type': type, 'id': id, 'fn': fn, 'numer': numer, 'text': text}]
def logger(id, fn, numer, text, type='INFO'):
print(u'{} : {} : {} : {} : {}'.format(type, id, fn, numer, text)) return [{'type': type, 'id': id, 'fn': fn, 'numer': numer, 'text': text}]
_out = [u'NIERUCHOMOŚĆ GRUNTOWA', u'GRUNT ODDANY W UŻYTKOWANIE WIECZYSTE'] logs = [] ### FUNKCJE POMOCNICZE def logger(id, fn, numer, text, type='INFO'):
64
64
65
14
49
mguomanila/johnCrawlerNewProject
extract_data.py
Python
logger
logger
35
37
35
35
911e99bc46047ad383c7662120030a755d17b503
bigcode/the-stack
train
c8547553fe7d3355a1a6025a
train
class
class CollabFilterTest(sparktk_test.SparkTKTestCase): def setUp(self): """Build test frame""" super(CollabFilterTest, self).setUp() ALS_dataset = self.get_file("collab_filtering.csv") schema = [("user", str), ("product", str), ("rating", float)] self.frame = self.context.f...
class CollabFilterTest(sparktk_test.SparkTKTestCase):
def setUp(self): """Build test frame""" super(CollabFilterTest, self).setUp() ALS_dataset = self.get_file("collab_filtering.csv") schema = [("user", str), ("product", str), ("rating", float)] self.frame = self.context.frame.import_csv(ALS_dataset, schema=schema) # ...
ation  # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #       http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
256
256
2,800
16
239
aayushidwivedi01/spark-tk-old
regression-tests/sparktkregtests/testcases/models/collaborative_filtering_test.py
Python
CollabFilterTest
CollabFilterTest
24
312
24
25
9115450007d8c5b8969a07d76dd3e334f6deab83
bigcode/the-stack
train
859e1a72680cbfcaa546cad8
train
class
class CreateSuperUserCommand(SQLCommandMixin, Command): name = 'createsuperuser' help = 'Create a super user account.' def handle(self, options, global_options, *args): from uliweb.manage import make_simple_application from uliweb import orm from getpass import getpass ...
class CreateSuperUserCommand(SQLCommandMixin, Command):
name = 'createsuperuser' help = 'Create a super user account.' def handle(self, options, global_options, *args): from uliweb.manage import make_simple_application from uliweb import orm from getpass import getpass self.get_application(global_options) us...
from __future__ import print_function from uliweb.core.commands import Command from uliweb.contrib.orm.commands import SQLCommandMixin from ...utils._compat import input class CreateSuperUserCommand(SQLCommandMixin, Command):
46
75
251
11
34
TommyLemon/uliweb3
uliweb/contrib/auth/commands.py
Python
CreateSuperUserCommand
CreateSuperUserCommand
6
41
6
6
4c6f790b7bda429113128002565ee9791a94ad59
bigcode/the-stack
train
53ae8934606e53b48a27d881
train
class
class EncryptPasswordCommand(Command): name = 'encryptpassword' help = 'Encrypt password.' def handle(self, options, global_options, *args): from uliweb import functions import getpass self.get_application(global_options) password = getpass.getpass('Input your password(Bla...
class EncryptPasswordCommand(Command):
name = 'encryptpassword' help = 'Encrypt password.' def handle(self, options, global_options, *args): from uliweb import functions import getpass self.get_application(global_options) password = getpass.getpass('Input your password(Blank will quit):') if not passwor...
matched, can't create super user!") return orm.set_dispatch_send(False) User = orm.get_model('user', options.engine) user = User(username=username, email=email) user.set_password(password) user.is_superuser = True user.save() class EncryptPa...
64
64
124
6
58
TommyLemon/uliweb3
uliweb/contrib/auth/commands.py
Python
EncryptPasswordCommand
EncryptPasswordCommand
43
60
43
43
9cc15a2446d9b09c42b5c7162705a5b8ba0b9160
bigcode/the-stack
train
f599580a991df2dadabb6bb8
train
function
def get_udp_data(ri, npkts, streamid, chans, nfft, stream_reg='streamid', addr=('192.168.1.1', 12345)): pkts = get_udp_packets(ri, npkts, streamid, stream_reg=stream_reg, addr=addr) darray, seqnos = decode_packets(pkts, streamid, chans, nfft) return darray, seqnos
def get_udp_data(ri, npkts, streamid, chans, nfft, stream_reg='streamid', addr=('192.168.1.1', 12345)):
pkts = get_udp_packets(ri, npkts, streamid, stream_reg=stream_reg, addr=addr) darray, seqnos = decode_packets(pkts, streamid, chans, nfft) return darray, seqnos
Did not receive UDP data.") break ri.r.write_int(stream_reg, 0) return pkts def get_udp_data(ri, npkts, streamid, chans, nfft, stream_reg='streamid', addr=('192.168.1.1', 12345)):
64
64
94
39
24
danielflanigan/kid_readout
kid_readout/roach/udp_catcher.py
Python
get_udp_data
get_udp_data
41
44
41
41
7b684053edc9f0a93ce69ed21b7ec35f89052a58
bigcode/the-stack
train
5d79362b7f364890be5e639e
train
function
def get_udp_packets(ri, npkts, streamid, stream_reg='streamid', addr=('192.168.1.1', 12345)): ri.r.write_int(stream_reg, 0) with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: s.bind(addr) s.settimeout(0) nstale = 0 try: while s.recv(2000): ...
def get_udp_packets(ri, npkts, streamid, stream_reg='streamid', addr=('192.168.1.1', 12345)):
ri.r.write_int(stream_reg, 0) with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: s.bind(addr) s.settimeout(0) nstale = 0 try: while s.recv(2000): nstale += 1 if nstale: logger.info("Flushed {} packets.".for...
import cPickle import numpy as np # TODO: verify that the log levels are correct here. logger = logging.getLogger(__name__) def get_udp_packets(ri, npkts, streamid, stream_reg='streamid', addr=('192.168.1.1', 12345)):
64
64
215
34
30
danielflanigan/kid_readout
kid_readout/roach/udp_catcher.py
Python
get_udp_packets
get_udp_packets
14
38
14
14
9b9b2af0988a7f6a45cc7c8d1ea609028cba8cda
bigcode/the-stack
train
b4f2b1278fc5106f75e9694c
train
function
def decode_packets(plist, streamid, chans, nfft, pkts_per_chunk=16, capture_failures=False): nchan = chans.shape[0] mcnt_inc = nfft * 2 ** 12 / nchan next_seqno = None mcnt_top = 0 dset = [] mcntoff = None last_mcnt_ovf = None seqnos = [] nextseqnos = [] chan0 = None for pnum...
def decode_packets(plist, streamid, chans, nfft, pkts_per_chunk=16, capture_failures=False):
nchan = chans.shape[0] mcnt_inc = nfft * 2 ** 12 / nchan next_seqno = None mcnt_top = 0 dset = [] mcntoff = None last_mcnt_ovf = None seqnos = [] nextseqnos = [] chan0 = None for pnum, pkt in enumerate(plist): if len(pkt) != pkt_size: logger.warning("Packe...
pkt = s.recv(2000) if pkt: pkts.append(pkt) else: logger.warning("Did not receive UDP data.") break ri.r.write_int(stream_reg, 0) return pkts def get_udp_data(ri, npkts, streamid, chans, nfft, stream_reg='streamid', addr=('192.168.1....
256
256
966
26
229
danielflanigan/kid_readout
kid_readout/roach/udp_catcher.py
Python
decode_packets
decode_packets
59
137
59
59
c68b099ba8d64672c2f1e0b5a9570fe2ffcd156f
bigcode/the-stack
train
1de849d61a1a91924f98b74f
train
class
class OptimizerParamsHandler(BaseOptimizerParamsHandler): """Helper handler to log optimizer parameters Examples: .. code-block:: python from ignite.contrib.handlers.wandb_logger import * # Create a logger. All parameters are optional. See documentation # on wandb...
class OptimizerParamsHandler(BaseOptimizerParamsHandler):
"""Helper handler to log optimizer parameters Examples: .. code-block:: python from ignite.contrib.handlers.wandb_logger import * # Create a logger. All parameters are optional. See documentation # on wandb.init for details. wandb_logger = WandBLogger...
(logger, WandBLogger): raise RuntimeError("Handler '{}' works only with WandBLogger.".format(self.__class__.__name__)) global_step = self.global_step_transform(engine, event_name) if not isinstance(global_step, int): raise TypeError( "global_step must be int, got...
153
153
511
10
143
ibotdotout/ignite
ignite/contrib/handlers/wandb_logger.py
Python
OptimizerParamsHandler
OptimizerParamsHandler
278
336
278
278
b2cc8b0c427b57f60639eb3d46f0f74b115a2214
bigcode/the-stack
train
93ee0f12c5a2f0096ad400df
train
class
class OutputHandler(BaseOutputHandler): """Helper handler to log engine's output and/or metrics Examples: .. code-block:: python from ignite.contrib.handlers.wandb_logger import * # Create a logger. All parameters are optional. See documentation # on wandb.init fo...
class OutputHandler(BaseOutputHandler):
"""Helper handler to log engine's output and/or metrics Examples: .. code-block:: python from ignite.contrib.handlers.wandb_logger import * # Create a logger. All parameters are optional. See documentation # on wandb.init for details. wandb_logger = W...
Checkpoint( wandb_logger.run.dir, n_saved=2, filename_prefix='best', require_empty=False, score_function=score_function, score_name="validation_accuracy", global_step_transform=global_step_from_engine(trainer) ) evaluator.add_event_...
256
256
1,120
7
249
ibotdotout/ignite
ignite/contrib/handlers/wandb_logger.py
Python
OutputHandler
OutputHandler
143
275
143
143
30ea976cd863f7252e27f02641aded39dae7ff70
bigcode/the-stack
train
b5fbb0414d7c331c92d7c4bc
train
class
class WandBLogger(BaseLogger): """`Weights & Biases <https://app.wandb.ai/>`_ handler to log metrics, model/optimizer parameters, gradients during training and validation. It can also be used to log model checkpoints to the Weights & Biases cloud. .. code-block:: bash pip install wandb This c...
class WandBLogger(BaseLogger):
"""`Weights & Biases <https://app.wandb.ai/>`_ handler to log metrics, model/optimizer parameters, gradients during training and validation. It can also be used to log model checkpoints to the Weights & Biases cloud. .. code-block:: bash pip install wandb This class is also a wrapper for the ...
from enum import Enum from typing import Any, Callable, List, Optional, Union from torch.optim import Optimizer from ignite.contrib.handlers.base_logger import BaseLogger, BaseOptimizerParamsHandler, BaseOutputHandler from ignite.engine import CallableEventWithFilter, Engine from ignite.handlers import global_step_fr...
96
256
1,050
7
89
ibotdotout/ignite
ignite/contrib/handlers/wandb_logger.py
Python
WandBLogger
WandBLogger
13
140
13
13
e9365059e4bb5c6b4af9b4b6f745abf12b50e9d4
bigcode/the-stack
train
df16c5eb85eac562ef27821e
train
class
class StronaConfig(AppConfig): name = 'strona'
class StronaConfig(AppConfig):
name = 'strona'
from django.apps import AppConfig class StronaConfig(AppConfig):
14
64
14
7
6
dawidhubicki97/BookMaker
src/strona/apps.py
Python
StronaConfig
StronaConfig
4
5
4
4
0875ecb55fa133a774eb0b05ebc70495e87bcdf4
bigcode/the-stack
train
4048b9e9c25ab09f8617336c
train
function
def report(context): source = zope.component.getUtility( zeit.vgwort.interfaces.IReportableContentSource) vgwort = zope.component.getUtility( zeit.vgwort.interfaces.IMessageService) log.info('reporting %s' % context.uniqueId) try: vgwort.new_document(context) source.mark_...
def report(context):
source = zope.component.getUtility( zeit.vgwort.interfaces.IReportableContentSource) vgwort = zope.component.getUtility( zeit.vgwort.interfaces.IMessageService) log.info('reporting %s' % context.uniqueId) try: vgwort.new_document(context) source.mark_done(context) exc...
, exc_info=True) # XXX vgwort returns 401 after some requests for unknown reasons. if i % 6 == 0 and 'client' in vgwort.__dict__: del vgwort.client finally: lock.close() log.info('Report end') def report(context):
64
64
176
4
60
fschulze/vivi
core/src/zeit/vgwort/report.py
Python
report
report
137
155
137
137
1d797c1cce23ef62e6579d3fad2bf1c65908a8b5
bigcode/the-stack
train
bc3c98f75fa69331c674138f
train
class
@zope.interface.implementer(zeit.vgwort.interfaces.IReportableContentSource) class ReportableContentSource(grok.GlobalUtility): def __iter__(self): age = self.config['days-before-report'] age = datetime.date.today() - datetime.timedelta(days=int(age)) age = age.isoformat() i = 0 ...
@zope.interface.implementer(zeit.vgwort.interfaces.IReportableContentSource) class ReportableContentSource(grok.GlobalUtility):
def __iter__(self): age = self.config['days-before-report'] age = datetime.date.today() - datetime.timedelta(days=int(age)) age = age.isoformat() i = 0 result = self._query(age, i) while len(result) < result.hits: i += 1 result.extend(self._qu...
from zeit.cms.content.interfaces import WRITEABLE_LIVE import ZODB.POSException import datetime import gocept.runner import grokcore.component as grok import logging import os.path import pytz import six import sys import tempfile import zc.lockfile import zeit.cms.content.dav import zeit.cms.interfaces import zeit.fin...
140
143
477
29
111
fschulze/vivi
core/src/zeit/vgwort/report.py
Python
ReportableContentSource
ReportableContentSource
25
78
25
27
0e62052d637b66b9c7e5f77987ccfc7aa52fd8cf
bigcode/the-stack
train
baf0ae085694cf742a3b6616
train
function
@zeit.cms.cli.runner(principal=gocept.runner.from_config( 'zeit.vgwort', 'token-principal')) def report_new_documents(): lock_file_name = os.path.join(tempfile.gettempdir(), 'vgwort-run-lock') try: lock = zc.lockfile.LockFile(lock_file_name) except zc.lockfile.LockError: sys.stderr.write...
@zeit.cms.cli.runner(principal=gocept.runner.from_config( 'zeit.vgwort', 'token-principal')) def report_new_documents():
lock_file_name = os.path.join(tempfile.gettempdir(), 'vgwort-run-lock') try: lock = zc.lockfile.LockFile(lock_file_name) except zc.lockfile.LockError: sys.stderr.write( "VGWort report alredy running? Could not lock {}\n".format( lock_file_name)) sys.exit(1...
Info(zeit.cms.content.dav.DAVPropertiesAdapter): grok.provides(zeit.vgwort.interfaces.IReportInfo) zeit.cms.content.dav.mapProperties( zeit.vgwort.interfaces.IReportInfo, 'http://namespaces.zeit.de/CMS/vgwort', ('reported_on', 'reported_error'), writeable=WRITEABLE_LIVE) @zeit....
111
111
370
31
80
fschulze/vivi
core/src/zeit/vgwort/report.py
Python
report_new_documents
report_new_documents
92
134
92
94
0d698e7c547d24d190953cd6fee91c3533da4795
bigcode/the-stack
train
1e1720728dcc350f3d4e6544
train
class
class ReportInfo(zeit.cms.content.dav.DAVPropertiesAdapter): grok.provides(zeit.vgwort.interfaces.IReportInfo) zeit.cms.content.dav.mapProperties( zeit.vgwort.interfaces.IReportInfo, 'http://namespaces.zeit.de/CMS/vgwort', ('reported_on', 'reported_error'), writeable=WRITEABLE_...
class ReportInfo(zeit.cms.content.dav.DAVPropertiesAdapter):
grok.provides(zeit.vgwort.interfaces.IReportInfo) zeit.cms.content.dav.mapProperties( zeit.vgwort.interfaces.IReportInfo, 'http://namespaces.zeit.de/CMS/vgwort', ('reported_on', 'reported_error'), writeable=WRITEABLE_LIVE)
(self, content): errors = zeit.retresco.update.index(content) if errors: raise errors[0] @property def config(self): return zope.app.appsetup.product.getProductConfiguration('zeit.vgwort') class ReportInfo(zeit.cms.content.dav.DAVPropertiesAdapter):
64
64
82
14
50
fschulze/vivi
core/src/zeit/vgwort/report.py
Python
ReportInfo
ReportInfo
81
89
81
82
09e5982e8819acc45c87b99141ba77a3afc1ae4e
bigcode/the-stack
train
ea9b21eada2e6906a9d2e175
train
class
class M2em: """ Main Class """ def __init__(self): # Python 3 is required! if sys.version_info[0] < 3: sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n") sys.exit(1) # Get args right at the start self.args = None if not self.args: ...
class M2em:
""" Main Class """ def __init__(self): # Python 3 is required! if sys.version_info[0] < 3: sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n") sys.exit(1) # Get args right at the start self.args = None if not self.args: ...
#!/usr/bin/env python """ Main Wrapper Module """ import os import sys import logging import time import argparse import datetime import validators from bin._version import __version__ # Start of the fun! import bin.Config as Config import bin.Helper as helper import bin.RssParser as mparser import bin.DownloaderHandle...
109
256
2,651
5
103
schemen/m2em
m2em.py
Python
M2em
M2em
20
440
20
20
ce71c6eedc263cc607ad235b6e7f0ae9a0cf30d6
bigcode/the-stack
train
d4208ea3c3bce8a496c1a822
train
class
class Test_RequireBodyInlineException: def test_1(self): input = "<<[ abc ]>><<[ end ]>>\n" \ "// [[[ <<[ def ]>><<[ end ]>> ]]]\n" \ " <<[ def ]>>\n" \ " // [[[ <<[ ghi ]>><<[ end ]>> ]]]\n" \ " // [[[ end ]]]\n" \ " <<...
class Test_RequireBodyInlineException:
def test_1(self): input = "<<[ abc ]>><<[ end ]>>\n" \ "// [[[ <<[ def ]>><<[ end ]>> ]]]\n" \ " <<[ def ]>>\n" \ " // [[[ <<[ ghi ]>><<[ end ]>> ]]]\n" \ " // [[[ end ]]]\n" \ " <<[ end ]>>\n" \ "// [[[ ...
end ]]]\n" \ " <<[ abc ]>> <<[d]>> <<[ end ]>>\n" \ "// [[[ end ]]]" msg = "Directly enclosed edit marker \"<<[ d ]>>\", consider reusing/removing it:\n" \ " <<[ abc ]>> <<[d]>> <<[ end ]>>\\n\n" \ " ^^^ line 6, column 15" ...
127
127
424
8
119
ldflo/autojinja
tests/test_exceptions.py
Python
Test_RequireBodyInlineException
Test_RequireBodyInlineException
776
804
776
776
be72174208bc52aeae465720c4593b5b96f593e3
bigcode/the-stack
train
8ca01583de37c9f0d6a1ef58
train
class
class Test_NonGeneratedEditException: def test_1(self): input = "[[[\n" \ " <<[ edit2 ]>>\n" \ " <<[ end ]>>\n" \ "]]]\n" \ " <<[ edit1 ]>>\n" \ " a\n" \ " <<[ end ]>>\n" \ "[[[ end ]]]\n" ...
class Test_NonGeneratedEditException:
def test_1(self): input = "[[[\n" \ " <<[ edit2 ]>>\n" \ " <<[ end ]>>\n" \ "]]]\n" \ " <<[ edit1 ]>>\n" \ " a\n" \ " <<[ end ]>>\n" \ "[[[ end ]]]\n" msg = "Non-generated edit mark...
end ]>>\\0\n" \ "^^^ line 1, column 1" invalid_marker(input, None, autojinja.exceptions.RequireBodyInlineException, msg) def test_2(self): input = "// [[[ <<[ def ]>><<[ end ]>> ]]]\n" \ "// [[[ end ]]]\n" \ "// [[[ ]]]\n" \ " <<[ d...
256
256
1,372
8
248
ldflo/autojinja
tests/test_exceptions.py
Python
Test_NonGeneratedEditException
Test_NonGeneratedEditException
806
921
806
806
cf6821e56f9deeb82ce926a4a39586013ce317cd
bigcode/the-stack
train
e3fc4615a9891e8d7308764a
train
class
class Test_EndMarkerNotFoundException: def test_1(self): input = "[[[]]] abc" msg = "Couldn't find corresponding end marker \"[[[ end ]]]\":\n" \ "[[[]]] abc\\0\n" \ " ^^^ line 1, column 4" invalid_marker(input, None, autojinja.exceptions.EndMarkerNotFound...
class Test_EndMarkerNotFoundException:
def test_1(self): input = "[[[]]] abc" msg = "Couldn't find corresponding end marker \"[[[ end ]]]\":\n" \ "[[[]]] abc\\0\n" \ " ^^^ line 1, column 4" invalid_marker(input, None, autojinja.exceptions.EndMarkerNotFoundException, msg) def test_2(self): ...
[[[ ]]]\n" \ " [[[ end ]]]\n" \ "<<[ end ]>>\n" \ "[[[end]]]\n" msg = "Couldn't find corresponding close marker \"]>>\":\n" \ "<<[ a\\n\n" \ "^^^ line 2, column 1" invalid_marker(input, None, autojinja.exceptions.Close...
256
256
1,781
8
248
ldflo/autojinja
tests/test_exceptions.py
Python
Test_EndMarkerNotFoundException
Test_EndMarkerNotFoundException
129
266
129
129
0f4fc8fc4024fc497af808b1baa5d47acb498ac3
bigcode/the-stack
train
0bcf540ae9a21b7177396e65
train
class
class Test_Jinja2Exceptions: class Test_TemplateSyntaxError: def test_1(self): input = "[[[ {{ ]]]\n" \ "[[[ end ]]]" msg = "\n File \"<unknown>\", line 1, in template\n" \ "unexpected 'end of template'" invalid_marker(input, None,...
class Test_Jinja2Exceptions:
class Test_TemplateSyntaxError: def test_1(self): input = "[[[ {{ ]]]\n" \ "[[[ end ]]]" msg = "\n File \"<unknown>\", line 1, in template\n" \ "unexpected 'end of template'" invalid_marker(input, None, jinja2.exceptions.TemplateSy...
" \ " <<[ a ]>>\n" \ " <<[ end ]>>\n" \ "[[[ end ]]]" output = "<<[ a ]>>\n" \ " [[[ <<[ a ]>><<[ end ]>> ]]]\n" \ " [[[ end ]]]\n" \ "<<[ end ]>>" msg = "\n During generation of \"[[[ <<[ a ]>>...
256
256
1,990
7
249
ldflo/autojinja
tests/test_exceptions.py
Python
Test_Jinja2Exceptions
Test_Jinja2Exceptions
992
1,159
992
992
403da06ce1bc4c186dc584b86321e15471777192
bigcode/the-stack
train
3446067e5be22109c18d8099
train
class
class RequireHeaderMultilineException: pass # Never reached
class RequireHeaderMultilineException:
pass # Never reached
1\n" \ "Marker can't have a multiline header:\n" \ " <<[\\n\n" \ " ^^^ line 1, column 3" invalid_marker(input, None, autojinja.exceptions.RequireHeaderInlineException, msg) class RequireHeaderMultilineException:
64
64
13
7
57
ldflo/autojinja
tests/test_exceptions.py
Python
RequireHeaderMultilineException
RequireHeaderMultilineException
313
314
313
313
e6c7abd56fce98174f9ff7cbf175d0a85de3bef7
bigcode/the-stack
train
263c8423f3cda98edd328d97
train
class
class Test_AlreadyGeneratedEditException: def test_1(self): input = "<<[ abc ]>><<[ end ]>>\n" \ "// [[[ <<[ abc ]>><<[ end ]>> ]]]\n" \ "// [[[ end ]]]" msg = "\n During generation of \"[[[ <<[ abc ]>><<[ end ]>> ]]]\" at line 2, column 4\n" \ "Alrea...
class Test_AlreadyGeneratedEditException:
def test_1(self): input = "<<[ abc ]>><<[ end ]>>\n" \ "// [[[ <<[ abc ]>><<[ end ]>> ]]]\n" \ "// [[[ end ]]]" msg = "\n During generation of \"[[[ <<[ abc ]>><<[ end ]>> ]]]\" at line 2, column 4\n" \ "Already generated edit marker \"<<[ abc ]>>\", ...
output = "[[[ ]]]\n" \ " <<[ a ]>> <<[ end ]>>\n" \ "[[[ end ]]]" msg = "Non-generated edit marker \"<<[ a ]>>\", consider reusing/removing it:\n" \ " <<[ a ]>> <<[ end ]>>\\n\n" \ " ^^^ line 2, column 3" invalid_marker(input, o...
256
256
1,030
8
248
ldflo/autojinja
tests/test_exceptions.py
Python
Test_AlreadyGeneratedEditException
Test_AlreadyGeneratedEditException
923
990
923
923
68f59cad93050a5e57b1edeb1560d117f26a4e43
bigcode/the-stack
train
00171077fe1caa491542e426
train
class
class Test_RequireHeaderInlineException: def test_1(self): input = " <<[\n" \ "]>>\n" \ "<<[ end ]>>" msg = "Marker can't have a multiline header:\n" \ " <<[\\n\n" \ " ^^^ line 1, column 2" invalid_marker(input, None, autojinj...
class Test_RequireHeaderInlineException:
def test_1(self): input = " <<[\n" \ "]>>\n" \ "<<[ end ]>>" msg = "Marker can't have a multiline header:\n" \ " <<[\\n\n" \ " ^^^ line 1, column 2" invalid_marker(input, None, autojinja.exceptions.RequireHeaderInlineException...
]]]\" at line 1, column 1\n" \ " During reinsertion of \"<<[ a ]>>\" at line 1, column 1\n" \ " During generation of \"[[[ <<[ b ]>> ]]]\" at line 1, column 5\n" \ "Couldn't find corresponding end marker \"<<[ end ]>>\":\n" \ "<<[ b ]>>\\0\n" \ ...
136
136
455
8
128
ldflo/autojinja
tests/test_exceptions.py
Python
Test_RequireHeaderInlineException
Test_RequireHeaderInlineException
268
311
268
268
69fbb14d73783f81081ddcc60a2c14bff8a36263
bigcode/the-stack
train
02835f268385711d647ef334
train
class
class Test_RequireNewlineException: def test_1(self): input = "[[[ a ]]]\n" \ "[[[ end ]]] [[[ a ]]] [[[ end ]]]" msg = "Marker can't start on same line as previous end marker:\n" \ "[[[ end ]]] [[[ a ]]] [[[ end ]]]\\0\n" \ " ^^^ line 2, ...
class Test_RequireNewlineException:
def test_1(self): input = "[[[ a ]]]\n" \ "[[[ end ]]] [[[ a ]]] [[[ end ]]]" msg = "Marker can't start on same line as previous end marker:\n" \ "[[[ end ]]] [[[ a ]]] [[[ end ]]]\\0\n" \ " ^^^ line 2, column 13" invalid_marker(in...
) def test_17(self): input = "[[[\n" \ " <<[ a ]>>\n" \ " <<[ end ]>>\n" \ "]]]\n" \ "<<[ a ]>>\n" \ " [[[\n" \ " abc\n" \ " ]]]\n" \ " [[[ end ]]]\n" \ ...
174
174
582
8
166
ldflo/autojinja
tests/test_exceptions.py
Python
Test_RequireNewlineException
Test_RequireNewlineException
486
529
486
486
5bc6a6ac5e1bdf614e6e7a49b49a9fd903c20914
bigcode/the-stack
train
903e04d40b35229751b4184c
train
class
class Test_CloseMarkerNotFoundException: def test_1(self): input = "[[[ abc " msg = "Couldn't find corresponding close marker \"]]]\":\n" \ "[[[ abc \\0\n" \ "^^^ line 1, column 1" invalid_marker(input, None, autojinja.exceptions.CloseMarkerNotFoundException...
class Test_CloseMarkerNotFoundException:
def test_1(self): input = "[[[ abc " msg = "Couldn't find corresponding close marker \"]]]\":\n" \ "[[[ abc \\0\n" \ "^^^ line 1, column 1" invalid_marker(input, None, autojinja.exceptions.CloseMarkerNotFoundException, msg) def test_2(self): inp...
line 1, column 1\n" \ " During reinsertion of \"<<[ a ]>>\" at line 1, column 3\n" \ " During generation of \"[[[ <<[ end ]>> ]]]\" at line 1, column 5\n" \ "Couldn't find corresponding open marker \"<<[ ]>>\":\n" \ "<<[ end ]>>\\0\n" \ ...
130
130
436
8
122
ldflo/autojinja
tests/test_exceptions.py
Python
Test_CloseMarkerNotFoundException
Test_CloseMarkerNotFoundException
89
127
89
89
1c16342a9a81f7bede450e092429246ee98b9360
bigcode/the-stack
train
29bef1b5c70bebc796cb20f6
train
class
class Test_RequireInlineException: def test_1(self): input = "[[[ a ]]] [[[ b ]]]\n" \ "[[[ end ]]]" msg = "Marker must start on same line as previous marker:\n" \ "[[[ end ]]]\\0\n" \ "^^^ line 2, column 1" invalid_marker(input, None, autoji...
class Test_RequireInlineException:
def test_1(self): input = "[[[ a ]]] [[[ b ]]]\n" \ "[[[ end ]]]" msg = "Marker must start on same line as previous marker:\n" \ "[[[ end ]]]\\0\n" \ "^^^ line 2, column 1" invalid_marker(input, None, autojinja.exceptions.RequireInlineExcepti...
4(self): input = "<<[ a ]>>\n" \ " [[[ ]]]\n" \ " <<[ b ]>>\n" \ " <<[ end ]>> <<[ a ]>>\n" \ " [[[ end ]]]\n" \ "<<[ end ]>>" msg = "Marker can't start on same line as previous end marker:\n" \ " ...
147
147
493
7
140
ldflo/autojinja
tests/test_exceptions.py
Python
Test_RequireInlineException
Test_RequireInlineException
531
571
531
531
a3a26128fc3abd2ba78cb4c02f1bf7ef619d7ee7
bigcode/the-stack
train
53b5ef2c8adee70727abeba9
train
class
class Test_WrongInclusionException: def test_1(self): input = "[[[]]]\n" \ " <<[ a ]>>\n" \ "[[[end]]]\n" msg = "Marker has wrong inclusion regarding enclosing markers:\n" \ "[[[end]]]\\n\n" \ "^^^ line 3, column 1" invalid...
class Test_WrongInclusionException:
def test_1(self): input = "[[[]]]\n" \ " <<[ a ]>>\n" \ "[[[end]]]\n" msg = "Marker has wrong inclusion regarding enclosing markers:\n" \ "[[[end]]]\\n\n" \ "^^^ line 3, column 1" invalid_marker(input, None, autojinja.excep...
2, column 4" invalid_marker(input, None, autojinja.exceptions.RequireInlineException, msg) def test_5(self): input = "// [[[ <<[ abc ]>><<[ end ]>> ]]] <<[ abc ]>> \n" \ "<<[ end ]>>\n" \ "// [[[ end ]]]" msg = "Marker must start on same line as previous m...
140
140
469
8
132
ldflo/autojinja
tests/test_exceptions.py
Python
Test_WrongInclusionException
Test_WrongInclusionException
573
615
573
573
65ccdec4bd42dac59456802159ae6c81e5bbd125
bigcode/the-stack
train
e3d61a5d33ef73292aa575c0
train
class
class Test_DuplicateEditException: def test_1(self): input = "<<[ abc ]>>\n" \ "<<[ end ]>>\n" \ "<<[ abc ]>>\n" \ "<<[ end ]>>" msg = "Duplicate edit marker \"<<[ abc ]>>\", consider reusing/removing duplicates:\n" \ "<<[ abc ]>>\\n\...
class Test_DuplicateEditException:
def test_1(self): input = "<<[ abc ]>>\n" \ "<<[ end ]>>\n" \ "<<[ abc ]>>\n" \ "<<[ end ]>>" msg = "Duplicate edit marker \"<<[ abc ]>>\", consider reusing/removing duplicates:\n" \ "<<[ abc ]>>\\n\n" \ "^^^ line 3, c...
\ " [[[ ]]]\n" \ "<<[ end ]>>" msg = "Marker has wrong inclusion regarding enclosing markers:\n" \ "<<[ end ]>>\\0\n" \ "^^^ line 3, column 1" invalid_marker(input, None, autojinja.exceptions.WrongInclusionException, msg) def test...
223
223
746
7
216
ldflo/autojinja
tests/test_exceptions.py
Python
Test_DuplicateEditException
Test_DuplicateEditException
617
672
617
617
37702ba86975132eb87d36e23ff0c91733a927ef
bigcode/the-stack
train
5036ade44e0bd5a37aab0fa8
train
class
class CustomException(Exception): def __init__(self, result, expected): result = str(result).replace('\t', "\\t").replace('\n', "\\n\n") expected = str(expected).replace('\t', "\\t").replace('\n', "\\n\n") message = f"--- Expected ---\n{expected}\\0\n--- Got ---\n{result}\\0" super()...
class CustomException(Exception):
def __init__(self, result, expected): result = str(result).replace('\t', "\\t").replace('\n', "\\n\n") expected = str(expected).replace('\t', "\\t").replace('\n', "\\n\n") message = f"--- Expected ---\n{expected}\\0\n--- Got ---\n{result}\\0" super().__init__(message)
import autojinja import jinja2 import os import sys class CustomException(Exception):
21
64
90
5
15
ldflo/autojinja
tests/test_exceptions.py
Python
CustomException
CustomException
6
11
6
6
ade8edbd398d175289931526e569188f9e540180
bigcode/the-stack
train
81779ada43b5c22f772b0467
train
class
class Test_DirectlyEnclosedEditException: def test_1(self): input = "<<[]>> abc <<[ end ]>>" msg = "Directly enclosed edit marker \"<<[ end ]>>\", consider reusing/removing it:\n" \ "<<[]>> abc <<[ end ]>>\\0\n" \ " ^^^ line 1, column 12" inv...
class Test_DirectlyEnclosedEditException:
def test_1(self): input = "<<[]>> abc <<[ end ]>>" msg = "Directly enclosed edit marker \"<<[ end ]>>\", consider reusing/removing it:\n" \ "<<[]>> abc <<[ end ]>>\\0\n" \ " ^^^ line 1, column 12" invalid_marker(input, None, autojinja.excepti...
]>>" msg = "Duplicate edit marker \"<<[ abc ]>>\", consider reusing/removing duplicates:\n" \ "<<[ abc ]>><<[ end ]>>\\0\n" \ "^^^ line 6, column 1" invalid_marker(input, None, autojinja.exceptions.DuplicateEditException, msg) def test_5(self): input = "//...
256
256
1,416
10
246
ldflo/autojinja
tests/test_exceptions.py
Python
Test_DirectlyEnclosedEditException
Test_DirectlyEnclosedEditException
674
774
674
674
a0a5ea817816a102dfdc0f256271ba8fe09f6b9c
bigcode/the-stack
train
0da7274a7d020bed98f9c799
train
class
class Test: def test_index_to_coordinates(self): input = "abcdef\n" \ "ghijklmnopqrst\n" \ "uvwwyz" for i in range(0, 7): assert autojinja.exceptions.index_to_coordinates(input, i) == (1, 1 + i) for i in range(7, 22): assert autojinja.e...
class Test:
def test_index_to_coordinates(self): input = "abcdef\n" \ "ghijklmnopqrst\n" \ "uvwwyz" for i in range(0, 7): assert autojinja.exceptions.index_to_coordinates(input, i) == (1, 1 + i) for i in range(7, 22): assert autojinja.exceptions.in...
n During generation of \"[[[ <<[ a ]>>\\n <<[ end ]>> ]]]\" at line 1, column 1\n" \ " During reinsertion of \"<<[ a ]>>\" at line 1, column 3\n" \ " File \"{{ ['arg1']|var_filter }}\", line 1, in top-level template code\n" \ "Tes...
256
256
3,331
3
252
ldflo/autojinja
tests/test_exceptions.py
Python
Test
Test
1,161
1,377
1,161
1,161
16bdd30b623823d17a5a9701cdd9e63abc2954cb
bigcode/the-stack
train
245eb04f048211a6a06753f6
train
class
class Test_WrongHeaderIndentationException: def test_1(self): input = " [[[\n" \ "]]]\n" \ "[[[ end ]]]" msg = "Wrong marker header indentation:\n" \ "]]]\\n\n" \ "^^^ line 2, column 1" invalid_marker(input, None, autojinja.ex...
class Test_WrongHeaderIndentationException:
def test_1(self): input = " [[[\n" \ "]]]\n" \ "[[[ end ]]]" msg = "Wrong marker header indentation:\n" \ "]]]\\n\n" \ "^^^ line 2, column 1" invalid_marker(input, None, autojinja.exceptions.WrongHeaderIndentationException, ms...
have a multiline header:\n" \ "// <<[\\n\n" \ " ^^^ line 1, column 4" invalid_marker(input, None, autojinja.exceptions.RequireHeaderInlineException, msg) def test_4(self): input = "[[[\n" \ " <<[\n" \ " a\n" \ " ]...
256
256
1,633
9
246
ldflo/autojinja
tests/test_exceptions.py
Python
Test_WrongHeaderIndentationException
Test_WrongHeaderIndentationException
316
484
316
316
68d9910b6833234a3dc4cfe874bbdcc379ecd521
bigcode/the-stack
train
d5f9c750bc8464dc74bb8fe1
train
function
def invalid_marker(input, output, exception_type, message, *args, **kwargs): try: template = autojinja.CogTemplate.from_string(input) template.context(*args, **kwargs).render(output) except BaseException as e: exception = e else: exception = None if message != None and st...
def invalid_marker(input, output, exception_type, message, *args, **kwargs):
try: template = autojinja.CogTemplate.from_string(input) template.context(*args, **kwargs).render(output) except BaseException as e: exception = e else: exception = None if message != None and str(exception) != str(message): raise CustomException(exception, messag...
('\t', "\\t").replace('\n', "\\n\n") message = f"--- Expected ---\n{expected}\\0\n--- Got ---\n{result}\\0" super().__init__(message) def invalid_marker(input, output, exception_type, message, *args, **kwargs):
64
64
110
18
46
ldflo/autojinja
tests/test_exceptions.py
Python
invalid_marker
invalid_marker
13
24
13
13
16c8cdfa69db3e2d7ec68b328f9c2e71baa629ed
bigcode/the-stack
train
62cebc49de09f8db2d0178a7
train
class
class Test_OpenMarkerNotFoundException: def test_1(self): input = "[[[end]]]" msg = "Couldn't find corresponding open marker \"[[[ ]]]\":\n" \ "[[[end]]]\\0\n" \ "^^^ line 1, column 1" invalid_marker(input, None, autojinja.exceptions.OpenMarkerNotFoundExcept...
class Test_OpenMarkerNotFoundException:
def test_1(self): input = "[[[end]]]" msg = "Couldn't find corresponding open marker \"[[[ ]]]\":\n" \ "[[[end]]]\\0\n" \ "^^^ line 1, column 1" invalid_marker(input, None, autojinja.exceptions.OpenMarkerNotFoundException, msg) def test_2(self): ...
import autojinja import jinja2 import os import sys class CustomException(Exception): def __init__(self, result, expected): result = str(result).replace('\t', "\\t").replace('\n', "\\n\n") expected = str(expected).replace('\t', "\\t").replace('\n', "\\n\n") message = f"--- Expected ---\n{ex...
224
255
851
8
216
ldflo/autojinja
tests/test_exceptions.py
Python
Test_OpenMarkerNotFoundException
Test_OpenMarkerNotFoundException
26
87
26
26
d2ce1ea76b793918fdde0078b26bcce7b3062fd3
bigcode/the-stack
train
196851e7b1ff827f4016a646
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ("auth", "0012_alter_user_first_name_max_length"), ] operations = [ migrations.CreateModel( name="User", fields=[ ( "id", models.BigAu...
class Migration(migrations.Migration):
initial = True dependencies = [ ("auth", "0012_alter_user_first_name_max_length"), ] operations = [ migrations.CreateModel( name="User", fields=[ ( "id", models.BigAutoField( auto_cr...
# Generated by Django 3.2.9 on 2021-11-17 16:54 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration):
56
199
665
7
48
w4nd0/KMDB
accounts/migrations/0001_initial.py
Python
Migration
Migration
9
132
9
10
c9b9099c5db63a911e902889e3758de85f1bdef3
bigcode/the-stack
train
bfe6620311f202e72d49c947
train
class
class ConfInfo(object): def __init__(self, edgeName=None, productKey=None, identifier=None, secret=None, registryToken=None, installerUrl=None): """ :param edgeName: (Optional) Edge名称 :param productKey: (Optional) Edge产品Key :param identifier: (Optional) Edge的identifier信息 :pa...
class ConfInfo(object):
def __init__(self, edgeName=None, productKey=None, identifier=None, secret=None, registryToken=None, installerUrl=None): """ :param edgeName: (Optional) Edge名称 :param productKey: (Optional) Edge产品Key :param identifier: (Optional) Edge的identifier信息 :param secret: (Optional) Ed...
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. # # NOTE: This class is auto generated by the jdcloud code generator program. class ConfInfo(object):
64
64
174
5
59
Tanc009/jdcloud-sdk-python
jdcloud_sdk/services/iotedge/models/ConfInfo.py
Python
ConfInfo
ConfInfo
20
37
20
21
0dcf17df0edfcf88a5635e300c831c7416997da9
bigcode/the-stack
train
9e4a1a3fff40e510b579d87e
train
class
class ReadDTCInformation(BaseService): _sid = 0x19 supported_negative_response = [ Response.Code.SubFunctionNotSupported, Response.Code.IncorrectMessageLengthOrInvalidFormat, Response.Code.RequestOutOf...
class ReadDTCInformation(BaseService):
_sid = 0x19 supported_negative_response = [ Response.Code.SubFunctionNotSupported, Response.Code.IncorrectMessageLengthOrInvalidFormat, Response.Code.RequestOutOfRange ...
from __future__ import absolute_import from . import * from udsoncan.Response import Response from udsoncan.exceptions import * import struct class ReadDTCInformation(BaseService):
38
256
6,779
8
29
autopi-io/py-udsoncan
udsoncan/services/ReadDTCInformation.py
Python
ReadDTCInformation
ReadDTCInformation
7
620
7
7
dd7416fae4c7387ab64c732fb1e6221b726c3973
bigcode/the-stack
train
3c0d76b0e3ec9c75f68ec74a
train
function
def main(argv: Sequence[str]) -> None: if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') # Read the Mujoco model. filename = FLAGS.xml_model_path with file.File(filename) as f: logging.info('Loading mujoco model from %s', filename) xml_string = f.read() # Convert the mod...
def main(argv: Sequence[str]) -> None:
if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') # Read the Mujoco model. filename = FLAGS.xml_model_path with file.File(filename) as f: logging.info('Loading mujoco model from %s', filename) xml_string = f.read() # Convert the model. m = mujoco.MujocoConverter( ...
', 4, 'Substeps to perform to maintain numerical stability.') flags.DEFINE_bool('ignore_unsupported_joints', False, 'Ignores unsupported joints.') flags.DEFINE_bool('add_joint_to_nearest_body', False, 'Adds a joint to the nearest (child)body.') def main(argv: Seq...
73
74
249
10
63
bharadwaj1098/brax
brax/tools/mujoco_converter.py
Python
main
main
51
80
51
51
ddd2a55bd2670fbe48c4d86b7bf063038ce70bff
bigcode/the-stack
train
2e30688a0f737b08957bf293
train
class
class data_generator(Sequence): 'Generates data for Keras' def __init__(self, X, Y, batch_size, shuffle): 'Initialization' self.X = X self.Y = Y self.batch_size = batch_size self.shuffle = shuffle self.on_epoch_end() def on_epoch_end(self): 'U...
class data_generator(Sequence):
'Generates data for Keras' def __init__(self, X, Y, batch_size, shuffle): 'Initialization' self.X = X self.Y = Y self.batch_size = batch_size self.shuffle = shuffle self.on_epoch_end() def on_epoch_end(self): 'Updates indexes after each epoch'...
""" Customise data generator for training model in Keras """ import numpy as np from tensorflow.keras.utils import Sequence class data_generator(Sequence):
31
81
271
6
24
zhengzhang96/Hardware-efficient-MUA-compression
Behavioral decoding/HPC code/functions/generator.py
Python
data_generator
data_generator
8
39
8
8
83ed1398decae6eddcbfa2d4fb0dc8554eabfaf3
bigcode/the-stack
train
e749d79e5833f7e139157cec
train
class
class VerifyChecksumTestCase(test.NoDBTestCase): def setUp(self): super(VerifyChecksumTestCase, self).setUp() self.img = {'container_format': 'ami', 'id': '42'} self.flags(checksum_base_images=True, group='libvirt') def _make_checksum(self, tmpdir): testdata = ('OpenStack Softw...
class VerifyChecksumTestCase(test.NoDBTestCase):
def setUp(self): super(VerifyChecksumTestCase, self).setUp() self.img = {'container_format': 'ami', 'id': '42'} self.flags(checksum_base_images=True, group='libvirt') def _make_checksum(self, tmpdir): testdata = ('OpenStack Software delivers a massively scalable cloud ' ...
_filename + '.info') os.utime(base_filename + '.info', (old, old)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(None, all_instances) self.assertTrue(os.path.exists(base_filename)) self.assertTrue(os.path.exists(base_filenam...
255
256
914
11
244
bopopescu/nested_quota
nova/tests/virt/libvirt/test_imagecache.py
Python
VerifyChecksumTestCase
VerifyChecksumTestCase
786
887
786
787
f1472bc65e0aa50b12153caabcb4994cf50aaf5d
bigcode/the-stack
train
d25b9b49a505edd029168765
train
function
@contextlib.contextmanager def intercept_log_messages(): try: mylog = logging.getLogger('nova') stream = cStringIO.StringIO() handler = logging.logging.StreamHandler(stream) handler.setFormatter(logging.ContextFormatter()) mylog.logger.addHandler(handler) yield stream...
@contextlib.contextmanager def intercept_log_messages():
try: mylog = logging.getLogger('nova') stream = cStringIO.StringIO() handler = logging.logging.StreamHandler(stream) handler.setFormatter(logging.ContextFormatter()) mylog.logger.addHandler(handler) yield stream finally: mylog.logger.removeHandler(handler)...
utils from nova.virt.libvirt import imagecache from nova.virt.libvirt import utils as libvirt_utils CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') @contextlib.contextmanager def intercept_log_messages():
64
64
73
11
53
bopopescu/nested_quota
nova/tests/virt/libvirt/test_imagecache.py
Python
intercept_log_messages
intercept_log_messages
42
52
42
43
e8f068df83681d19942ad94187317e9e49408079
bigcode/the-stack
train
a67a5b8f1d858ff95c9666f0
train
class
class ImageCacheManagerTestCase(test.NoDBTestCase): def setUp(self): super(ImageCacheManagerTestCase, self).setUp() self.stock_instance_names = set(['instance-00000001', 'instance-00000002', 'instance-00000003', ...
class ImageCacheManagerTestCase(test.NoDBTestCase):
def setUp(self): super(ImageCacheManagerTestCase, self).setUp() self.stock_instance_names = set(['instance-00000001', 'instance-00000002', 'instance-00000003', 'banana-42-hamste...
OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import cStringIO import hashlib import os import time from oslo.config import cfg from nova import conductor from nova import db from ...
256
256
6,758
12
244
bopopescu/nested_quota
nova/tests/virt/libvirt/test_imagecache.py
Python
ImageCacheManagerTestCase
ImageCacheManagerTestCase
55
783
55
56
def3933a6b2d22221a8ebc8619fbb0705d9a059b
bigcode/the-stack
train
f31efd0f82118ab729dccb1c
train
class
class Vector(commands.Bot): def __init__(self, **kwargs): super().__init__(**kwargs) self.session = aiohttp.ClientSession() async def on_ready(self): print('Bot is ready.')
class Vector(commands.Bot):
def __init__(self, **kwargs): super().__init__(**kwargs) self.session = aiohttp.ClientSession() async def on_ready(self): print('Bot is ready.')
import discord from discord.ext import commands from os import getenv import aiohttp import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) class Vector(commands.Bot):
39
64
47
5
34
drapespy/vector-cogs
bot.py
Python
Vector
Vector
9
16
9
9
14653a4a166ecf5bfb22ac5fff916fe40b06aaaf
bigcode/the-stack
train
c3433d8170b8b1f6230642c0
train
class
class V2alpha1CronJobStatus(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. attrib...
class V2alpha1CronJobStatus(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 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re...
85
250
836
10
74
anemerovsky-essextec/python
kubernetes/client/models/v2alpha1_cron_job_status.py
Python
V2alpha1CronJobStatus
V2alpha1CronJobStatus
19
154
19
19
80788089716fac00ec10e1d638a64327675bf9f2
bigcode/the-stack
train
2e8ce3df37c970077eecbde1
train
class
class DokuTest(unittest.TestCase): PASSWORD = "CorrectHorseBatteryStaple" EMAIL = "test@doku.test" def setUp(self): self.app = create_app(test=True) self.client = self.app.test_client() with self.app.app_context(): db.create_all(app=self.app) user = User() ...
class DokuTest(unittest.TestCase):
PASSWORD = "CorrectHorseBatteryStaple" EMAIL = "test@doku.test" def setUp(self): self.app = create_app(test=True) self.client = self.app.test_client() with self.app.app_context(): db.create_all(app=self.app) user = User() user.set_password(self.PA...
import unittest from doku import create_app from doku.models import db from doku.models.user import User class DokuTest(unittest.TestCase):
33
64
129
8
24
desklab/doku
doku/tests/__init__.py
Python
DokuTest
DokuTest
8
28
8
9
b554a7cc443e3dbadeb7abd5e5e3b3ae8743599d
bigcode/the-stack
train
f4bf8c7f268f6e5f79a48cdc
train
function
@pytest.mark.parametrize('data', ( ({'filter': 'value'}), ({'filter': 123}), ({'filter': 3.14159}), ({ 'filter1': 'value1', 'filter2': 123, 'filter3': 3.14159 }) )) def test_extracts_values_correctly(data): parsed = url_params.parse({str(n): str(v) for n, v in data.items(...
@pytest.mark.parametrize('data', ( ({'filter': 'value'}), ({'filter': 123}), ({'filter': 3.14159}), ({ 'filter1': 'value1', 'filter2': 123, 'filter3': 3.14159 }) )) def test_extracts_values_correctly(data):
parsed = url_params.parse({str(n): str(v) for n, v in data.items()}) assert parsed == data
@pytest.mark.parametrize('data', ( ({'filter': 'value'}), ({'filter': 123}), ({'filter': 3.14159}), ({ 'filter1': 'value1', 'filter2': 123, 'filter3': 3.14159 }) )) def test_extracts_values_correctly(data):
76
64
104
76
0
novopl/restible
src/test/restible/params/test_parse.py
Python
test_extracts_values_correctly
test_extracts_values_correctly
12
25
12
22
45ef70985f0a2dda676d41be35f13bf561c0791d
bigcode/the-stack
train
8e253bf4188768ab6fbc277f
train
function
def RCL(input_shape, rec_conv_layers, dense_layers, output_layer=[1, 'sigmoid'], padding='same', optimizer='adam', loss='binary_crossentropy'): """Summary Args: input_shape (tuple): The shape of the input layer. output_nodes (int): Number of...
def RCL(input_shape, rec_conv_layers, dense_layers, output_layer=[1, 'sigmoid'], padding='same', optimizer='adam', loss='binary_crossentropy'):
"""Summary Args: input_shape (tuple): The shape of the input layer. output_nodes (int): Number of nodes in the output layer. It depends on the loss function used. rec_conv_layers (list): RCL descriptor [ [ ...
1D(time_conv_layer[0][0], time_conv_layer[0][1], padding=padding) c2a = _c2(input) s2a = add([outer_conv, c2a]) b2a = BatchNormalization()(s2a) a2a = LeakyReLU(alpha=time_conv_layer[2])(b2a) d2a = Dropout(time_conv_layer[3])(a2a) input = d2a return ...
152
152
507
44
107
gkroussos/pdkit
pdkit/models.py
Python
RCL
RCL
52
113
52
58
276cb95d3680a8331b4b94e4edddd0ef8936c47c
bigcode/the-stack
train
a2064f81f3aa6819cd6c35aa
train
function
def time_steps(input, conv_layer, time_conv_layer, padding): conv = Conv1D(conv_layer[0][0], conv_layer[0][1], padding=padding)(input) batch = BatchNormalization()(conv) act = LeakyReLU(alpha=conv_layer[2])(batch) inner = shared_weights_steps(input=act, outer_conv =...
def time_steps(input, conv_layer, time_conv_layer, padding):
conv = Conv1D(conv_layer[0][0], conv_layer[0][1], padding=padding)(input) batch = BatchNormalization()(conv) act = LeakyReLU(alpha=conv_layer[2])(batch) inner = shared_weights_steps(input=act, outer_conv = conv, time_conv_layer=time_conv...
1D from keras.layers.pooling import AveragePooling1D, MaxPooling1D from keras.layers.normalization import BatchNormalization from keras.layers.merge import add from keras.layers.advanced_activations import LeakyReLU def time_steps(input, conv_layer, time_conv_layer, padding):
64
64
145
15
48
gkroussos/pdkit
pdkit/models.py
Python
time_steps
time_steps
20
34
20
20
abb59f844db6616a6d71560989001ac296907bc9
bigcode/the-stack
train
fa6c1e92f447d99225551e8b
train
function
def shared_weights_steps(input, outer_conv, time_conv_layer, padding): for i in range(time_conv_layer[4]): if i == 0: _c2 = Conv1D(time_conv_layer[0][0], time_conv_layer[0][1], padding=padding) c2a = _c2(input) s2a = add([outer_conv, c2a]) b2a = BatchNormalization()(...
def shared_weights_steps(input, outer_conv, time_conv_layer, padding):
for i in range(time_conv_layer[4]): if i == 0: _c2 = Conv1D(time_conv_layer[0][0], time_conv_layer[0][1], padding=padding) c2a = _c2(input) s2a = add([outer_conv, c2a]) b2a = BatchNormalization()(s2a) a2a = LeakyReLU(alpha=time_conv_layer[2])(b2a) d2a...
pool = MaxPooling1D(pool_size=conv_layer[1][0], strides=conv_layer[1][1], padding=padding)(inner) drop = Dropout(conv_layer[3])(pool) return drop def shared_weights_steps(input, outer_conv, time_conv_layer, padding):
64
64
147
15
48
gkroussos/pdkit
pdkit/models.py
Python
shared_weights_steps
shared_weights_steps
36
49
36
36
b4fb22258d01be9f8895f1b335ce0b2a4cde6e5a
bigcode/the-stack
train
362a6d4fb2a7b3c06b09064e
train
function
def VOICE(input_shape, conv_layers, dense_layers, output_layer=[1, 'sigmoid'], padding='same', optimizer='adam', loss='binary_crossentropy'): """Conv1D CNN used primarily for voice data. Args: input_shape (tuple): The shape of the i...
def VOICE(input_shape, conv_layers, dense_layers, output_layer=[1, 'sigmoid'], padding='same', optimizer='adam', loss='binary_crossentropy'):
"""Conv1D CNN used primarily for voice data. Args: input_shape (tuple): The shape of the input layer targets (int): Number of targets conv_layers (list): Conv layer descriptor [[(filter, kernel), (pool_size, stride), leak, drop], ... []] dense_layers (TYPE): Dense layer desc...
bn = BatchNormalization()(dense) act = LeakyReLU(alpha=d[1])(bn) drop = Dropout(d[2])(act) output = Dense(output_layer[0], activation=output_layer[1])(drop) model = Model(inputs=inputs, outputs=output) model.compile(loss=loss, optimizer=optimizer, metrics=['accurac...
128
128
427
42
85
gkroussos/pdkit
pdkit/models.py
Python
VOICE
VOICE
116
162
116
122
5c971f568471a0174e92a58199dbc5e4dc1a3086
bigcode/the-stack
train
27cab9152a38b2a2dbc9a302
train
function
def DNN(input_shape, dense_layers, output_layer=[1, 'sigmoid'], optimizer='adam', loss='binary_crossentropy'): """Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense la...
def DNN(input_shape, dense_layers, output_layer=[1, 'sigmoid'], optimizer='adam', loss='binary_crossentropy'):
"""Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense layer descriptor [fully_connected] optimizer (str or object optional): Keras optimizer as string or keras optimizer Returns: TYPE: m...
model = Model(inputs=inputs, outputs=output) model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy']) return model def DNN(input_shape, dense_layers, output_layer=[1, 'sigmoid'], optimizer='adam', loss='binary_crossentropy'):
64
64
213
32
31
gkroussos/pdkit
pdkit/models.py
Python
DNN
DNN
165
196
165
169
78a93bf1d95e456c0dde731269dcb0f9a77d9045
bigcode/the-stack
train
c88edf6e7484a9af7f2cbf20
train
function
def state_from_coherence_vector(n,d,state=True): ''' Uses the supplied coherence vector n to generate the corresponding operator via X=(1/d)*(eye(d)+n*L), where L are the su(d) generators. n is a vector of length d^2. ''' L=su_generators(d) X=np.array(np.zeros((d,d)),dtype=np.comple...
def state_from_coherence_vector(n,d,state=True):
''' Uses the supplied coherence vector n to generate the corresponding operator via X=(1/d)*(eye(d)+n*L), where L are the su(d) generators. n is a vector of length d^2. ''' L=su_generators(d) X=np.array(np.zeros((d,d)),dtype=np.complex128) for i in range(len(L)): X+=...
must retain this copyright notice, and modified files need to carry a notice indicating that they have been altered from the originals. ''' import numpy as np from qutipy.su import su_generators from qutipy.general_functions import eye def state_from_coherence_vector(n,d,state=True):
64
64
112
11
52
sumeetkhatri/QuTIPy
qutipy/su/state_from_coherence_vector.py
Python
state_from_coherence_vector
state_from_coherence_vector
22
39
22
23
d312871fbf7c1f437eac833ffbb83f94a7413ae7
bigcode/the-stack
train
1c7c16b535d8099669c8e157
train
function
def make_bitmapVID_docstring(id_modules_working_points_pset): pset = id_modules_working_points_pset for modname in pset.modules: ids = __import__(modname, globals(), locals(), ['idName','cutFlow']) for name in dir(ids): _id = getattr(ids,name) if hasattr(_id,'idName') an...
def make_bitmapVID_docstring(id_modules_working_points_pset):
pset = id_modules_working_points_pset for modname in pset.modules: ids = __import__(modname, globals(), locals(), ['idName','cutFlow']) for name in dir(ids): _id = getattr(ids,name) if hasattr(_id,'idName') and hasattr(_id,'cutFlow'): if (len(pset.Working...
-V2p2-loose", "egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-medium", "egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-tight", ) ) def make_bitmapVID_docstring(id_modules_working_points_pset):
64
64
199
14
50
nistefan/cmssw
PhysicsTools/NanoAOD/python/photons_cff.py
Python
make_bitmapVID_docstring
make_bitmapVID_docstring
35
47
35
35
9255d46fdb44a79d981187c3ae0467c1682debe3
bigcode/the-stack
train
fdc2f9d6f421f1d9627171b1
train
class
class RenameDialog(QtWidgets.QDialog): ''' parent: SourceWindow that started the new XrefDialog ''' def __init__(self, parent=None, win=None, element="", info=()): super(RenameDialog, self).__init__(parent) self.sourceWin = parent self.info = info self.element = ele...
class RenameDialog(QtWidgets.QDialog):
''' parent: SourceWindow that started the new XrefDialog ''' def __init__(self, parent=None, win=None, element="", info=()): super(RenameDialog, self).__init__(parent) self.sourceWin = parent self.info = info self.element = element title = "Rename: " + eleme...
from PyQt5 import QtWidgets, QtGui from androguard.core import androconf class RenameDialog(QtWidgets.QDialog):
27
84
281
8
18
tkgwJeff/androguard
androguard/gui/renamewindow.py
Python
RenameDialog
RenameDialog
5
42
5
5
33f270fb4ed1fc6dae3143487d87dcde7cd6be8b
bigcode/the-stack
train
140726c00845283d18a07d00
train
function
@Command('s4clib.show_running_situations', command_type=CommandType.Live) def _common_show_running_situations(opt_sim: OptionalTargetParam=None, _connection: int=None): from server_commands.argument_helpers import get_optional_target output = CheatOutput(_connection) sim = get_optional_target(opt_sim, _conn...
@Command('s4clib.show_running_situations', command_type=CommandType.Live) def _common_show_running_situations(opt_sim: OptionalTargetParam=None, _connection: int=None):
from server_commands.argument_helpers import get_optional_target output = CheatOutput(_connection) sim = get_optional_target(opt_sim, _connection) sim_info = CommonSimUtils.get_sim_info(sim) if sim_info is None: output('Failed, no Sim was specified or the specified Sim was not found!') ...
als is not None: goal_instances.extend(goal_tracker._realized_minor_goals.keys()) if goal_tracker._realized_main_goal is not None: goal_instances.insert(0, goal_tracker._realized_main_goal) elif isinstance(goal_tracker, DynamicSituationGoalTracker): ...
115
115
384
42
73
ColonolNutty/Sims4CommunityLibrary
Scripts/sims4communitylib/utils/sims/common_sim_situation_utils.py
Python
_common_show_running_situations
_common_show_running_situations
296
326
296
297
ad406d71d9bb35d1da634bb39e03dc38c6b0ca72
bigcode/the-stack
train
563ee67b3f2810c27aa46e85
train
class
class CommonSimSituationUtils: """Utilities for manipulating the Situations of Sims. """ @staticmethod def has_situation(sim_info: SimInfo, situation_id: Union[int, CommonSituationId]) -> bool: """has_situation(sim_info, situation_id) Determine if a Sim is involved in the specified Sit...
class CommonSimSituationUtils:
"""Utilities for manipulating the Situations of Sims. """ @staticmethod def has_situation(sim_info: SimInfo, situation_id: Union[int, CommonSituationId]) -> bool: """has_situation(sim_info, situation_id) Determine if a Sim is involved in the specified Situation. :param sim_inf...
, Iterator, Union, List, Tuple from distributor.shared_messages import IconInfoData from server_commands.argument_helpers import OptionalTargetParam from sims.sim_info import SimInfo from sims4.commands import Command, CommandType, CheatOutput from sims4communitylib.enums.situations_enum import CommonSituationId from ...
256
256
2,621
6
249
ColonolNutty/Sims4CommunityLibrary
Scripts/sims4communitylib/utils/sims/common_sim_situation_utils.py
Python
CommonSimSituationUtils
CommonSimSituationUtils
32
293
32
32
8f738571d08b47707241d2e6bdb0b40bc7878852
bigcode/the-stack
train
643dc4e61325109fab4a20fe
train
class
class Glpk(AutotoolsPackage, GNUMirrorPackage): """The GLPK (GNU Linear Programming Kit) package is intended for solving large-scale linear programming (LP), mixed integer programming (MIP), and other related problems. It is a set of routines written in ANSI C and organized in the form of a callable lib...
class Glpk(AutotoolsPackage, GNUMirrorPackage):
"""The GLPK (GNU Linear Programming Kit) package is intended for solving large-scale linear programming (LP), mixed integer programming (MIP), and other related problems. It is a set of routines written in ANSI C and organized in the form of a callable library. """ homepage = "https://www.gnu.o...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Glpk(AutotoolsPackage, GNUMirrorPackage):
68
95
317
14
54
plamborn/spack
var/spack/repos/builtin/packages/glpk/package.py
Python
Glpk
Glpk
9
36
9
9
6eb2274f1826a6d10d6dd8f3ffec4ecd5ea0d920
bigcode/the-stack
train
3ec9c896bccb5965391071a1
train
function
def _pgather_parallel_translation(ctx, avals_in, avals_out, src, idx, *, axes): if any(not isinstance(axis, int) for axis in axes): raise NotImplementedError("pgather only supported in the SPMD lowering." "Please open a feature request!") return xla.lower_fun(_pgather_impl, multipl...
def _pgather_parallel_translation(ctx, avals_in, avals_out, src, idx, *, axes):
if any(not isinstance(axis, int) for axis in axes): raise NotImplementedError("pgather only supported in the SPMD lowering." "Please open a feature request!") return xla.lower_fun(_pgather_impl, multiple_results=False, new_style=True)( ctx, avals_in, avals_out, src, idx, axes...
sorted((a for a in axes if isinstance(a, int)), reverse=True): del shape[axis] shape = idx.shape + tuple(shape) return ShapedArray(shape, src.dtype) def _pgather_parallel_translation(ctx, avals_in, avals_out, src, idx, *, axes):
64
64
100
23
41
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pgather_parallel_translation
_pgather_parallel_translation
1,491
1,496
1,491
1,491
d26daeda25d048d58d6663d8e1e749b14baeab1c
bigcode/the-stack
train
5f3b62fd539edde0dc89f148
train
function
def _replica_groups(axis_env, axis_name, axis_index_groups): replica_groups = xla.axis_groups(axis_env, axis_name) if axis_index_groups is not None: replica_groups = [[axis_group[i] for i in axis_index_group] for axis_group in replica_groups for axis_index_group in ax...
def _replica_groups(axis_env, axis_name, axis_index_groups):
replica_groups = xla.axis_groups(axis_env, axis_name) if axis_index_groups is not None: replica_groups = [[axis_group[i] for i in axis_index_group] for axis_group in replica_groups for axis_index_group in axis_index_groups] return replica_groups
) if isinstance(axis, int) else axis if axis != frame_name else d for axis in axes), d_vals_in)) return vals_out, [batching.not_mapped] * len(vals_out) def _replica_groups(axis_env, axis_n...
64
64
77
15
49
rsepassi/jax
jax/_src/lax/parallel.py
Python
_replica_groups
_replica_groups
617
623
617
617
a289be668034d8c4dbd2643ab2e61b1b573ecaff
bigcode/the-stack
train
33b64718e88d37ec493fcaca
train
function
def _all_to_all_via_all_gather(x, *, axis_name, split_axis, concat_axis, axis_index_groups): idx = _index_in_group(axis_name, axis_index_groups) full = all_gather(x, axis_name, axis_index_groups=axis_index_groups) axis_size = full.shape[0] tile_size = x.shape[split_axis] // axis_size tile_base_idx = idx * til...
def _all_to_all_via_all_gather(x, *, axis_name, split_axis, concat_axis, axis_index_groups):
idx = _index_in_group(axis_name, axis_index_groups) full = all_gather(x, axis_name, axis_index_groups=axis_index_groups) axis_size = full.shape[0] tile_size = x.shape[split_axis] // axis_size tile_base_idx = idx * tile_size sliced = slicing.dynamic_slice_in_dim(full, tile_base_idx, tile_size, ...
_groups.argsort() % len(axis_index_groups[0]) return lax.squeeze( slicing.dynamic_slice_in_dim(device_id_to_idx, cur_device_id, 1), [0]) def _all_to_all_via_all_gather(x, *, axis_name, split_axis, concat_axis, axis_index_groups):
64
64
136
26
38
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_to_all_via_all_gather
_all_to_all_via_all_gather
842
850
842
842
601d93eac490d24f5637176558e91357805e109b
bigcode/the-stack
train
f47964462fba656dc7dbf563
train
function
def _splitaxis(axis, factor, x): new_shape = list(x.shape) assert new_shape[axis] % factor == 0, (new_shape[axis], factor) new_shape[axis:axis+1] = [factor, new_shape[axis] // factor] return x.reshape(new_shape)
def _splitaxis(axis, factor, x):
new_shape = list(x.shape) assert new_shape[axis] % factor == 0, (new_shape[axis], factor) new_shape[axis:axis+1] = [factor, new_shape[axis] // factor] return x.reshape(new_shape)
(_subst_all_names_in_param, 'axis_name') def _moveaxis(src, dst, x): perm = [i for i in range(x.ndim) if i != src] perm.insert(dst, src) return lax.transpose(x, perm) def _splitaxis(axis, factor, x):
64
64
68
10
54
rsepassi/jax
jax/_src/lax/parallel.py
Python
_splitaxis
_splitaxis
821
825
821
821
727f71dd32864bf97864a84a23882bc1e68aa231
bigcode/the-stack
train
3e914bdc36a625e753fcd2db
train
function
def pgather(src, idx, axes: Union[int, AxisName]): """Uses the last positional axis of idx to index into src's axes.""" if not isinstance(axes, (tuple, list)): axes = (axes,) # TODO: Canonicalize exes! return pgather_p.bind(src, idx, axes=tuple(axes))
def pgather(src, idx, axes: Union[int, AxisName]):
"""Uses the last positional axis of idx to index into src's axes.""" if not isinstance(axes, (tuple, list)): axes = (axes,) # TODO: Canonicalize exes! return pgather_p.bind(src, idx, axes=tuple(axes))
arg_specs = [] cont = True while not self.eof: cont, result = self.parse_arg() arg_specs.append(result) if cont: arg_specs.append(([], [])) return arg_specs def pgather(src, idx, axes: Union[int, AxisName]):
64
64
75
15
48
rsepassi/jax
jax/_src/lax/parallel.py
Python
pgather
pgather
535
540
535
535
1e817079152f99fa108f636b06645e477d24ae98
bigcode/the-stack
train
18c712dbd4172791aed0f9c2
train
function
def _all_to_all_translation_rule(ctx, avals_in, avals_out, x, *, split_axis, concat_axis, axis_name, axis_index_groups): # Workaround for AllToAll not being implemented on CPU. replica_groups = _replica_groups(ctx.axis_env, axis_name, axis_index_groups) if len(replica_groups[0]) =...
def _all_to_all_translation_rule(ctx, avals_in, avals_out, x, *, split_axis, concat_axis, axis_name, axis_index_groups): # Workaround for AllToAll not being implemented on CPU.
replica_groups = _replica_groups(ctx.axis_env, axis_name, axis_index_groups) if len(replica_groups[0]) == 1: return [x] elif (ctx.platform == "tpu") or ((ctx.platform == "gpu") and (split_axis == 0) and (concat_axis == 0)): split_count = len(replica_groups[0]) if not all...
tile_base_idx = idx * tile_size sliced = slicing.dynamic_slice_in_dim(full, tile_base_idx, tile_size, split_axis + 1) return _foldaxis(concat_axis, _moveaxis(0, concat_axis, sliced)) def _all_to_all_translation_rule(ctx, avals_in, avals_out, x, *, split_axis, ...
102
102
342
48
54
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_to_all_translation_rule
_all_to_all_translation_rule
852
879
852
854
db4c7490a5035be133b5916ff9d541342f9f3622
bigcode/the-stack
train
dc2b3ecae93d71c17a7182bf
train
function
def _allreduce_translation_rule(prim, pos_fn, ctx, avals_in, avals_out, *args, axes, axis_index_groups): c = ctx.builder if axis_index_groups is not None and ctx.platform == "tpu": len_0 = len(axis_index_groups[0]) if any(len(g) != len_0 for g in axis_index_groups): rai...
def _allreduce_translation_rule(prim, pos_fn, ctx, avals_in, avals_out, *args, axes, axis_index_groups):
c = ctx.builder if axis_index_groups is not None and ctx.platform == "tpu": len_0 = len(axis_index_groups[0]) if any(len(g) != len_0 for g in axis_index_groups): raise ValueError("axis_index_groups must all be the same size") named_axes, positional_axes = axes_partition = [], [] for axis in axes: ...
if len(pos_axes) != 0: raise ValueError(f"axis_index_groups can only be used with reductions over " f"named axes, but got: {axes}") return [ShapedArray(lax._reduce_op_shape_rule(raise_to_shaped(arg), axes=pos_axes), arg.dtype, named_shape=named_shape) f...
119
119
398
32
87
rsepassi/jax
jax/_src/lax/parallel.py
Python
_allreduce_translation_rule
_allreduce_translation_rule
646
680
646
647
cb6402e8996fe08499a4582d10248577f2e9b88e
bigcode/the-stack
train
cf2496769a03ff5433dbe79e
train
function
def all_gather(x, axis_name, *, axis_index_groups=None, axis=0, tiled=False): """Gather values of x across all replicas. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This is equivalent to, but faster than, all_to_all(broadcast(x)). Args: x: array...
def all_gather(x, axis_name, *, axis_index_groups=None, axis=0, tiled=False):
"""Gather values of x across all replicas. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This is equivalent to, but faster than, all_to_all(broadcast(x)). Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python obj...
if axis_index_groups is None else len(axis_index_groups[0]) assert shape[split_axis] % axis_size == 0, (shape[split_axis], axis_size) shape[split_axis] //= axis_size shape[concat_axis] *= axis_size return input_aval.update(shape=tuple(shape), weak_type=False) all_to_all_p = core.AxisPrimitive('all_to_all') al...
243
243
813
22
221
rsepassi/jax
jax/_src/lax/parallel.py
Python
all_gather
all_gather
976
1,044
976
976
897f26855b6e44d52da392cfdb29b72a5ed404e4
bigcode/the-stack
train
4bd615391e290233bdb8d182
train
function
def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis, axis_index_groups): x, = vals_in d, = dims_in result = all_to_all_p.bind( x, axis_name=axis_name, split_axis=split_axis + (d <= split_axis), concat_axis=concat_axis + (d <= concat_axis), axis_index_group...
def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis, axis_index_groups):
x, = vals_in d, = dims_in result = all_to_all_p.bind( x, axis_name=axis_name, split_axis=split_axis + (d <= split_axis), concat_axis=concat_axis + (d <= concat_axis), axis_index_groups=axis_index_groups) return result, d
_all( cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis, axis_index_groups=axis_index_groups),) def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis, axis_index_groups):
64
64
101
27
37
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_to_all_batcher
_all_to_all_batcher
889
898
889
889
4347227ee7e2fea4d7cfdd5271cc2db85f3f1474
bigcode/the-stack
train
314cb2b6cbb84098acbc2a7b
train
function
def _reduce_scatter_via_reducer(x, *, reducer, scatter_dimension, axis_name, axis_index_groups, axis_size, tiled): index = _index_in_group(axis_name, axis_index_groups) scatter_dim_input_size = x.shape[scatter_dimension] if tiled and scatter_dim_input_size % axis_size != 0: r...
def _reduce_scatter_via_reducer(x, *, reducer, scatter_dimension, axis_name, axis_index_groups, axis_size, tiled):
index = _index_in_group(axis_name, axis_index_groups) scatter_dim_input_size = x.shape[scatter_dimension] if tiled and scatter_dim_input_size % axis_size != 0: raise ValueError(f"tiled reduce_scatter operand scatter dimension size " f"{scatter_dim_input_size} must be divisible by " ...
_primitive_batchers[all_gather_p] = _all_gather_batched_collective core.axis_substitution_rules[all_gather_p] = partial(_subst_all_names_in_param, 'axis_name') def _reduce_scatter_via_reducer(x, *, reducer, scatter_dimension, axis_name, axis_index_groups, axis_size, tiled):
74
74
248
30
44
rsepassi/jax
jax/_src/lax/parallel.py
Python
_reduce_scatter_via_reducer
_reduce_scatter_via_reducer
1,165
1,187
1,165
1,166
0b784da39063476da5a982ec5ed0799dc0219ff3
bigcode/the-stack
train
5979a3bf06fcf5c475859a30
train
function
def _axis_index_of_val(x, val, axis_name): idx = axis_index(axis_name) validx = lax_numpy.where(val == x, idx, dtypes.iinfo(dtypes.dtype(idx)).max) return pmin(validx, axis_name)
def _axis_index_of_val(x, val, axis_name):
idx = axis_index(axis_name) validx = lax_numpy.where(val == x, idx, dtypes.iinfo(dtypes.dtype(idx)).max) return pmin(validx, axis_name)
): if isinstance(axis_name, (tuple, list)): raise TypeError(f"pargmin only accepts a single axis, got {axis_name}") return _axis_index_of_val(x, pmax(x, axis_name), axis_name) def _axis_index_of_val(x, val, axis_name):
64
64
55
13
51
rsepassi/jax
jax/_src/lax/parallel.py
Python
_axis_index_of_val
_axis_index_of_val
193
196
193
193
c9e9d8c3bc9ad7dc7b7e0c31ff2bed7dc7efc07e
bigcode/the-stack
train
8c563d3c70e255aa8a4dd063
train
function
def _pdot_vmap_batching_rule(vals_in, dims_in, *, axis_name, pos_contract, pos_batch, precision): x, y = vals_in (pos_contract, pos_batch), result_batch_dim = lax._dot_general_batch_dim_nums( (x.ndim, y.ndim), dims_in, [pos_contract, pos_batch]) out = pdot_p.bind(x, y, axis_name...
def _pdot_vmap_batching_rule(vals_in, dims_in, *, axis_name, pos_contract, pos_batch, precision):
x, y = vals_in (pos_contract, pos_batch), result_batch_dim = lax._dot_general_batch_dim_nums( (x.ndim, y.ndim), dims_in, [pos_contract, pos_batch]) out = pdot_p.bind(x, y, axis_name=axis_name, pos_contract=pos_contract, pos_batch=pos_batch, precision=precision) return out, result_batch...
y_pos_batch], precision=precision) return out, None batching.axis_primitive_batchers[pdot_p] = _pdot_vmap_collective_rule def _pdot_vmap_batching_rule(vals_in, dims_in, *, axis_name, pos_contract, pos_batch, precision):
64
64
118
28
35
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_vmap_batching_rule
_pdot_vmap_batching_rule
1,431
1,438
1,431
1,432
9069c786eec3a51b63cb2247d94fb9c66940e442
bigcode/the-stack
train
6651e25cd085d4d45f42533b
train
function
def _reduce_scatter_abstract_eval(x, *, axis_name, scatter_dimension, axis_index_groups, axis_size, tiled): if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) x_aval = core.raise_to_shaped(x) new_shape = list(x_aval.shape) scatter_dim_input_size = x_aval....
def _reduce_scatter_abstract_eval(x, *, axis_name, scatter_dimension, axis_index_groups, axis_size, tiled):
if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) x_aval = core.raise_to_shaped(x) new_shape = list(x_aval.shape) scatter_dim_input_size = x_aval.shape[scatter_dimension] if tiled: if scatter_dim_input_size % axis_size != 0: raise ValueError(f"tiled reduce_scatter operand sca...
avals_in, avals_out, x, reducer=reducer, scatter_dimension=scatter_dimension, axis_name=axis_name, axis_index_groups=axis_index_groups, axis_size=axis_size, tiled=tiled) def _reduce_scatter_abstract_eval(x, *, axis_name, scatter_dimension, ...
77
77
259
27
50
rsepassi/jax
jax/_src/lax/parallel.py
Python
_reduce_scatter_abstract_eval
_reduce_scatter_abstract_eval
1,222
1,247
1,222
1,223
b7a87f8cce68455afdc5557fc017ed7fa455212f
bigcode/the-stack
train
4a40dc9e4f413f7ceb51c4ec
train
function
def xeinsum(spec: str, x, y): in_spec, out_spec = spec.split('->') (lhs_subs, lhs_named), (rhs_subs, rhs_named) = XeinsumSpecParser(in_spec).parse_args() (out_subs, out_named), = XeinsumSpecParser(out_spec).parse_args() all_named = {*lhs_named, *rhs_named, *out_named} all_subs = {*lhs_subs, *rhs_subs, *out_su...
def xeinsum(spec: str, x, y):
in_spec, out_spec = spec.split('->') (lhs_subs, lhs_named), (rhs_subs, rhs_named) = XeinsumSpecParser(in_spec).parse_args() (out_subs, out_named), = XeinsumSpecParser(out_spec).parse_args() all_named = {*lhs_named, *rhs_named, *out_named} all_subs = {*lhs_subs, *rhs_subs, *out_subs} lhs_uniques = set(lhs_su...
2] [3 3]] >>> print(y) [[0 1] [0 1] [0 1] [0 1]] """ return axis_index_p.bind(axis_name=axis_name) def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ()), precision=None): if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) return pdot_p.bind(x, y, axis...
150
150
500
12
138
rsepassi/jax
jax/_src/lax/parallel.py
Python
xeinsum
xeinsum
408
451
408
408
fcc04ef3d000f1a7f00a242a0bba1e67f2e3ff6f
bigcode/the-stack
train
6d1f70c0524920b000bcd75a
train
function
def _subst_all_names_in_param( pname: str, params: core.ParamDict, subst: core.AxisSubst, traverse: bool) -> core.ParamDict: axis_name = params[pname] if not isinstance(axis_name, (tuple, list)): axis_name = (axis_name,) result = dict(params) result[pname] = sum(((name,) if isinstance(name, int) else su...
def _subst_all_names_in_param( pname: str, params: core.ParamDict, subst: core.AxisSubst, traverse: bool) -> core.ParamDict:
axis_name = params[pname] if not isinstance(axis_name, (tuple, list)): axis_name = (axis_name,) result = dict(params) result[pname] = sum(((name,) if isinstance(name, int) else subst(name) for name in axis_name), ()) return result
# TODO: Canonicalize exes! return pgather_p.bind(src, idx, axes=tuple(axes)) ### parallel primitives def _subst_all_names_in_param( pname: str, params: core.ParamDict, subst: core.AxisSubst, traverse: bool) -> core.ParamDict:
64
64
102
35
28
rsepassi/jax
jax/_src/lax/parallel.py
Python
_subst_all_names_in_param
_subst_all_names_in_param
545
554
545
546
6861429c9f296eb0bfd0a61847782dfa26cd29c9
bigcode/the-stack
train
219e7419e095b4e76021e7ab
train
function
def _batched_reduction_collective( prim, if_unmapped, axis_size, frame_name, _, vals_in, dims_in, axes, axis_index_groups): assert prim.multiple_results assert frame_name in axes # Note that we have a choice here. We can either unfuse the reduction into one # that handles the batched dims and then anoth...
def _batched_reduction_collective( prim, if_unmapped, axis_size, frame_name, _, vals_in, dims_in, axes, axis_index_groups):
assert prim.multiple_results assert frame_name in axes # Note that we have a choice here. We can either unfuse the reduction into one # that handles the batched dims and then another one that handles the rest. # Alternatively, we can keep the dimension reduction fused with the rest, but # we have to split t...
d_vals_in)) # _reduction_with_positional_batcher moves all map dims to 0 return vals_out, [d if d is batching.not_mapped else 0 for d in dims_in] def _batched_reduction_collective( prim, if_unmapped, axis_size, frame_name, _, vals_in, dims_in, axes, axis_index_groups):
82
82
275
36
46
rsepassi/jax
jax/_src/lax/parallel.py
Python
_batched_reduction_collective
_batched_reduction_collective
595
615
595
597
87894b801f0b4898903d9d99f3bf344872c7728a
bigcode/the-stack
train
265d52fd8d297753b92072e3
train
function
def _allreduce_impl(pos_reducer, *args, axes, axis_index_groups): assert axis_index_groups is None assert all(isinstance(axis, int) for axis in axes) return [pos_reducer(arg, axes) for arg in args]
def _allreduce_impl(pos_reducer, *args, axes, axis_index_groups):
assert axis_index_groups is None assert all(isinstance(axis, int) for axis in axes) return [pos_reducer(arg, axes) for arg in args]
axis_index_groups is not None: replica_groups = [[axis_group[i] for i in axis_index_group] for axis_group in replica_groups for axis_index_group in axis_index_groups] return replica_groups def _allreduce_impl(pos_reducer, *args, axes, axis_index_groups):
64
64
55
18
45
rsepassi/jax
jax/_src/lax/parallel.py
Python
_allreduce_impl
_allreduce_impl
625
628
625
625
02e3b290567eff219ae485db335cacbdb19a61c6
bigcode/the-stack
train
8d069bdd1100e8bf2bd669a7
train
function
def _reduction_with_positional_batcher(prim, vals_in, dims_in, axis_index_groups, transform_unmapped, transform_mapped): if axis_index_groups is not None: raise NotImplementedError("axis_index_groups not supported in vmap collectives. " "Please open a feature request!") vals_in...
def _reduction_with_positional_batcher(prim, vals_in, dims_in, axis_index_groups, transform_unmapped, transform_mapped):
if axis_index_groups is not None: raise NotImplementedError("axis_index_groups not supported in vmap collectives. " "Please open a feature request!") vals_in = [val if d is batching.not_mapped or d == 0 else _moveaxis(d, 0, val) for val, d in zip(vals_in, dims_in)] m...
, traverse: bool) -> core.ParamDict: axis_name = params[pname] if not isinstance(axis_name, (tuple, list)): axis_name = (axis_name,) result = dict(params) result[pname] = sum(((name,) if isinstance(name, int) else subst(name) for name in axis_name), ()) return ...
108
108
361
31
76
rsepassi/jax
jax/_src/lax/parallel.py
Python
_reduction_with_positional_batcher
_reduction_with_positional_batcher
556
580
556
557
78742d58b3d519aeca690720e1ca9404575cce78
bigcode/the-stack
train
3928af3c2b26a2df299ff052
train
function
def axis_index(axis_name): """Return the index along the mapped axis ``axis_name``. Args: axis_name: hashable Python object used to name the mapped axis. Returns: An integer representing the index. For example, with 8 XLA devices available: >>> from functools import partial >>> @partial(jax.pmap...
def axis_index(axis_name):
"""Return the index along the mapped axis ``axis_name``. Args: axis_name: hashable Python object used to name the mapped axis. Returns: An integer representing the index. For example, with 8 XLA devices available: >>> from functools import partial >>> @partial(jax.pmap, axis_name='i') ... def ...
# we have a new axis before split_axis now result = all_to_all_p.bind(x, split_axis=split_axis, concat_axis=concat_axis, axis_name=axis_name, axis_index_groups=axis_index_groups) if not tiled and split_axis != concat_axis: result = lax.squee...
92
92
307
6
86
rsepassi/jax
jax/_src/lax/parallel.py
Python
axis_index
axis_index
359
396
359
359
7878fa01ec56d87e77aac91160268cda248d3c77
bigcode/the-stack
train
bf7b3ccc854ccfd2271d6b93
train
function
def _vmap_process_axis_index(self, frame): assert frame.size is not None return batching.BatchTracer(self, lax.iota(np.int32, frame.size), 0)
def _vmap_process_axis_index(self, frame):
assert frame.size is not None return batching.BatchTracer(self, lax.iota(np.int32, frame.size), 0)
1 index = 0 for name in reversed(axis_name): index += name_idx(name) * inner_size inner_size *= psum(1, name) return index axis_index_p.def_custom_bind(_axis_index_bind) def _vmap_process_axis_index(self, frame):
64
64
39
11
53
rsepassi/jax
jax/_src/lax/parallel.py
Python
_vmap_process_axis_index
_vmap_process_axis_index
1,386
1,388
1,386
1,386
ab0548f15052909f4fd49b4e1aff28b3741f65f5
bigcode/the-stack
train
49bc494aa0c6f1d2fdd612e1
train
function
def all_to_all(x, axis_name, split_axis, concat_axis, *, axis_index_groups=None, tiled=False): """Materialize the mapped axis and map a different axis. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. In the output, the input mapped axis ``axis_name`` is ma...
def all_to_all(x, axis_name, split_axis, concat_axis, *, axis_index_groups=None, tiled=False):
"""Materialize the mapped axis and map a different axis. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. In the output, the input mapped axis ``axis_name`` is materialized at the logical axis position ``concat_axis``, and the input unmapped axis at posit...
apped axis of the input is placed at the position ``axis`` in the output. That is, it is equivalent to ``all_to_all(x, axis_name, axis, axis)``. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the :func:`jax.pmap` document...
256
256
873
24
232
rsepassi/jax
jax/_src/lax/parallel.py
Python
all_to_all
all_to_all
288
357
288
288
dc228719b93815551ab399400ad522374508d272
bigcode/the-stack
train
376d55d08976b60c80831fee
train
function
def _moveaxis(src, dst, x): perm = [i for i in range(x.ndim) if i != src] perm.insert(dst, src) return lax.transpose(x, perm)
def _moveaxis(src, dst, x):
perm = [i for i in range(x.ndim) if i != src] perm.insert(dst, src) return lax.transpose(x, perm)
(_collective_batcher, ppermute_p) batching.axis_primitive_batchers[ppermute_p] = _ppermute_batcher core.axis_substitution_rules[ppermute_p] = partial(_subst_all_names_in_param, 'axis_name') def _moveaxis(src, dst, x):
64
64
43
10
54
rsepassi/jax
jax/_src/lax/parallel.py
Python
_moveaxis
_moveaxis
816
819
816
816
c82aa31f5b3b593a08dcee9930dfaabf4760dd58
bigcode/the-stack
train
16d899693776763bab9c539c
train
function
def _collective_batcher(prim, args, dims, **params): return prim.bind(*args, **params), dims if prim.multiple_results else dims[0]
def _collective_batcher(prim, args, dims, **params):
return prim.bind(*args, **params), dims if prim.multiple_results else dims[0]
batching.not_mapped perm_indices = np.zeros(axis_size, dtype=int) for src, dst in perm: perm_indices[dst] = src return lax_numpy.take(v, perm_indices, d), d def _collective_batcher(prim, args, dims, **params):
64
64
37
16
47
rsepassi/jax
jax/_src/lax/parallel.py
Python
_collective_batcher
_collective_batcher
802
803
802
802
720a620087e7090779df5a2971863a673a71fbd6
bigcode/the-stack
train
5a8f8eb959a330d18b07ae6a
train
function
def _reduction_batcher(prim, vals_in, dims_in, *, axes, axis_index_groups): assert prim.multiple_results if not any(isinstance(axis, int) for axis in axes): return prim.bind(*vals_in, axes=axes, axis_index_groups=axis_index_groups), dims_in vals_out = _reduction_with_positional_batcher( prim, vals_in, d...
def _reduction_batcher(prim, vals_in, dims_in, *, axes, axis_index_groups):
assert prim.multiple_results if not any(isinstance(axis, int) for axis in axes): return prim.bind(*vals_in, axes=axes, axis_index_groups=axis_index_groups), dims_in vals_out = _reduction_with_positional_batcher( prim, vals_in, dims_in, axis_index_groups, lambda d, d_vals_in: (axes, d_vals_in), ...
=None) for i, val in zip(mapped_idxs, mapped_vals_out): vals_out[i] = val assert all(v is not None for v in vals_out) return vals_out def _reduction_batcher(prim, vals_in, dims_in, *, axes, axis_index_groups):
64
64
186
22
41
rsepassi/jax
jax/_src/lax/parallel.py
Python
_reduction_batcher
_reduction_batcher
582
593
582
582
1d645d770788986b6c3d2646c47b3fd260ca15f0
bigcode/the-stack
train
b6b161e4c85205841456fc56
train
function
def pmin(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce min on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hasha...
def pmin(x, axis_name, *, axis_index_groups=None):
"""Compute an all-reduce min on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see ...
) and axis_index_groups is not None: raise ValueError("axis_index_groups only supported for sums over just named axes") _validate_reduce_axis_index_groups(axis_index_groups) leaves, treedef = tree_util.tree_flatten(x) out_flat = pmax_p.bind(*leaves, axes=axis_name, axis_index_groups=a...
104
104
349
14
90
rsepassi/jax
jax/_src/lax/parallel.py
Python
pmin
pmin
152
179
152
152
f370e4f5550cc522828a35fa4d01eb3be84d15f6
bigcode/the-stack
train
3a095978f3bb65701f9b76a5
train
function
def _pgather_batcher(vals_in, dims_in, *, axes): src, idx = vals_in dsrc, didx = dims_in if didx is not batching.not_mapped and dsrc is not batching.not_mapped: # NB: We could just go forward with it and take the diagonal along the # two axes we get in the output, but that would be quite inefficient ...
def _pgather_batcher(vals_in, dims_in, *, axes):
src, idx = vals_in dsrc, didx = dims_in if didx is not batching.not_mapped and dsrc is not batching.not_mapped: # NB: We could just go forward with it and take the diagonal along the # two axes we get in the output, but that would be quite inefficient raise NotImplementedError("Please open a featu...
D lowering." "Please open a feature request!") return xla.lower_fun(_pgather_impl, multiple_results=False, new_style=True)( ctx, avals_in, avals_out, src, idx, axes=axes) def _pgather_batcher(vals_in, dims_in, *, axes):
64
64
199
15
49
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pgather_batcher
_pgather_batcher
1,498
1,512
1,498
1,498
782cd2c5401c457ba885d4802265c472f248a538
bigcode/the-stack
train