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
8b8222eeebaa09f17692305d
train
function
def test_API_doc(): """Should work as expected.""" app = proxy.API(name="test") @app.route("/test", methods=["POST"]) def _post(body: str) -> Tuple[str, str, str]: """Return something.""" return ("OK", "text/plain", "Yo") @app.route("/<user>", methods=["GET"], tag=["users"], descri...
def test_API_doc():
"""Should work as expected.""" app = proxy.API(name="test") @app.route("/test", methods=["POST"]) def _post(body: str) -> Tuple[str, str, str]: """Return something.""" return ("OK", "text/plain", "Yo") @app.route("/<user>", methods=["GET"], tag=["users"], description="a route") ...
", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", } res = app(event, {}) body = json.loads(res["body"]) assert res["statusCode"] == 200 assert res["headers"] == headers assert body["user"] == "remotepixel" assert not body.get("num") assert not bo...
224
224
748
5
219
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_doc
test_API_doc
1,094
1,192
1,094
1,094
c32b95b8d61873a79cb7045cce93295810660b93
bigcode/the-stack
train
acbe3326eab1239d20bd1d36
train
function
def test_API_routeToken(monkeypatch): """Validate tokens.""" monkeypatch.setenv("TOKEN", "yo") app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True, token=True) event = { ...
def test_API_routeToken(monkeypatch):
"""Validate tokens.""" monkeypatch.setenv("TOKEN", "yo") app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True, token=True) event = { "path": "/test/remotepixel", ...
1/-1.0.jpeg", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "...
204
204
681
9
195
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_routeToken
test_API_routeToken
798
892
798
798
d8e7f93d5e4fe132b6955afd4c611e544637e8a2
bigcode/the-stack
train
6926fb9c8fa11fd73d5c0337
train
function
def test_API_compression(): """Test compression and base64.""" body = b"thisisafakeencodedjpeg" gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) gzbody = gzip_compress.compress(body) + gzip_compress.flush() b64gzipbody = base64.b64encode(gzbody).decode() app = proxy.API(n...
def test_API_compression():
"""Test compression and base64.""" body = b"thisisafakeencodedjpeg" gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) gzbody = gzip_compress.compress(body) + gzip_compress.flush() b64gzipbody = base64.b64encode(gzbody).decode() app = proxy.API(name="test") funct = Mock...
": {}, } resp = { "body": body, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "image/jpeg", }, "statusCode": 200, } res = ...
256
256
1,094
6
249
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_compression
test_API_compression
466
611
466
466
c161d3e6fcb1be3ce349c4730c2859cf1ac78fac
bigcode/the-stack
train
14d5390dbafc4be892e7a3ae
train
function
def test_API_addRoute(): """Add and parse route.""" app = proxy.API(name="test") assert len(list(app.routes.keys())) == 3 app._add_route("/endpoint/test/<id>", funct, methods=["GET"], cors=True, token="yo") assert app.routes with pytest.raises(ValueError): app._add_route("/endpoint/tes...
def test_API_addRoute():
"""Add and parse route.""" app = proxy.API(name="test") assert len(list(app.routes.keys())) == 3 app._add_route("/endpoint/test/<id>", funct, methods=["GET"], cors=True, token="yo") assert app.routes with pytest.raises(ValueError): app._add_route("/endpoint/test/<id>", funct, methods=[...
_logDebug(): """Should work as expected.""" app = proxy.API(name="test", debug=True) assert app.log.getEffectiveLevel() == 10 # DEBUG # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h) def test_API_addRoute():
64
64
138
6
58
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_addRoute
test_API_addRoute
156
172
156
156
77e99e09fbc4823b7978b75862a30367bc5e67f7
bigcode/the-stack
train
6a95dec4cb49f3620802ff25
train
function
def test_proxy_API(): """Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) event = { "path": "/test/remote/pixel", "httpMetho...
def test_proxy_API():
"""Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) event = { "path": "/test/remote/pixel", "httpMethod": "GET", "he...
id>", funct, methods=["GET"], cors=True) with pytest.raises(TypeError): app._add_route("/endpoint/test/<id>", funct, methods=["GET"], c=True) # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h) def test_proxy_API():
64
64
198
5
59
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_proxy_API
test_proxy_API
175
199
175
175
cf4cc90ef5da89270d69c9d78b0473ea61d8464b
bigcode/the-stack
train
028de373f9be8b9781fd1ad3
train
function
def test_routeRegexFailing(): """Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "yooooo")) app._add_route( r"/test/<regex(user(\d+)?):user>/<sport>", funct, methods=["GET"], cors=True ) event = { "path": "/test...
def test_routeRegexFailing():
"""Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "yooooo")) app._add_route( r"/test/<regex(user(\d+)?):user>/<sport>", funct, methods=["GET"], cors=True ) event = { "path": "/test/user1234/rugby", "htt...
statusCode": 200, } res = app(event, {}) assert res == resp funct_two.assert_called_with(number="1234", name="pix") # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h) def test_routeRegexFailing():
64
64
157
7
57
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_routeRegexFailing
test_routeRegexFailing
1,409
1,428
1,409
1,409
c1652d48142b3c2ab67ca8c56adeb71fc3ebe3b8
bigcode/the-stack
train
e5f9b94cd4e801ada57f2200
train
function
def test_API_ctx(): """Should work as expected and pass ctx and evt to the function.""" app = proxy.API(name="test") @app.route("/<id>", methods=["GET"], cors=True) @app.pass_event @app.pass_context def print_id(ctx, evt, id, params=None): return ( "OK", "applica...
def test_API_ctx():
"""Should work as expected and pass ctx and evt to the function.""" app = proxy.API(name="test") @app.route("/<id>", methods=["GET"], cors=True) @app.pass_event @app.pass_context def print_id(ctx, evt, id, params=None): return ( "OK", "application/json", ...
-Allow-Methods": "GET,POST", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="remotepixel") # Clear logger handlers for h in app.log.handlers: ...
90
90
300
5
85
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_ctx
test_API_ctx
999
1,037
999
999
a8e3f3e65a193d7cb3175985627e97b9aab7d22e
bigcode/the-stack
train
1cd50f1a80339b78320d09fb
train
function
def test_proxy_APIpathProxy(): """Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) event = { "resource": "{something+}", "pa...
def test_proxy_APIpathProxy():
"""Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) event = { "resource": "{something+}", "pathParameters": {"something": "t...
"GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="remote", name="pixel") def test_proxy_APIpathProxy():
66
66
223
7
59
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_proxy_APIpathProxy
test_proxy_APIpathProxy
256
282
256
256
32c4cc147286b2bbc40c73cd52789d97690a9734
bigcode/the-stack
train
fd5b2d9ecb1d885fad17bedf
train
function
def test_value_converters(): """Convert convert value to correct type.""" pathArg = "<string:v>" assert "123" == proxy._converters("123", pathArg) pathArg = "<int:v>" assert 123 == proxy._converters("123", pathArg) pathArg = "<float:v>" assert 123.0 == proxy._converters("123", pathArg) ...
def test_value_converters():
"""Convert convert value to correct type.""" pathArg = "<string:v>" assert "123" == proxy._converters("123", pathArg) pathArg = "<int:v>" assert 123 == proxy._converters("123", pathArg) pathArg = "<float:v>" assert 123.0 == proxy._converters("123", pathArg) pathArg = "<uuid:v>" as...
w = os.path.join(os.path.dirname(__file__), "fixtures", "openapi_apigw.json") with open(json_apigw, "r") as f: openapi_apigw_content = json.loads(f.read()) funct = Mock(__name__="Mock") def test_value_converters():
64
64
186
6
58
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_value_converters
test_value_converters
32
49
32
32
30603fdc9fb913d6a2c4ff732e366e4db1fc0f42
bigcode/the-stack
train
49e7e5edd7bbb01146e5d49b
train
function
def test_routeRegex(): """Add and parse route.""" app = proxy.API(name="test") funct_one = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) funct_two = Mock(__name__="Mock", return_value=("OK", "text/plain", "yooooo")) app._add_route( "/test/<regex([0-9]{4}):number>/<regex(...
def test_routeRegex():
"""Add and parse route.""" app = proxy.API(name="test") funct_one = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) funct_two = Mock(__name__="Mock", return_value=("OK", "text/plain", "yooooo")) app._add_route( "/test/<regex([0-9]{4}):number>/<regex([a-z]{3}):name>", ...
", "headers": {}, "queryStringParameters": {}, } headers = { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", } res = app(event, {}) body = json....
132
132
443
5
127
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_routeRegex
test_routeRegex
1,350
1,406
1,350
1,350
4d68bd40033710bf24ba9f48e509cc7af7889de0
bigcode/the-stack
train
cbce854e3a3a89c2e836d535
train
function
def test_API_logDebug(): """Should work as expected.""" app = proxy.API(name="test", debug=True) assert app.log.getEffectiveLevel() == 10 # DEBUG # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_logDebug():
"""Should work as expected.""" app = proxy.API(name="test", debug=True) assert app.log.getEffectiveLevel() == 10 # DEBUG # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
Should work as expected.""" app = proxy.API(name="test", configure_logs=False) assert app.name == "test" assert not app.debug assert app.log # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h) def test_API_logDebug():
64
64
61
6
58
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_logDebug
test_API_logDebug
146
153
146
146
f5b0bf92ef0893d4325d3ca235e2ee07ec0e6b11
bigcode/the-stack
train
60e428af068af22e95fd15c0
train
function
def test_API_noDocs(): """Do not set default documentation routes.""" app = proxy.API(name="test", add_docs=False) assert app.name == "test" assert len(list(app.routes.keys())) == 0 assert not app.debug assert app.log.getEffectiveLevel() == 40 # ERROR # Clear logger handlers for h in a...
def test_API_noDocs():
"""Do not set default documentation routes.""" app = proxy.API(name="test", add_docs=False) assert app.name == "test" assert len(list(app.routes.keys())) == 0 assert not app.debug assert app.log.getEffectiveLevel() == 40 # ERROR # Clear logger handlers for h in app.log.handlers: ...
== "test" assert len(list(app.routes.keys())) == 3 assert not app.debug assert app.log.getEffectiveLevel() == 40 # ERROR # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h) def test_API_noDocs():
64
64
90
6
58
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_noDocs
test_API_noDocs
121
131
121
121
40d28a89fe83976757f80c577b7be607e050d169
bigcode/the-stack
train
983ec4618e47ab80f6680ec7
train
function
def test_API_init(): """Should work as expected.""" app = proxy.API(name="test") assert app.name == "test" assert len(list(app.routes.keys())) == 3 assert not app.debug assert app.log.getEffectiveLevel() == 40 # ERROR # Clear logger handlers for h in app.log.handlers: app.log.r...
def test_API_init():
"""Should work as expected.""" app = proxy.API(name="test") assert app.name == "test" assert len(list(app.routes.keys())) == 3 assert not app.debug assert app.log.getEffectiveLevel() == 40 # ERROR # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
assert route.b64encode def test_RouteEntry_invalidCompression(): """Should work as expected.""" with pytest.raises(ValueError): proxy.RouteEntry( funct, "my-function", "/endpoint/test/<id>", payload_compression_method="nope", ) def test_API_init...
64
64
83
5
59
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_init
test_API_init
108
118
108
108
b04fd0455351f9c07289dae3da2cfe678a25d33e
bigcode/the-stack
train
38211a0b14523b40e0ca04ac
train
function
def test_API_routeURL(): """Should catch invalid route and parse valid args.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "route": "/users/remotepixel", ...
def test_API_routeURL():
"""Should catch invalid route and parse valid args.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "route": "/users/remotepixel", "httpMethod": "GE...
"queryStringParameters": {}, } resp = { "body": zlibbody, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Encoding": "zlib", "Content-Type": "...
253
253
846
6
246
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_routeURL
test_API_routeURL
683
795
683
683
a49d9db517b97af3df60611bc4551fc103c30a34
bigcode/the-stack
train
0c6ec4d0f3d90652fbe53ed0
train
function
def test_API_doc_apigw(): """Should work as expected if request from api-gateway.""" app = proxy.API(name="test") @app.route("/test", methods=["POST"]) def _post(body: str) -> Tuple[str, str, str]: """Return something.""" return ("OK", "text/plain", "Yo") @app.route("/<user>", meth...
def test_API_doc_apigw():
"""Should work as expected if request from api-gateway.""" app = proxy.API(name="test") @app.route("/test", methods=["POST"]) def _post(body: str) -> Tuple[str, str, str]: """Return something.""" return ("OK", "text/plain", "Yo") @app.route("/<user>", methods=["GET"], tag=["users"]...
} headers = { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/html", } res = app(event, {}) assert res["statusCode"] == 200 assert res["headers"] == headers event = ...
211
211
705
8
203
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_doc_apigw
test_API_doc_apigw
1,195
1,278
1,195
1,195
58ec2d732d9c0117e0b92e749501adb10bc01932
bigcode/the-stack
train
a4e457db2a37d5770e696422
train
function
def test_API_Post(): """Should work as expected on POST request.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET", "POST"], cors=True) event = { "path": "/test/remotepixel", ...
def test_API_Post():
"""Should work as expected on POST request.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET", "POST"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "POST...
>", funct, methods=["GET"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "hey something went wrong"}', "headers": { "Access-Control-Allow-Cr...
162
162
540
5
157
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_Post
test_API_Post
925
996
925
925
b52cd673863cd92a81984be1f11be22204f75f0f
bigcode/the-stack
train
7eba69657ac1beaf36fa2e6f
train
function
def test_path_to_regex_convert(): """Convert route path to regex.""" path = "/jqtrde/<a>/<string:path>/<int:num>/<float:fl>/<uuid:id>/<regex([A-Z0-9]{5}):var>/<regex([a-z]{1}):othervar>" assert ( "^/jqtrde/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)/([0-9]+)/([+-]?[0-9]+.[0-9]+)/([0-9a-f]{8}-[0-9a-f]{4}-[0-...
def test_path_to_regex_convert():
"""Convert route path to regex.""" path = "/jqtrde/<a>/<string:path>/<int:num>/<float:fl>/<uuid:id>/<regex([A-Z0-9]{5}):var>/<regex([a-z]{1}):othervar>" assert ( "^/jqtrde/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)/([0-9]+)/([+-]?[0-9]+.[0-9]+)/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})...
( "f5c21e12-8317-11e9-bf96-2e2ca3acb545", pathArg ) pathArg = "<v>" assert "123" == proxy._converters("123", pathArg) def test_path_to_regex_convert():
64
64
186
7
57
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_path_to_regex_convert
test_path_to_regex_convert
52
58
52
52
21ee8f829bb474e752367b49c90f9ac0f8b158aa
bigcode/the-stack
train
866d06ba1d1748eb38166b9e
train
function
def test_RouteEntry_default(): """Should work as expected.""" route = proxy.RouteEntry(funct, "/endpoint/test/<id>") assert route.endpoint == funct assert route.methods == ["GET"] assert not route.cors assert not route.token assert not route.compression assert not route.b64encode
def test_RouteEntry_default():
"""Should work as expected.""" route = proxy.RouteEntry(funct, "/endpoint/test/<id>") assert route.endpoint == funct assert route.methods == ["GET"] assert not route.cors assert not route.token assert not route.compression assert not route.b64encode
_to_openapi_converters(): """Convert proxy path to openapi path.""" path = "/<string:num>/<test>-<regex([0-1]{4}):var>" assert "/{num}/{test}-{var}" == proxy._path_to_openapi(path) def test_RouteEntry_default():
64
64
72
7
57
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_RouteEntry_default
test_RouteEntry_default
67
75
67
67
694a208b56362b4761ca08837c42229bb1d0cacd
bigcode/the-stack
train
e181d50429658993d8ae7e67
train
function
def test_API_multipleRoute(): """Should work as expected.""" app = proxy.API(name="test") @app.route("/<user>", methods=["GET"], cors=True) @app.route("/<user>@<int:num>", methods=["GET"], cors=True) def print_id(user, num=None, params=None): return ( "OK", "applicat...
def test_API_multipleRoute():
"""Should work as expected.""" app = proxy.API(name="test") @app.route("/<user>", methods=["GET"], cors=True) @app.route("/<user>@<int:num>", methods=["GET"], cors=True) def print_id(user, num=None, params=None): return ( "OK", "application/json", json.du...
res = app(event, {"ctx": "jqtrde"}) body = res["body"] assert res["headers"] == headers assert res["statusCode"] == 200 assert body["id"] == "remotepixel" assert body["params"] == "1" assert body["evt"] == event assert body["ctx"] == {"ctx": "jqtrde"} # Clear logger handlers for h ...
114
114
380
6
108
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_multipleRoute
test_API_multipleRoute
1,040
1,091
1,040
1,040
2ecb642b812b374d2f784487580c81302c020e2a
bigcode/the-stack
train
02bfca79d480594df4244eb9
train
function
def test_querystringNull(): """Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "GET"...
def test_querystringNull():
"""Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, ...
name="pixel") event = { "path": "/yo", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } res = app(event, {}) assert res["headers"]["Cache-Control"] == "no-cache" def test_querystringNull():
64
64
196
6
58
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_querystringNull
test_querystringNull
355
379
355
355
4da340075eddb8ea7dd2782482af095d2d65d87b
bigcode/the-stack
train
440dc10359e17e200d471782
train
function
def test_API_encoding(): """Test b64 encoding.""" app = proxy.API(name="test") body = b"thisisafakeencodedjpeg" b64body = base64.b64encode(body).decode() funct = Mock(__name__="Mock", return_value=("OK", "image/jpeg", body)) app._add_route("/test/<user>.jpg", funct, methods=["GET"], cors=True)...
def test_API_encoding():
"""Test b64 encoding.""" app = proxy.API(name="test") body = b"thisisafakeencodedjpeg" b64body = base64.b64encode(body).decode() funct = Mock(__name__="Mock", return_value=("OK", "image/jpeg", body)) app._add_route("/test/<user>.jpg", funct, methods=["GET"], cors=True) event = { "...
": None, "queryStringParameters": {}, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, ...
111
111
373
5
106
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_API_encoding
test_API_encoding
409
463
409
409
0f2b1c1d05116bab5af5f27912661080b076bbf5
bigcode/the-stack
train
525318cef6c5a99df46e3387
train
function
def testApigwPath(): """test api call parsing.""" # resource "/", no apigwg, noproxy, no path mapping event = {"path": "/test/1234/pix", "headers": {}} p = proxy.ApigwPath(event) assert p.path == "/test/1234/pix" assert not p.apigw_stage assert not p.api_prefix assert not p.path_mapping ...
def testApigwPath():
"""test api call parsing.""" # resource "/", no apigwg, noproxy, no path mapping event = {"path": "/test/1234/pix", "headers": {}} p = proxy.ApigwPath(event) assert p.path == "/test/1234/pix" assert not p.apigw_stage assert not p.api_prefix assert not p.path_mapping assert p.prefix =...
= app(event, {}) assert res == resp funct_two.assert_called_with(number="1234", name="pix") # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h) def test_routeRegexFailing(): """Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Moc...
211
211
706
7
204
dmmop/lambda-proxy
tests/test_proxy.py
Python
testApigwPath
testApigwPath
1,431
1,505
1,431
1,431
e9114ef34d5a53be40c6b842225d898ec526f118
bigcode/the-stack
train
250e640ba0390d951326fcca
train
function
def testApigwHostUrl(): """Test url property.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) # resource "/", no apigwg, noproxy, no path mapping event = { ...
def testApigwHostUrl():
"""Test url property.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) # resource "/", no apigwg, noproxy, no path mapping event = { "path": "/test/1...
" assert not p.apigw_stage assert p.api_prefix == "/api" assert p.path_mapping == "/prefix" assert p.prefix == "/prefix/api" # resource "proxy+", apigwg (production), api prefix (api) event = { "resource": "/api/{proxy+}", "pathParameters": {"proxy": "test/1234/pix"}, "p...
198
198
662
8
190
dmmop/lambda-proxy
tests/test_proxy.py
Python
testApigwHostUrl
testApigwHostUrl
1,508
1,582
1,508
1,508
991e9003773b49be5e16d45bc50011befdc48ac8
bigcode/the-stack
train
31ef7357239128442025c475
train
function
def test_RouteEntry_Options(): """Should work as expected.""" route = proxy.RouteEntry( funct, "/endpoint/test/<id>", ["POST"], cors=True, token="Yo", payload_compression_method="deflate", binary_b64encode=True, ) assert route.endpoint == funct ...
def test_RouteEntry_Options():
"""Should work as expected.""" route = proxy.RouteEntry( funct, "/endpoint/test/<id>", ["POST"], cors=True, token="Yo", payload_compression_method="deflate", binary_b64encode=True, ) assert route.endpoint == funct assert route.methods == ["POST...
= proxy.RouteEntry(funct, "/endpoint/test/<id>") assert route.endpoint == funct assert route.methods == ["GET"] assert not route.cors assert not route.token assert not route.compression assert not route.b64encode def test_RouteEntry_Options():
64
64
109
8
55
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_RouteEntry_Options
test_RouteEntry_Options
78
94
78
78
29025ee0c2bffb1f1d891958d3a206f2171449d6
bigcode/the-stack
train
8c02400b2d0dc8cfe983f690
train
function
def test_proxy_APIpath(): """Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) event = { "resource": "/", "path": "/test/remo...
def test_proxy_APIpath():
"""Add and parse route.""" app = proxy.API(name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True) event = { "resource": "/", "path": "/test/remote/pixel", "httpMe...
": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 204, } res = app(event, {}) assert res == resp def test_proxy_APIpath():
64
64
205
6
57
dmmop/lambda-proxy
tests/test_proxy.py
Python
test_proxy_APIpath
test_proxy_APIpath
228
253
228
228
ac36e76eb15035e9ff8badd09c060bb4b101c4c2
bigcode/the-stack
train
c2251d215d923fd782650f47
train
class
class GlobalMapToActionTriplet(torch.nn.Module): def __init__(self, map_channels, map_size=(30,30), other_features_size=120): super(GlobalMapToActionTriplet, self).__init__() # Rotate the global map to the robot's current frame self.map_affine = Rotation2DRelative() self.grid_sample...
class GlobalMapToActionTriplet(torch.nn.Module):
def __init__(self, map_channels, map_size=(30,30), other_features_size=120): super(GlobalMapToActionTriplet, self).__init__() # Rotate the global map to the robot's current frame self.map_affine = Rotation2DRelative() self.grid_sampler = GridSampler() # Then apply the local...
from deprecated.learning.models.semantic_map.map_affine_old import Rotation2DRelative from learning.models.semantic_map.grid_sampler import GridSampler from learning.modules.map_to_action.ego_map_to_action_triplet import EgoMapToActionTriplet HIDDEN_SIZE = 32 class GlobalMapToActionTriplet(torch.nn.Module):
66
66
223
11
54
esteng/guiding-multi-step
learning/modules/map_to_action/global_map_to_action_triplet.py
Python
GlobalMapToActionTriplet
GlobalMapToActionTriplet
10
33
10
10
a01ed8baa9a3369d20a162233fbbd5ef7b3afea7
bigcode/the-stack
train
072784f6afd2b1242fc25a85
train
function
def run_model_test( self, model, batch_size=2, state_dict=None, input=None, use_gpu=True, rtol=0.001, atol=1e-7, do_constant_folding=True, dynamic_axes=None, test_with_inputs=None, input_names=None, output_names=None, fixed_batch_size=False, dict_check=True, ...
def run_model_test( self, model, batch_size=2, state_dict=None, input=None, use_gpu=True, rtol=0.001, atol=1e-7, do_constant_folding=True, dynamic_axes=None, test_with_inputs=None, input_names=None, output_names=None, fixed_batch_size=False, dict_check=True, ...
if training is not None and training == torch.onnx.TrainingMode.TRAINING: model.train() elif training is None or training == torch.onnx.TrainingMode.EVAL: model.eval() if input is None: input = torch.randn(batch_size, 3, 224, 224, requires_grad=True) with torch.no_grad(): ...
ort_outs, []) def ort_compare_with_pytorch(ort_outs, output, rtol, atol): output, _ = torch.jit._flatten(output) outputs = unpack_to_numpy(output) # compare onnxruntime and PyTorch results assert len(outputs) == len(ort_outs), "number of outputs differ" # compare onnxruntime and PyTorch results ...
232
233
779
108
124
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
run_model_test
run_model_test
189
284
189
209
1eac89b2a7aaf0acf1b65fb9cfd9d2b445ec72ad
bigcode/the-stack
train
b6bb72ecbc8c1331a82cf223
train
function
def setup_rnn_tests(): layers_opts = [(1, "unilayer"), (3, "trilayer")] bidirectional_opts = [(False, "forward"), (True, "bidirectional")] initial_state_opts = [(True, "with_initial_state"), (False, "no_initial_state")] variable_length_opts = [ (0, "without_sequence_lengths"), (1, "with_...
def setup_rnn_tests():
layers_opts = [(1, "unilayer"), (3, "trilayer")] bidirectional_opts = [(False, "forward"), (True, "bidirectional")] initial_state_opts = [(True, "with_initial_state"), (False, "no_initial_state")] variable_length_opts = [ (0, "without_sequence_lengths"), (1, "with_variable_length_sequenc...
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1055384 @skipScriptTest() @skipIfUnsupportedMinOpsetVersion(9) def f(self): self.is_script_test_enabled = ( self.opset_version >= script_test_min_opset_version ) self._dispatch_rnn_test( base, ...
156
156
522
6
150
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
setup_rnn_tests
setup_rnn_tests
12,728
12,793
12,728
12,728
cfec1ff7c38c90314fb3c59757f26235b2f3e0ea
bigcode/the-stack
train
57841181a7db9f1fd11cac17
train
function
def _init_test_rpn(): anchor_sizes = ((32,), (64,), (128,), (256,), (512,)) aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) rpn_anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios) out_channels = 256 rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0...
def _init_test_rpn():
anchor_sizes = ((32,), (64,), (128,), (256,), (512,)) aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) rpn_anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios) out_channels = 256 rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0]) rpn_fg_iou_thre...
_generalized_rcnn_transform(): min_size = 100 max_size = 200 image_mean = [0.485, 0.456, 0.406] image_std = [0.229, 0.224, 0.225] transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std) return transform def _init_test_rpn():
89
89
297
7
81
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
_init_test_rpn
_init_test_rpn
296
323
296
296
183f6fd0d933cf563ba468befc625979238cbbaf
bigcode/the-stack
train
fa7a9ca0932e7c785a2f788b
train
function
def ort_compare_with_pytorch(ort_outs, output, rtol, atol): output, _ = torch.jit._flatten(output) outputs = unpack_to_numpy(output) # compare onnxruntime and PyTorch results assert len(outputs) == len(ort_outs), "number of outputs differ" # compare onnxruntime and PyTorch results [ np...
def ort_compare_with_pytorch(ort_outs, output, rtol, atol):
output, _ = torch.jit._flatten(output) outputs = unpack_to_numpy(output) # compare onnxruntime and PyTorch results assert len(outputs) == len(ort_outs), "number of outputs differ" # compare onnxruntime and PyTorch results [ np.testing.assert_allclose(out, ort_out, rtol=rtol, atol=atol)...
_inputs}" ) ort_inputs[ort_sess_inputs[i].name] = input ort_outs = ort_sess.run(None, ort_inputs) return inline_flatten_list(ort_outs, []) def ort_compare_with_pytorch(ort_outs, output, rtol, atol):
63
64
118
18
45
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
ort_compare_with_pytorch
ort_compare_with_pytorch
175
186
175
175
159e10096667ab5ff0942c89794ddc4a5cea4f5f
bigcode/the-stack
train
c4a0be100a95976774a74f29
train
function
def _init_test_roi_heads_faster_rcnn(): out_channels = 256 num_classes = 91 box_fg_iou_thresh = 0.5 box_bg_iou_thresh = 0.5 box_batch_size_per_image = 512 box_positive_fraction = 0.25 bbox_reg_weights = None box_score_thresh = 0.05 box_nms_thresh = 0.5 box_detections_per_img = 1...
def _init_test_roi_heads_faster_rcnn():
out_channels = 256 num_classes = 91 box_fg_iou_thresh = 0.5 box_bg_iou_thresh = 0.5 box_batch_size_per_image = 512 box_positive_fraction = 0.25 bbox_reg_weights = None box_score_thresh = 0.05 box_nms_thresh = 0.5 box_detections_per_img = 100 box_roi_pool = ops.MultiScaleRoI...
rpn_head, rpn_fg_iou_thresh, rpn_bg_iou_thresh, rpn_batch_size_per_image, rpn_positive_fraction, rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_nms_thresh, score_thresh=rpn_score_thresh, ) return rpn def _init_test_roi_heads_faster_rcnn():
86
86
289
11
74
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
_init_test_roi_heads_faster_rcnn
_init_test_roi_heads_faster_rcnn
326
363
326
326
0c67e63dd7df353cfd7636b553fda48ccd8397bd
bigcode/the-stack
train
b35214edfcafb529a5b714af
train
function
def flatten_tuples(elem): flattened = [] for t in elem: if isinstance(t, tuple): flattened.extend(flatten_tuples(t)) else: flattened.append(t) return flattened
def flatten_tuples(elem):
flattened = [] for t in elem: if isinstance(t, tuple): flattened.extend(flatten_tuples(t)) else: flattened.append(t) return flattened
.onnx import ( CheckerError, register_custom_op_symbolic, unregister_custom_op_symbolic, ) from torch.onnx.symbolic_helper import _unimplemented from torch.onnx.utils import unpack_quantized_tensor _ORT_PROVIDERS = ["CPUExecutionProvider"] def flatten_tuples(elem):
63
64
44
6
57
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
flatten_tuples
flatten_tuples
68
75
68
68
bc158f045281cb4c6afd87fa6c26549d22fd3520
bigcode/the-stack
train
7b338a963685d6ada9ec2665
train
function
def to_numpy(elem): if isinstance(elem, Tensor): if elem.requires_grad: return elem.detach().cpu().numpy() else: return elem.cpu().numpy() elif isinstance(elem, (list, tuple)): return [to_numpy(inp) for inp in elem] elif isinstance(elem, bool): return ...
def to_numpy(elem):
if isinstance(elem, Tensor): if elem.requires_grad: return elem.detach().cpu().numpy() else: return elem.cpu().numpy() elif isinstance(elem, (list, tuple)): return [to_numpy(inp) for inp in elem] elif isinstance(elem, bool): return np.array(elem, dtype...
ized_tensor _ORT_PROVIDERS = ["CPUExecutionProvider"] def flatten_tuples(elem): flattened = [] for t in elem: if isinstance(t, tuple): flattened.extend(flatten_tuples(t)) else: flattened.append(t) return flattened def to_numpy(elem):
64
64
148
5
58
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
to_numpy
to_numpy
78
97
78
78
9c5b0a2805d457823c867030dc1a41f089b1206b
bigcode/the-stack
train
22c760ff56f2789467b05a26
train
function
def run_ort(ort_sess, inputs): kw_inputs = {} if inputs and isinstance(inputs[-1], dict): kw_inputs = inputs[-1] inputs = inputs[:-1] inputs = unpack_to_numpy(flatten_tuples(inputs)) ort_inputs = {} for input_name, input in kw_inputs.items(): ort_inputs[input_name] = to_numpy...
def run_ort(ort_sess, inputs):
kw_inputs = {} if inputs and isinstance(inputs[-1], dict): kw_inputs = inputs[-1] inputs = inputs[:-1] inputs = unpack_to_numpy(flatten_tuples(inputs)) ort_inputs = {} for input_name, input in kw_inputs.items(): ort_inputs[input_name] = to_numpy(input) inputs = to_numpy(i...
_list ) return res_list def unpack_to_numpy(values): value_unpacked = [] for value in values: value_unpacked.extend(unpack_quantized_tensor(value)) return [to_numpy(v) for v in value_unpacked] def run_ort(ort_sess, inputs):
64
64
201
11
53
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
run_ort
run_ort
154
172
154
154
fcb9af08636c801823522d2ed86f94fcf788edd6
bigcode/the-stack
train
45a9bd50db1e209e05c857de
train
function
def _construct_tensor_for_quantization_test( shape: Tuple[int], offset: Optional[Union[int, float]] = None, max_val: Optional[Union[int, float]] = None, ) -> torch.Tensor: """Helper function to generate weights and test inputs in a deterministic way. Due to difference in implementation details betw...
def _construct_tensor_for_quantization_test( shape: Tuple[int], offset: Optional[Union[int, float]] = None, max_val: Optional[Union[int, float]] = None, ) -> torch.Tensor:
"""Helper function to generate weights and test inputs in a deterministic way. Due to difference in implementation details between PyTorch and ONNXRuntime, randomly generated test data for quantization tests can be flaky. To help stablize the test, this helper function is used to generate weights and t...
_positive_fraction, bbox_reg_weights, box_score_thresh, box_nms_thresh, box_detections_per_img, ) return roi_heads def _construct_tensor_for_quantization_test( shape: Tuple[int], offset: Optional[Union[int, float]] = None, max_val: Optional[Union[int, float]] = None, ...
81
81
270
47
33
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
_construct_tensor_for_quantization_test
_construct_tensor_for_quantization_test
366
389
366
370
0c99cf9b1f7fbd08ff6593ad5f01e2bcd578955b
bigcode/the-stack
train
e15e1d8e56cd53faf163969a
train
function
def _init_test_generalized_rcnn_transform(): min_size = 100 max_size = 200 image_mean = [0.485, 0.456, 0.406] image_std = [0.229, 0.224, 0.225] transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std) return transform
def _init_test_generalized_rcnn_transform():
min_size = 100 max_size = 200 image_mean = [0.485, 0.456, 0.406] image_std = [0.229, 0.224, 0.225] transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std) return transform
x if flatten: test_input, _ = torch.jit._flatten(test_input) ort_outs = run_ort(ort_sess, test_input) ort_compare_with_pytorch(ort_outs, output, rtol, atol) def _init_test_generalized_rcnn_transform():
64
64
86
10
54
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
_init_test_generalized_rcnn_transform
_init_test_generalized_rcnn_transform
287
293
287
287
48cc473002b4c7abe2a704a8f3c25d7001c1ce35
bigcode/the-stack
train
c68e55181ce29d1eae784076
train
function
def set_rng_seed(seed): torch.manual_seed(seed) random.seed(seed) np.random.seed(seed)
def set_rng_seed(seed):
torch.manual_seed(seed) random.seed(seed) np.random.seed(seed)
.prod(shape), dtype=torch.float).view(shape) if offset is not None: tensor = tensor + offset if max_val is not None and tensor.abs().max() > max_val: tensor = tensor * max_val / tensor.abs().max() return tensor def set_rng_seed(seed):
64
64
23
6
57
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
set_rng_seed
set_rng_seed
392
395
392
392
6522991e693e17b29570319532fe6adb9be90672
bigcode/the-stack
train
1f0afa9d4781906860f7a5ac
train
function
def make_test( name, base, layer, bidirectional, initial_state, variable_length, dropout, script_test_min_opset_version, **extra_kwargs, ): test_name = str( "_".join( [ "test", name, layer[1], bid...
def make_test( name, base, layer, bidirectional, initial_state, variable_length, dropout, script_test_min_opset_version, **extra_kwargs, ):
test_name = str( "_".join( [ "test", name, layer[1], bidirectional[1], initial_state[1], variable_length[1], dropout[1], ] ) ) # Cannot export with older o...
0.02}) input, grid = torch.randn(n, c, h_in, w_in), torch.randn(n, h_out, w_out, 2) self.run_test( GridSampleModule(mode, padding_mode, align_corners), (input, grid), **atol_rtol, ) def make_test( name, base, layer, bidi...
109
109
366
42
67
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
make_test
make_test
12,675
12,725
12,675
12,685
3459fb2377ba903f9966ab2fb2061ee2d6da2c25
bigcode/the-stack
train
d245547855ac46d252030893
train
function
def inline_flatten_list(inputs, res_list): for i in inputs: res_list.append(i) if not isinstance(i, (list, tuple)) else inline_flatten_list( i, res_list ) return res_list
def inline_flatten_list(inputs, res_list):
for i in inputs: res_list.append(i) if not isinstance(i, (list, tuple)) else inline_flatten_list( i, res_list ) return res_list
3:Error, 4:Fatal. Default is 2. so.log_severity_level = 3 ort_sess = onnxruntime.InferenceSession(f.getvalue(), so, providers=_ORT_PROVIDERS) return ort_sess def inline_flatten_list(inputs, res_list):
64
64
51
10
53
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
inline_flatten_list
inline_flatten_list
139
144
139
139
f339408fe171171528afb3d190d85309775b3654
bigcode/the-stack
train
62545e3240a4a71772709b72
train
function
def unpack_to_numpy(values): value_unpacked = [] for value in values: value_unpacked.extend(unpack_quantized_tensor(value)) return [to_numpy(v) for v in value_unpacked]
def unpack_to_numpy(values):
value_unpacked = [] for value in values: value_unpacked.extend(unpack_quantized_tensor(value)) return [to_numpy(v) for v in value_unpacked]
) return ort_sess def inline_flatten_list(inputs, res_list): for i in inputs: res_list.append(i) if not isinstance(i, (list, tuple)) else inline_flatten_list( i, res_list ) return res_list def unpack_to_numpy(values):
64
64
44
6
57
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
unpack_to_numpy
unpack_to_numpy
147
151
147
147
764dbeaac17ead52c13a5f2262076fcb60da231a
bigcode/the-stack
train
c670c8b9c7ad73d9af9b731f
train
function
def convert_to_onnx( model, input=None, opset_version=9, do_constant_folding=True, keep_initializers_as_inputs=True, dynamic_axes=None, input_names=None, output_names=None, fixed_batch_size=False, training=None, verbose=False, ): f = io.BytesIO() input_copy = copy.dee...
def convert_to_onnx( model, input=None, opset_version=9, do_constant_folding=True, keep_initializers_as_inputs=True, dynamic_axes=None, input_names=None, output_names=None, fixed_batch_size=False, training=None, verbose=False, ):
f = io.BytesIO() input_copy = copy.deepcopy(input) torch.onnx._export( model, input_copy, f, opset_version=opset_version, do_constant_folding=do_constant_folding, keep_initializers_as_inputs=keep_initializers_as_inputs, dynamic_axes=dynamic_axes, ...
[to_numpy(elem[k])] return flattened return elem def convert_to_onnx( model, input=None, opset_version=9, do_constant_folding=True, keep_initializers_as_inputs=True, dynamic_axes=None, input_names=None, output_names=None, fixed_batch_size=False, training=None, ve...
80
80
268
66
13
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
convert_to_onnx
convert_to_onnx
100
136
100
112
fea1cdf2b4be0b65e806980dbb9b34d495b7f2c4
bigcode/the-stack
train
aa6e5308503b4627d3448b2f
train
function
def MakeTestCase(opset_version: int, keep_initializers_as_inputs: bool = True) -> type: name = f"TestONNXRuntime_opset{opset_version}" if not keep_initializers_as_inputs: name += "_IRv4" return type( str(name), (unittest.TestCase,), dict( _TestONNXRuntime.__dict__...
def MakeTestCase(opset_version: int, keep_initializers_as_inputs: bool = True) -> type:
name = f"TestONNXRuntime_opset{opset_version}" if not keep_initializers_as_inputs: name += "_IRv4" return type( str(name), (unittest.TestCase,), dict( _TestONNXRuntime.__dict__, opset_version=opset_version, keep_initializers_as_inputs=keep_...
one accidentally disables all the tests without # noticing if test_count != 192: raise ValueError("Expected 192 tests but found {}".format(test_count)) setup_rnn_tests() def MakeTestCase(opset_version: int, keep_initializers_as_inputs: bool = True) -> type:
64
64
109
23
41
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
MakeTestCase
MakeTestCase
12,799
12,811
12,799
12,799
435e6f5000dbd76e32cab5d9ed0335d0ad6074cc
bigcode/the-stack
train
d481842e04639516f7eea527
train
class
class _TestONNXRuntime: """Abstract base class for test cases. Intentionally not a sub-class of unittest.TestCase so that unittest / pytest don't run it directly. unitest.TestCase is mixed in as another base class when creating concrete sub-types. See MakeTestCase(). """ opset_version = -1 # ...
class _TestONNXRuntime:
"""Abstract base class for test cases. Intentionally not a sub-class of unittest.TestCase so that unittest / pytest don't run it directly. unitest.TestCase is mixed in as another base class when creating concrete sub-types. See MakeTestCase(). """ opset_version = -1 # Sub-classes must overrid...
torch.Tensor: """Helper function to generate weights and test inputs in a deterministic way. Due to difference in implementation details between PyTorch and ONNXRuntime, randomly generated test data for quantization tests can be flaky. To help stablize the test, this helper function is used to generat...
256
256
108,169
7
249
wayi1/pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
Python
_TestONNXRuntime
_TestONNXRuntime
398
12,672
398
398
9a94a1cf4290026d56f9932022b28b1bb0984e00
bigcode/the-stack
train
5f2b347f583f2d1512e9b9ca
train
class
class Chess(object): board = Board() def __unicode__(self): return self.board.__unicode__() def __repr__(self): return self.board.__repr__() def reset(self): self.board.reset() def load(self, fen): self.board.reset(fen) def makemove(self, lan): """ :param lan: (LAN) form of move e.g.: a2a3 """ f...
class Chess(object):
board = Board() def __unicode__(self): return self.board.__unicode__() def __repr__(self): return self.board.__repr__() def reset(self): self.board.reset() def load(self, fen): self.board.reset(fen) def makemove(self, lan): """ :param lan: (LAN) form of move e.g.: a2a3 """ frm, to, promotion = re...
import re from board import Board, KingInCheck, InvalidMove from serialization import to_bit LAN_PATT = r"([a-g]{1}[1-8]{1})-([a-g]{1}[1-8]{1})([nbrq]{1})?" class Chess(object):
63
64
170
4
59
martinogden/chessval
__init__.py
Python
Chess
Chess
12
39
12
13
d96be21e50c0697912084d3b5c2ae9c52da3c577
bigcode/the-stack
train
d9b6bd7e1214cd2bcd3db49b
train
class
class CrossMarketSummaryRecorder(TimeSeriesDataRecorder): entity_provider = 'exchange' entity_schema = Index provider = 'joinquant' data_schema = CrossMarketSummary def __init__(self, batch_size=10, force_update=False, sleeping_time=5, default_size=2000, real_time=False, ...
class CrossMarketSummaryRecorder(TimeSeriesDataRecorder):
entity_provider = 'exchange' entity_schema = Index provider = 'joinquant' data_schema = CrossMarketSummary def __init__(self, batch_size=10, force_update=False, sleeping_time=5, default_size=2000, real_time=False, fix_duplicate_way='add') -> None: # 聚宽编码 ...
from jqdatapy.api import run_query from zvt.contract.recorder import TimeSeriesDataRecorder from zvt.domain import Index, CrossMarketSummary from zvt.utils.time_utils import to_time_str from zvt.utils.utils import multiple_number class CrossMarketSummaryRecorder(TimeSeriesDataRecorder):
62
130
436
10
51
wheelhorse/zvt
zvt/recorders/joinquant/overall/cross_market_recorder.py
Python
CrossMarketSummaryRecorder
CrossMarketSummaryRecorder
9
62
9
9
4d5cbb12c4328b794d30412a46a1e013281aa47f
bigcode/the-stack
train
d6ace96c5df13c1c36474cdb
train
class
class User(AbstractBaseUser, PermissionsMixin): mobile_number = models.CharField(_('mobile number'), max_length=13, unique=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone....
class User(AbstractBaseUser, PermissionsMixin):
mobile_number = models.CharField(_('mobile number'), max_length=13, unique=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD = 'mobile_number' R...
django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.utils.translation import gettext_lazy as _ from django.utils import timezone from django.shortcuts import reverse from .managers import UserManager class User(A...
64
64
121
9
54
swahilipothub/changemaker
app/users/models.py
Python
User
User
24
40
24
24
7c8de9f499fbcb7633cb89c5f16161de8915762f
bigcode/the-stack
train
2a4c4943101097985fd3b8af
train
class
class Profile(models.Model): SUBCOUNTY = [ ('Mvita', 'Mvita'), ('Kisauni', 'Kisauni'), ('Nyali', 'Nyali'), ('Changamwe', 'Changamwe'), ('Jomvu', 'Jomvu'), ('Likoni', 'Likoni') ] GENDER = [ ('Male', 'Male'), ('Female', 'Female') ] use...
class Profile(models.Model):
SUBCOUNTY = [ ('Mvita', 'Mvita'), ('Kisauni', 'Kisauni'), ('Nyali', 'Nyali'), ('Changamwe', 'Changamwe'), ('Jomvu', 'Jomvu'), ('Likoni', 'Likoni') ] GENDER = [ ('Male', 'Male'), ('Female', 'Female') ] user = models.OneToOneField(setti...
django.shortcuts import reverse from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): mobile_number = models.CharField(_('mobile number'), max_length=13, unique=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(default=False) ...
178
178
596
5
173
swahilipothub/changemaker
app/users/models.py
Python
Profile
Profile
48
121
48
49
bc5ab081860c375fca5f68449c00ea634d841c97
bigcode/the-stack
train
fb2203284f1050f47ec96a23
train
function
def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename)
def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') def __str__(self): return self.mobile_number def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
64
64
39
23
40
swahilipothub/changemaker
app/users/models.py
Python
user_directory_path
user_directory_path
43
45
43
44
e7f1fadc9c6e3c407f0f680f094d1ab254f80bff
bigcode/the-stack
train
d92aaf47818506611417c9f8
train
class
class DateRangeSearchForm(SearchForm): start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) def search(self): # First, store the SearchQuerySet received from other processing. sqs = super(DateRangeSearchForm, self).search() if not self.is_valid():...
class DateRangeSearchForm(SearchForm):
start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) def search(self): # First, store the SearchQuerySet received from other processing. sqs = super(DateRangeSearchForm, self).search() if not self.is_valid(): return self.no_query_found...
from django import forms from haystack.forms import SearchForm class DateRangeSearchForm(SearchForm):
21
64
158
8
12
mmitucha/blavanet-web
blog/forms.py
Python
DateRangeSearchForm
DateRangeSearchForm
5
24
5
5
e0207e7b8d9b2a92ff17333f9f88f237c4383b23
bigcode/the-stack
train
d4486db714a598f07cf296d4
train
class
class Factorial_analysis_manifold: def __init__( self, matrix, manifold_method, clustering_method, ): self.matrix = matrix self.manifold_method = manifold_method self.clustering_method = clustering_method self.table_ = None self.run() ...
class Factorial_analysis_manifold:
def __init__( self, matrix, manifold_method, clustering_method, ): self.matrix = matrix self.manifold_method = manifold_method self.clustering_method = clustering_method self.table_ = None self.run() def run(self): matrix = se...
_0 ... CLTR_3 rn ... 0 crowdfunding 008:0116 ... financial technologies 028:0225 1 peer-to-peer lending 008:0073 ... innovating 013:0249 2 covid-19 008:0036 ... bank ...
219
219
730
7
211
jdvelasq/techminer-api
techminer2/factorial_analysis_manifold.py
Python
Factorial_analysis_manifold
Factorial_analysis_manifold
76
181
76
76
08668bdc491e3f4f6914336d6a6818624573ce4a
bigcode/the-stack
train
deaf5ce89428e02b362ef715
train
class
class DiscreteDynamicsWorldTestCase(WorldTestDataMixin, unittest.TestCase): def setUp(self): super(DiscreteDynamicsWorldTestCase, self).setUp() self.world = bullet.btDiscreteDynamicsWorld( self.dispatcher, self.broadphase, self....
class DiscreteDynamicsWorldTestCase(WorldTestDataMixin, unittest.TestCase):
def setUp(self): super(DiscreteDynamicsWorldTestCase, self).setUp() self.world = bullet.btDiscreteDynamicsWorld( self.dispatcher, self.broadphase, self.solver, self.collision_config ) def test_ctor(self): pass def test_step(se...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_collision.test_discretedynamicsworld """ from __future__ import unicode_literals, print_function, absolute_import import unittest import bullet from .test_worlds import WorldTestDataMixin class DiscreteDynamicsWorldTestCase(WorldTestDataMixin, ...
73
75
253
17
55
Klumhru/boost-python-bullet
test_collision/test_discretedynamicsworld.py
Python
DiscreteDynamicsWorldTestCase
DiscreteDynamicsWorldTestCase
15
49
15
16
af26e921f7c2a9d3b596040e541c647e22ca6389
bigcode/the-stack
train
452cf048b797348213b04e0f
train
function
def on_error(ws, error): print("### error:", error)
def on_error(ws, error):
print("### error:", error)
w["w"] print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False))) except Exception as e: print("receive msg,but parse exception:", e) # 收到websocket错误的处理 def on_error(ws, error):
64
64
15
7
56
cmx0223/AnsAudio
iat_ws_python3.py
Python
on_error
on_error
113
114
113
113
31b16a2a81c6b1cc377224404e17cf1e9a298d32
bigcode/the-stack
train
900077d8bccd0ce948287eb0
train
function
def on_close(ws): print("### closed ###")
def on_close(ws):
print("### closed ###")
json.dumps(data, ensure_ascii=False))) except Exception as e: print("receive msg,but parse exception:", e) # 收到websocket错误的处理 def on_error(ws, error): print("### error:", error) # 收到websocket关闭的处理 def on_close(ws):
64
64
12
5
58
cmx0223/AnsAudio
iat_ws_python3.py
Python
on_close
on_close
118
119
118
118
2c36861203ca3be9774e6966fdb11eaab376beb7
bigcode/the-stack
train
25626e4b615dadcfe1157742
train
function
def run(path): # 测试时候在此处正确填写相关信息即可运行 time1 = datetime.now() wsParam = Ws_Param(APPID='a4fed1af', APISecret='ZDU0YTBlMTM4YmIxMjhhN2E4YWU3ZDdl', APIKey='9976327509f5437289603f8ffe234d3f', AudioFile=path) websocket.enableTrace(False) wsUrl = wsParam....
def run(path): # 测试时候在此处正确填写相关信息即可运行
time1 = datetime.now() wsParam = Ws_Param(APPID='a4fed1af', APISecret='ZDU0YTBlMTM4YmIxMjhhN2E4YWU3ZDdl', APIKey='9976327509f5437289603f8ffe234d3f', AudioFile=path) websocket.enableTrace(False) wsUrl = wsParam.create_url() ws = websocket.WebSocketA...
.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run, ()) def run(path): # 测试时候在此处正确填写相关信息即可运行
63
64
177
20
43
cmx0223/AnsAudio
iat_ws_python3.py
Python
run
run
169
181
169
170
33ffe985bdcb8b2b09b7b5b5c28254a23532b48c
bigcode/the-stack
train
14aaf681a496d6128ee87ea8
train
function
def on_message(ws, message): try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: data = json.l...
def on_message(ws, message):
try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: data = json.loads(message)["data"]["result"...
的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url # 收到websocket消息的处理 def on_message(ws, message):
64
64
161
7
56
cmx0223/AnsAudio
iat_ws_python3.py
Python
on_message
on_message
91
108
91
91
5f12210cb25785a27f47b8a393f47def80626d9b
bigcode/the-stack
train
3af2b131466271a2a11dce59
train
function
def on_open(ws): def run(*args): frameSize = 8000 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(wsParam.AudioFile, "rb") as fp: while True: buf = fp.read(frameSize) ...
def on_open(ws):
def run(*args): frameSize = 8000 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(wsParam.AudioFile, "rb") as fp: while True: buf = fp.read(frameSize) # 文件结束 ...
(message)) result = "" for i in data: for w in i["cw"]: result += w["w"] print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False))) except Exception as e: print("receive msg,but parse exception:", e) ...
133
133
445
5
127
cmx0223/AnsAudio
iat_ws_python3.py
Python
on_open
on_open
123
166
123
123
67b3e7c16d799ae401fbc68d0bf0771891cca969
bigcode/the-stack
train
e2d4609c97cfe539c2abc2ce
train
class
class Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.AudioFile = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(b...
class Ws_Param(object): # 初始化
def __init__(self, APPID, APIKey, APISecret, AudioFile): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.AudioFile = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self...
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import websocket import datetime import hashlib import base64 import hmac import json from urllib.parse import urlencode import time import ssl from wsgiref.handlers import format_date_time from datetime import datet...
162
162
543
9
152
cmx0223/AnsAudio
iat_ws_python3.py
Python
Ws_Param
Ws_Param
43
87
43
44
50f07db0f26acc00c0518a4c14d54605d5ed86b0
bigcode/the-stack
train
3c205ea062872af843ad0685
train
function
def get_readable_time(seconds: int) -> int: count = 0 ping_time = "" time_list = [] time_suffix_list = ["d", "m", "j", "hari"] while count < 4: count += 1 remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0:...
def get_readable_time(seconds: int) -> int:
count = 0 ping_time = "" time_list = [] time_suffix_list = ["d", "m", "j", "hari"] while count < 4: count += 1 remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0: break time_list.append...
0: user_s = int(asplit[0]) if asplit[0].isdigit() else asplit[0] if len(asplit) == 2: reason_ = asplit[1] return user_s, reason_ def get_readable_time(seconds: int) -> int:
64
64
180
12
52
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
get_readable_time
get_readable_time
339
375
339
340
c44aa4274ed2ebb67b8241bd3cfd7d60244daf0b
bigcode/the-stack
train
85f9a4da1e364d8d454d80f7
train
function
@Client.on_message(filters.command(["song", f"song@{BOT_USERNAME}"]) & ~filters.channel) def song(client, message): user_id = message.from_user.id user_name = message.from_user.first_name rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")" query = "".join(" " + str(i) for i in message.co...
@Client.on_message(filters.command(["song", f"song@{BOT_USERNAME}"]) & ~filters.channel) def song(client, message):
user_id = message.from_user.id user_name = message.from_user.first_name rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")" query = "".join(" " + str(i) for i in message.command[1:]) print(query) m = message.reply("🔎 **Searching**") ydl_opts = {"format": "bestaudio[ext=m4a]...
OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import unicode_literals import asyncio import math import os import time import aiofiles import aiohttp import requests import wget import yt_dlp from io import BytesIO from random import randint from urllib.parse import urlparse from pyrogram import ...
172
172
576
29
142
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
song
song
83
199
83
86
66b4317511c5056c08376a328eed45e51603f73d
bigcode/the-stack
train
08e24d9c73dac01583a9bbc1
train
function
def get_user(message: Message, text: str) -> [int, str, None]: asplit = None if text is None else text.split(" ", 1) user_s = None reason_ = None if message.reply_to_message: user_s = message.reply_to_message.from_user.id reason_ = text or None elif asplit is None: re...
def get_user(message: Message, text: str) -> [int, str, None]:
asplit = None if text is None else text.split(" ", 1) user_s = None reason_ = None if message.reply_to_message: user_s = message.reply_to_message.from_user.id reason_ = text or None elif asplit is None: return None, None elif len(asplit[0]) > 0: user_s = ...
else: try: await message.edit("{}\n{}".format(type_of_ps, tmp)) except FloodWait as e: await asyncio.sleep(e.x) except MessageNotModified: pass def get_user(message: Message, text: str) -> [int, str, None]:
64
64
150
19
44
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
get_user
get_user
311
337
311
312
705542122e3b2a5bc41576e246b7b385a94df7a0
bigcode/the-stack
train
b9b945d3347ca8aa060ae9ae
train
function
def time_formatter(milliseconds: int) -> str: seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ( ((str(days) + " day(s), ") if days else "") + ((str(hours) ...
def time_formatter(milliseconds: int) -> str:
seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ( ((str(days) + " day(s), ") if days else "") + ((str(hours) + " hour(s), ") if hours else "") + ((...
] = str(time_list[x]) + time_suffix_list[x] if len(time_list) == 4: ping_time += time_list.pop() + ", " time_list.reverse() ping_time += ":".join(time_list) return ping_time def time_formatter(milliseconds: int) -> str:
64
64
157
10
53
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
time_formatter
time_formatter
377
401
377
378
484b1829e2b24462ee1ffd8da9990e1e9bce008e
bigcode/the-stack
train
6f58a9b3dad4d0886cd66062
train
function
def time_to_seconds(time): stringt = str(time) return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(":"))))
def time_to_seconds(time):
stringt = str(time) return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(":"))))
session: async with session.get(url) as resp: if resp.status == 200: f = await aiofiles.open(song_name, mode="wb") await f.write(await resp.read()) await f.close() return song_name is_downloading = False def time_to_seconds(time):
64
64
38
6
57
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
time_to_seconds
time_to_seconds
455
459
455
456
68e27735db33d72ff5922de1c82c2df16e9732f6
bigcode/the-stack
train
d4dc686cebc6e73b53d7795c
train
function
def get_file_extension_from_url(url): url_path = urlparse(url).path basename = os.path.basename(url_path) return basename.split(".")[-1]
def get_file_extension_from_url(url):
url_path = urlparse(url).path basename = os.path.basename(url_path) return basename.split(".")[-1]
"bestaudio/best", "writethumbnail": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "192", } ], } def get_file_extension_from_url(url):
64
64
36
8
56
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
get_file_extension_from_url
get_file_extension_from_url
425
431
425
426
6a6063f78a45214e81931fa785c529af70e15b10
bigcode/the-stack
train
def9cde85a0aabcf8f74499a
train
function
async def download_song(url): song_name = f"{randint(6969, 6999)}.mp3" async with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status == 200: f = await aiofiles.open(song_name, mode="wb") await f.write(await resp.read(...
async def download_song(url):
song_name = f"{randint(6969, 6999)}.mp3" async with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status == 200: f = await aiofiles.open(song_name, mode="wb") await f.write(await resp.read()) await f.clo...
3", "preferredquality": "192", } ], } def get_file_extension_from_url(url): url_path = urlparse(url).path basename = os.path.basename(url_path) return basename.split(".")[-1] # Funtion To Download Song async def download_song(url):
64
64
87
6
57
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
download_song
download_song
435
451
435
436
20b27219a0ee003c81345701dcffb9573a7928c2
bigcode/the-stack
train
7cdbc4c7949ca743e7754005
train
function
async def progress(current, total, message, start, type_of_ps, file_name=None): now = time.time() diff = now - start if round(diff % 10.00) == 0 or current == total: percentage = current * 100 / total speed = current / diff elapsed_time = round(diff) * 1000 if elapsed_...
async def progress(current, total, message, start, type_of_ps, file_name=None):
now = time.time() diff = now - start if round(diff % 10.00) == 0 or current == total: percentage = current * 100 / total speed = current / diff elapsed_time = round(diff) * 1000 if elapsed_time == 0: return time_to_completion = round((total - curre...
= 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power raised_to_pow += 1 return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B" async def progress(current, total, message, start, type_of_ps, file_name=None):
100
100
335
19
81
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
progress
progress
241
309
241
242
42045b53d99a94960cc25474df23b96694e5058b
bigcode/the-stack
train
c7f11a3346c32719d755cb68
train
function
async def download_song(url): async with session.get(url) as resp: song = await resp.read() song = BytesIO(song) song.name = "a.mp3" return song
async def download_song(url):
async with session.get(url) as resp: song = await resp.read() song = BytesIO(song) song.name = "a.mp3" return song
}` **From YouTube Music!**", file_stark, ), ) await pablo.delete() is_downloading = False for files in (sedlyf, file_stark): if files and os.path.exists(files): os.remove(files) async def download_song(url):
64
64
43
6
58
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
download_song
download_song
617
627
617
618
82986df53ea5a798fa73f6957bc436b5859555d7
bigcode/the-stack
train
97a72c8d49070a199d4f2e13
train
function
def get_text(message: Message) -> [None, str]: text_to_return = message.text if message.text is None: return None if " " not in text_to_return: return None try: return message.text.split(None, 1)[1] except IndexError: return None
def get_text(message: Message) -> [None, str]:
text_to_return = message.text if message.text is None: return None if " " not in text_to_return: return None try: return message.text.split(None, 1)[1] except IndexError: return None
) m.delete() except Exception as e: m.edit("❌ **Error**") print(e) try: os.remove(audio_file) os.remove(thumb_name) except Exception as e: print(e) def get_text(message: Message) -> [None, str]:
64
64
70
13
51
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
get_text
get_text
201
219
201
202
5570a6ff9aa840f8621259df7ac310e654f6d6cb
bigcode/the-stack
train
359a7260f73d4ec267ce4e98
train
function
@Client.on_message(command(["saavn", f"saavn@{BOT_USERNAME}"])) async def jssong(_, message): global is_downloading if len(message.command) < 2: return await message.reply_text("/saavn requires an argument.") if is_downloading: return await message.reply_text("Another download is in pr...
@Client.on_message(command(["saavn", f"saavn@{BOT_USERNAME}"])) async def jssong(_, message):
global is_downloading if len(message.command) < 2: return await message.reply_text("/saavn requires an argument.") if is_downloading: return await message.reply_text("Another download is in progress, try again after sometime.") is_downloading = True text = message.text.split(No...
if files and os.path.exists(files): os.remove(files) async def download_song(url): async with session.get(url) as resp: song = await resp.read() song = BytesIO(song) song.name = "a.mp3" return song @Client.on_message(command(["saavn", f"saavn@{BOT_USERNAME}"])) async ...
85
85
285
28
56
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
jssong
jssong
629
697
629
632
3a121ffe060e9a0c97ee174bbc5e62413f8ddd40
bigcode/the-stack
train
4029f8f770a3ecc11cb6d706
train
function
def humanbytes(size): if not size: return "" power = 2 ** 10 raised_to_pow = 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power raised_to_pow += 1 return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
def humanbytes(size):
if not size: return "" power = 2 ** 10 raised_to_pow = 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power raised_to_pow += 1 return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
str]: text_to_return = message.text if message.text is None: return None if " " not in text_to_return: return None try: return message.text.split(None, 1)[1] except IndexError: return None def humanbytes(size):
64
64
107
5
58
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
humanbytes
humanbytes
221
239
221
222
30abeb9b210e78bc565275202c3fd5ca89aa6641
bigcode/the-stack
train
878f72d2ec2767e5e1cd5139
train
function
@Client.on_message(command(["video", f"video@{BOT_USERNAME}"])) async def ytmusic(client, message: Message): global is_downloading if is_downloading: await message.reply_text( "**Downloadan yang lain sedang berlangsung, coba lagi nanti**" ) return urlissed = get_t...
@Client.on_message(command(["video", f"video@{BOT_USERNAME}"])) async def ytmusic(client, message: Message):
global is_downloading if is_downloading: await message.reply_text( "**Downloadan yang lain sedang berlangsung, coba lagi nanti**" ) return urlissed = get_text(message) pablo = await client.send_message( message.chat.id, f"`Getting {urlissed} From YouTu...
codec": "mp3", "preferredquality": "192", } ], } def get_file_extension_from_url(url): url_path = urlparse(url).path basename = os.path.basename(url_path) return basename.split(".")[-1] # Funtion To Download Song async def download_song(url): song_name = f"{randint(696...
222
222
741
29
193
ArshCypherZ/DaisyXMusic
DaisyXMusic/modules/song.py
Python
ytmusic
ytmusic
461
615
461
464
4288a9b2ba61140330a26a35e5243c61a9b15ece
bigcode/the-stack
train
bf5275a35824d90559588ade
train
function
def quaternion2euler(quaternion): w = quaternion[0] x = quaternion[1] y = quaternion[2] z = quaternion[3] ysqr = y * y t0 = +2.0 * (w * x + y * z) t1 = +1.0 - 2.0 * (x * x + ysqr) X = math.degrees(math.atan2(t0, t1)) t2 = +2.0 * (w * y - z * x) t2 = +1.0 if t2 > +1.0 else t2 t2 = -1.0 if t2 < -1.0 else t...
def quaternion2euler(quaternion):
w = quaternion[0] x = quaternion[1] y = quaternion[2] z = quaternion[3] ysqr = y * y t0 = +2.0 * (w * x + y * z) t1 = +1.0 - 2.0 * (x * x + ysqr) X = math.degrees(math.atan2(t0, t1)) t2 = +2.0 * (w * y - z * x) t2 = +1.0 if t2 > +1.0 else t2 t2 = -1.0 if t2 < -1.0 else t2 Y = math.degrees(math.asin(t2))...
, quaternion): q1 = np.copy(quaternion) q2 = np.zeros(4) q2[1:4] = np.copy(vector) q3 = inverse_quaternion(quaternion) q = quaternion_product(q2, q3) q = quaternion_product(q1, q) result = q[1:4] return result def quaternion2euler(quaternion):
78
78
261
8
69
WooQi57/cassie-run
cassie/misc/quaternion_function.py
Python
quaternion2euler
quaternion2euler
27
52
27
27
bfc0840599ac43b8edc4702ed2cbfc877af73f68
bigcode/the-stack
train
2156218f4725b389565dc114
train
function
def euler2quat(z=0, y=0, x=0): z = z/2.0 y = y/2.0 x = x/2.0 cz = math.cos(z) sz = math.sin(z) cy = math.cos(y) sy = math.sin(y) cx = math.cos(x) sx = math.sin(x) result = np.array([ cx*cy*cz - sx*sy*sz, cx*sy*sz + cy*cz*sx, cx*cz*sy - sx*...
def euler2quat(z=0, y=0, x=0):
z = z/2.0 y = y/2.0 x = x/2.0 cz = math.cos(z) sz = math.sin(z) cy = math.cos(y) sy = math.sin(y) cx = math.cos(x) sx = math.sin(x) result = np.array([ cx*cy*cz - sx*sy*sz, cx*sy*sz + cy*cz*sx, cx*cz*sy - sx*cy*sz, cx*cy*sz + s...
np.zeros(3) result[0] = X * np.pi / 180 result[1] = Y * np.pi / 180 result[2] = Z * np.pi / 180 return result def euler2quat(z=0, y=0, x=0):
64
64
164
17
46
WooQi57/cassie-run
cassie/misc/quaternion_function.py
Python
euler2quat
euler2quat
54
72
54
55
c61dbbe511997f79379d3f45068ee8714db8944c
bigcode/the-stack
train
077e9ffd067350596fee4f28
train
function
def inverse_quaternion(quaternion): result = np.copy(quaternion) result[1:4] = -result[1:4] return result
def inverse_quaternion(quaternion):
result = np.copy(quaternion) result[1:4] = -result[1:4] return result
import math import numpy as np def inverse_quaternion(quaternion):
15
64
31
7
7
WooQi57/cassie-run
cassie/misc/quaternion_function.py
Python
inverse_quaternion
inverse_quaternion
4
7
4
4
b1ebaa0bb26190255f028c8055036c97366c2af6
bigcode/the-stack
train
0c4e5dec3975bc0879936c1b
train
function
def quaternion_product(q1, q2): result = np.zeros(4) result[0] = q1[0]*q2[0]-q1[1]*q2[1]-q1[2]*q2[2]-q1[3]*q2[3] result[1] = q1[0]*q2[1]+q2[0]*q1[1]+q1[2]*q2[3]-q1[3]*q2[2] result[2] = q1[0]*q2[2]-q1[1]*q2[3]+q1[2]*q2[0]+q1[3]*q2[1] result[3] = q1[0]*q2[3]+q1[1]*q2[2]-q1[2]*q2[1]+q1[3]*q2[0] return result
def quaternion_product(q1, q2):
result = np.zeros(4) result[0] = q1[0]*q2[0]-q1[1]*q2[1]-q1[2]*q2[2]-q1[3]*q2[3] result[1] = q1[0]*q2[1]+q2[0]*q1[1]+q1[2]*q2[3]-q1[3]*q2[2] result[2] = q1[0]*q2[2]-q1[1]*q2[3]+q1[2]*q2[0]+q1[3]*q2[1] result[3] = q1[0]*q2[3]+q1[1]*q2[2]-q1[2]*q2[1]+q1[3]*q2[0] return result
import math import numpy as np def inverse_quaternion(quaternion): result = np.copy(quaternion) result[1:4] = -result[1:4] return result def quaternion_product(q1, q2):
48
64
199
9
38
WooQi57/cassie-run
cassie/misc/quaternion_function.py
Python
quaternion_product
quaternion_product
9
15
9
9
2b668a01213e6e1e7a3a56c2af7717c19a470d6d
bigcode/the-stack
train
40701a4dd3f33290cce28676
train
function
def rotate_by_quaternion(vector, quaternion): q1 = np.copy(quaternion) q2 = np.zeros(4) q2[1:4] = np.copy(vector) q3 = inverse_quaternion(quaternion) q = quaternion_product(q2, q3) q = quaternion_product(q1, q) result = q[1:4] return result
def rotate_by_quaternion(vector, quaternion):
q1 = np.copy(quaternion) q2 = np.zeros(4) q2[1:4] = np.copy(vector) q3 = inverse_quaternion(quaternion) q = quaternion_product(q2, q3) q = quaternion_product(q1, q) result = q[1:4] return result
3]*q2[1] result[3] = q1[0]*q2[3]+q1[1]*q2[2]-q1[2]*q2[1]+q1[3]*q2[0] return result def rotate_by_quaternion(vector, quaternion):
64
64
76
9
54
WooQi57/cassie-run
cassie/misc/quaternion_function.py
Python
rotate_by_quaternion
rotate_by_quaternion
17
25
17
17
c952506bc479c7d3c7264592b007f3ffe00f8e6c
bigcode/the-stack
train
3d85de2b16289c1e43c21e2c
train
function
def comp_height(self): """Compute the height of the Slot. Caution, the bottom of the Slot is an Arc Parameters ---------- self : SlotW11 A SlotW11 object Returns ------- Htot: float Height of the slot [m] """ Rbo = self.get_Rbo() if self.H1_is_rad: # H1 ...
def comp_height(self):
"""Compute the height of the Slot. Caution, the bottom of the Slot is an Arc Parameters ---------- self : SlotW11 A SlotW11 object Returns ------- Htot: float Height of the slot [m] """ Rbo = self.get_Rbo() if self.H1_is_rad: # H1 in rad H1 = (se...
# -*- coding: utf-8 -*- from numpy import cos, tan def comp_height(self):
20
74
249
5
14
mxgnsr/pyleecan
pyleecan/Methods/Slot/SlotW11/comp_height.py
Python
comp_height
comp_height
6
39
6
6
2200e64864715371c3a1015a58e27e7359586025
bigcode/the-stack
train
b1a3d002616d8045296883ee
train
function
def verbose_option(f): def callback(ctx, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.DEBUG) return click.option('-v', '--verbose', is_flag=True, expose_value=False, hel...
def verbose_option(f):
def callback(ctx, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.DEBUG) return click.option('-v', '--verbose', is_flag=True, expose_value=False, help='Enable verbose outpu...
stream = logging.StreamHandler() formatter = logging.Formatter("%(levelname)-7s - %(message)s ") stream.setFormatter(formatter) self.logger.addHandler(stream) self.logger.setLevel(level) pass_state = click.make_pass_decorator(State, ensure=True) def verbose_option(f):
64
64
68
5
59
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
verbose_option
verbose_option
40
49
40
40
f6861fe4d52572e790011fabb8ec8cb9fedcc3a6
bigcode/the-stack
train
2eb9540e52daf7b1582f2789
train
function
def quiet_option(f): def callback(ctx, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.ERROR) return click.option('-q', '--quiet', is_flag=True, expose_value=False, help='S...
def quiet_option(f):
def callback(ctx, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.ERROR) return click.option('-q', '--quiet', is_flag=True, expose_value=False, help='Silence warnings', ...
, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.DEBUG) return click.option('-v', '--verbose', is_flag=True, expose_value=False, help='Enable verbose output', ...
64
64
68
5
59
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
quiet_option
quiet_option
52
61
52
52
306eb8721942b6d04d01f69adff6e6441dcddafa
bigcode/the-stack
train
c4b2f48b8a0a00845023e94d
train
class
class State(object): ''' Maintain logging level.''' def __init__(self, log_name='mkdocs', level=logging.INFO): self.logger = logging.getLogger(log_name) self.logger.propagate = False stream = logging.StreamHandler() formatter = logging.Formatter("%(levelname)-7s - %(message)s "...
class State(object):
''' Maintain logging level.''' def __init__(self, log_name='mkdocs', level=logging.INFO): self.logger = logging.getLogger(log_name) self.logger.propagate = False stream = logging.StreamHandler() formatter = logging.Formatter("%(levelname)-7s - %(message)s ") stream.setF...
(__name__) # Disable the warning that Click displays (as of Click version 5.0) when users # use unicode_literals in Python 2. # See http://click.pocoo.org/dev/python3/#unicode-literals for more details. click.disable_unicode_literals_warning = True class State(object):
64
64
94
4
59
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
State
State
23
34
23
23
b43579f5aab126e140bea1ec341c4cbf71592d45
bigcode/the-stack
train
f6a85b223a9c5cafcf79ed12
train
function
@cli.command(name="serve") @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>') @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_...
@cli.command(name="serve") @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>') @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_...
"""Run the builtin development server""" logging.getLogger('tornado').setLevel(logging.WARNING) # Don't override config value if user did not specify --strict flag # Conveniently, load_config drops None values strict = strict or None try: serve.serve( config_file=config_fi...
@cli.command(name="serve") @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>') @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_...
208
105
350
208
0
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
serve_command
serve_command
101
131
101
111
8b3afc61ed89ea83eee42805573cac6cfc4b9380
bigcode/the-stack
train
6d76b21b3b0b7ce6d43ae240
train
function
@cli.command(name="build") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-t', '--theme', type=click.Choice(theme_choices), he...
@cli.command(name="build") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-t', '--theme', type=click.Choice(theme_choices), he...
"""Build the MkDocs documentation""" # Don't override config value if user did not specify --strict flag # Conveniently, load_config drops None values strict = strict or None try: build.build(config.load_config( config_file=config_file, strict=strict, th...
@cli.command(name="build") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-t', '--theme', type=click.Choice(theme_choices), he...
150
82
274
150
0
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
build_command
build_command
134
159
134
142
2357b216e258eedbf22ac2549e3379aa43fb0fc9
bigcode/the-stack
train
97254033cd8dfec4bc4b2c22
train
function
@cli.command(name="new") @click.argument("project_directory") @common_options def new_command(project_directory): """Create a new MkDocs project""" new.new(project_directory)
@cli.command(name="new") @click.argument("project_directory") @common_options def new_command(project_directory):
"""Create a new MkDocs project""" new.new(project_directory)
, force=force) except exceptions.ConfigurationError as e: # pragma: no cover # Avoid ugly, unhelpful traceback raise SystemExit('\n' + str(e)) @cli.command(name="new") @click.argument("project_directory") @common_options def new_command(project_directory):
64
64
38
23
41
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
new_command
new_command
219
224
219
222
eebe39fea6d17175867c4867243da2986d95fc7c
bigcode/the-stack
train
f0aa862e141855e6cbc13601
train
function
@cli.command(name="json") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_h...
@cli.command(name="json") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_h...
"""Build the MkDocs documentation to JSON files Rather than building your documentation to HTML pages, this outputs each page in a simple JSON format. This command is useful if you want to index your documentation in an external search engine. """ log.warning("The json command is deprecate...
@cli.command(name="json") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-s', '--strict', is_flag=True, help=strict_help) @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_h...
104
93
312
104
0
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
json_command
json_command
162
193
162
168
6d94c13868943be98ef39bc45b045a0c434ce4d6
bigcode/the-stack
train
a4b96398e1393d8842cff726
train
function
@cli.command(name="gh-deploy") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-m', '--message', help=commit_message_help) @click.option('-b', '--remote-branch', help=remote_branch_help) @cli...
@cli.command(name="gh-deploy") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-m', '--message', help=commit_message_help) @click.option('-b', '--remote-branch', help=remote_branch_help) @cli...
"""Deploy your documentation to GitHub Pages""" try: cfg = config.load_config( config_file=config_file, remote_branch=remote_branch, remote_name=remote_name ) build.build(cfg, dirty=not clean) gh_deploy.gh_deploy(cfg, message=message, force=for...
@cli.command(name="gh-deploy") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-f', '--config-file', type=click.File('rb'), help=config_help) @click.option('-m', '--message', help=commit_message_help) @click.option('-b', '--remote-branch', help=remote_branch_help) @cli...
135
72
241
135
0
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
gh_deploy_command
gh_deploy_command
196
216
196
204
41c73d5dd884432787b98ca2cb9e7bc3a3a3ea81
bigcode/the-stack
train
70a7cd05b8d6dbff47bd04ea
train
function
@click.group(context_settings={'help_option_names': ['-h', '--help']}) @click.version_option(__version__, '-V', '--version') @common_options def cli(): """ MkDocs - Project documentation with Markdown. """
@click.group(context_settings={'help_option_names': ['-h', '--help']}) @click.version_option(__version__, '-V', '--version') @common_options def cli():
""" MkDocs - Project documentation with Markdown. """
to for Github Pages. This " "overrides the value specified in config") force_help = "Force the push to the repository." @click.group(context_settings={'help_option_names': ['-h', '--help']}) @click.version_option(__version__, '-V', '--version') @common_options def cli():
64
64
49
36
28
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
cli
cli
92
98
92
95
0d61fdebf1b97753b1d5756398b04b14209f974f
bigcode/the-stack
train
977bb2cdc0bf8cc16d0ef119
train
function
def common_options(f): f = verbose_option(f) f = quiet_option(f) return f
def common_options(f):
f = verbose_option(f) f = quiet_option(f) return f
, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.ERROR) return click.option('-q', '--quiet', is_flag=True, expose_value=False, help='Silence warnings', ...
64
64
23
5
59
MichaelAquilina/mkdocs
mkdocs/__main__.py
Python
common_options
common_options
64
67
64
64
d7599bebb90489e40e7c1149f6c8b4eec2704426
bigcode/the-stack
train
ed2831573e7fc13cf9bfb728
train
function
def _check_file(fname, overwrite): """Prevent overwrites.""" if op.isfile(fname) and not overwrite: raise IOError('File %s exists, use --overwrite to overwrite it' % fname)
def _check_file(fname, overwrite):
"""Prevent overwrites.""" if op.isfile(fname) and not overwrite: raise IOError('File %s exists, use --overwrite to overwrite it' % fname)
p_surfaces --overwrite --subject sample """ import copy import os import os.path as op import sys import MNE.mne from MNE.mne.utils import (run_subprocess, verbose, logger, ETSContext, get_subjects_dir) def _check_file(fname, overwrite):
64
64
44
8
56
mpoziomska/MNE_poprawione
mne/commands/mne_make_scalp_surfaces.py
Python
_check_file
_check_file
28
32
28
28
0c1467c05ff701894401f008740a805ffc1ecf51
bigcode/the-stack
train
0ff5b8cc7269e8b9db05d02c
train
function
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', hel...
def run():
"""Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', help='Overwrit...
.path as op import sys import MNE.mne from MNE.mne.utils import (run_subprocess, verbose, logger, ETSContext, get_subjects_dir) def _check_file(fname, overwrite): """Prevent overwrites.""" if op.isfile(fname) and not overwrite: raise IOError('File %s exists, use --overwrite to ...
85
85
285
3
82
mpoziomska/MNE_poprawione
mne/commands/mne_make_scalp_surfaces.py
Python
run
run
35
63
35
35
10f1122a06a4535c471f3082f5dddecce53cf6ab
bigcode/the-stack
train
86545f47d2abdd7a6f75a82f
train
function
@verbose def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None): this_env = copy.deepcopy(os.environ) subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) this_env['SUBJECTS_DIR'] = subjects_dir this_env['SUBJECT'] = subject if 'FREESURFER_HOME' not in this_env: ...
@verbose def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None):
this_env = copy.deepcopy(os.environ) subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) this_env['SUBJECTS_DIR'] = subjects_dir this_env['SUBJECT'] = subject if 'FREESURFER_HOME' not in this_env: raise RuntimeError('The FreeSurfer environment needs to be set up ' ...
help='Overwrite previously computed surface') parser.add_option('-s', '--subject', dest='subject', help='The name of the subject', type='str') parser.add_option('-f', '--force', dest='force', action='store_true', help='Force transformation of sur...
241
241
805
23
218
mpoziomska/MNE_poprawione
mne/commands/mne_make_scalp_surfaces.py
Python
_run
_run
66
134
66
67
321ed607eaf8774160bbd6555d3824a0b5aca044
bigcode/the-stack
train
d04e14905470946da3ced322
train
function
def get_processes_info(): import psutil from datetime import datetime processes = [] for process in psutil.process_iter(): with process.oneshot(): pid = process.pid if pid == 0: continue name = process.name() try: create_time = date...
def get_processes_info():
import psutil from datetime import datetime processes = [] for process in psutil.process_iter(): with process.oneshot(): pid = process.pid if pid == 0: continue name = process.name() try: create_time = datetime.fromtimestamp(process....
def get_processes_info():
6
123
411
6
0
Bot-7037/Resource-Monitor
GetInfo.py
Python
get_processes_info
get_processes_info
1
58
1
1
341a49df15c2c80eda4a63d4f00c6b7658522ea4
bigcode/the-stack
train
d7b5c0086e094cf10d0a9d1a
train
class
class StylesQueue: def __init__(self): self.styles = {} def add(self, styles): for name, value in styles.items(): if name in self.styles: self.styles[name].append(value) else: self.styles[name] = [value] def remove(self, names): ...
class StylesQueue:
def __init__(self): self.styles = {} def add(self, styles): for name, value in styles.items(): if name in self.styles: self.styles[name].append(value) else: self.styles[name] = [value] def remove(self, names): for name in name...
class StylesQueue:
4
64
118
4
0
swiftfish/flexitext
flexitext/parser/utils.py
Python
StylesQueue
StylesQueue
1
19
1
1
40409a15f3adf83c32aa89d6ecbfc20fa2e864b4
bigcode/the-stack
train
4878ec2960dc0d0f2f5e516b
train
function
def array_path(arr,i,j): if not arr[i][j]: return 0 elif i == len(arr) - 1 and j == len(arr[0]) - 1: return 1 if i < len(arr)-1 and j < len(arr[0]) - 1: return array_path(arr,i + 1,j) + array_path(arr,i,j + 1) elif i == len(arr)-1: return array_path(arr,i,j+1) el...
def array_path(arr,i,j):
if not arr[i][j]: return 0 elif i == len(arr) - 1 and j == len(arr[0]) - 1: return 1 if i < len(arr)-1 and j < len(arr[0]) - 1: return array_path(arr,i + 1,j) + array_path(arr,i,j + 1) elif i == len(arr)-1: return array_path(arr,i,j+1) elif j == len(arr[0])-1: ...
""" Find the total number of path in arry. Only right and down movement is allowed. Constraint: a[i][j] shoukd be 1 to be valid path """ def array_path(arr,i,j):
45
64
128
7
38
bkpathak/HackerRank-Problems
python/recursion/array_path.py
Python
array_path
array_path
7
21
7
7
fe23b9b5c8a6bcf5172ff9f84a795c939c74a15e
bigcode/the-stack
train
936cefdbafa5cd9d1fae0f80
train
function
@tf_export(v1=["data.experimental.make_csv_dataset"]) def make_csv_dataset_v1( file_pattern, batch_size, column_names=None, column_defaults=None, label_name=None, select_columns=None, field_delim=",", use_quote_delim=True, na_value="", header=True, num_epochs=None...
@tf_export(v1=["data.experimental.make_csv_dataset"]) def make_csv_dataset_v1( file_pattern, batch_size, column_names=None, column_defaults=None, label_name=None, select_columns=None, field_delim=",", use_quote_delim=True, na_value="", header=True, num_epochs=None...
return dataset_ops.DatasetV1Adapter(make_csv_dataset_v2( file_pattern, batch_size, column_names, column_defaults, label_name, select_columns, field_delim, use_quote_delim, na_value, header, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed, prefetch_buffer_size, num_parallel_reads, sl...
@tf_export(v1=["data.experimental.make_csv_dataset"]) def make_csv_dataset_v1( file_pattern, batch_size, column_names=None, column_defaults=None, label_name=None, select_columns=None, field_delim=",", use_quote_delim=True, na_value="", header=True, num_epochs=None...
146
69
232
146
0
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
make_csv_dataset_v1
make_csv_dataset_v1
541
569
541
563
eba309dfc8e3f1b4069a4a6203574ddf7e58bd31
bigcode/the-stack
train
f765aa1b113ef0c945966870
train
class
@tf_export(v1=["data.experimental.CsvDataset"]) class CsvDatasetV1(dataset_ops.DatasetV1Adapter): """A Dataset comprising lines from one or more CSV files.""" @functools.wraps(CsvDatasetV2.__init__) def __init__(self, filenames, record_defaults, compression_ty...
@tf_export(v1=["data.experimental.CsvDataset"]) class CsvDatasetV1(dataset_ops.DatasetV1Adapter):
"""A Dataset comprising lines from one or more CSV files.""" @functools.wraps(CsvDatasetV2.__init__) def __init__(self, filenames, record_defaults, compression_type=None, buffer_size=None, header=False, field_delim...
compression_type=self._compression_type) super(CsvDatasetV2, self).__init__(variant_tensor) @property def element_spec(self): return self._element_spec @tf_export(v1=["data.experimental.CsvDataset"]) class CsvDatasetV1(dataset_ops.DatasetV1Adapter):
64
64
158
25
38
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
CsvDatasetV1
CsvDatasetV1
709
727
709
710
f75968eb5a9280387a700e65de9ecbe1eacd56fa
bigcode/the-stack
train
2e59278152caabfcaf2c95ed
train
function
@tf_export("data.experimental.make_batched_features_dataset", v1=[]) def make_batched_features_dataset_v2(file_pattern, batch_size, features, reader=core_readers.TFRecordDataset, ...
@tf_export("data.experimental.make_batched_features_dataset", v1=[]) def make_batched_features_dataset_v2(file_pattern, batch_size, features, reader=core_readers.TFRecordDataset, ...
"""Returns a `Dataset` of feature dictionaries from `Example` protos. If label_key argument is provided, returns a `Dataset` of tuple comprising of feature dictionaries and label. Example: ``` serialized_examples = [ features { feature { key: "age" value { int64_list { value: [ 0 ] } ...
(dataset_ops.DatasetV1Adapter): """A Dataset comprising lines from one or more CSV files.""" @functools.wraps(CsvDatasetV2.__init__) def __init__(self, filenames, record_defaults, compression_type=None, buffer_size=None, header=F...
256
256
1,574
116
140
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
make_batched_features_dataset_v2
make_batched_features_dataset_v2
730
887
730
745
c9a4ce90b54db4991dc7ac564192a296e2ef5290
bigcode/the-stack
train
f8c402de5bc7096325d63438
train
function
def _maybe_shuffle_and_repeat( dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed): """Optionally shuffle and repeat dataset, as requested.""" if num_epochs != 1 and shuffle: # Use shuffle_and_repeat for perf return dataset.apply( shuffle_ops.shuffle_and_repeat(shuffle_buffer_...
def _maybe_shuffle_and_repeat( dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed):
"""Optionally shuffle and repeat dataset, as requested.""" if num_epochs != 1 and shuffle: # Use shuffle_and_repeat for perf return dataset.apply( shuffle_ops.shuffle_and_repeat(shuffle_buffer_size, num_epochs, shuffle_seed)) elif shuffle: return d...
# Sort and ensure there are no duplicates result = sorted(set(select_columns)) if len(result) != len(select_columns): raise ValueError("select_columns contains duplicate columns") return result def _maybe_shuffle_and_repeat( dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed):
64
64
112
22
41
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_maybe_shuffle_and_repeat
_maybe_shuffle_and_repeat
208
220
208
209
fecc2856dcfd8a1c40514b222f87c2e6f8443542
bigcode/the-stack
train
ef4b7784f14bf6553ca4b43c
train
class
@tf_export(v1=["data.experimental.SqlDataset"]) class SqlDatasetV1(dataset_ops.DatasetV1Adapter): """A `Dataset` consisting of the results from a SQL query.""" @functools.wraps(SqlDatasetV2.__init__) def __init__(self, driver_name, data_source_name, query, output_types): wrapped = SqlDatasetV2(driver_n...
@tf_export(v1=["data.experimental.SqlDataset"]) class SqlDatasetV1(dataset_ops.DatasetV1Adapter):
"""A `Dataset` consisting of the results from a SQL query.""" @functools.wraps(SqlDatasetV2.__init__) def __init__(self, driver_name, data_source_name, query, output_types): wrapped = SqlDatasetV2(driver_name, data_source_name, query, output_types) super(SqlDatasetV1, self).__init__(wrapped)
query, **self._flat_structure) super(SqlDatasetV2, self).__init__(variant_tensor) @property def element_spec(self): return self._element_spec @tf_export(v1=["data.experimental.SqlDataset"]) class SqlDatasetV1(dataset_ops.DatasetV1Adapter):
64
64
106
24
39
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
SqlDatasetV1
SqlDatasetV1
994
1,001
994
995
db7afa7b81ad6323fa37d12a76ca2dd37c074181
bigcode/the-stack
train
dc7be261f5403da659e55552
train
function
def _get_sorted_col_indices(select_columns, column_names): """Transforms select_columns argument into sorted column indices.""" names_to_indices = {n: i for i, n in enumerate(column_names)} num_cols = len(column_names) for i, v in enumerate(select_columns): if isinstance(v, int): if v < 0 or v >...
def _get_sorted_col_indices(select_columns, column_names):
"""Transforms select_columns argument into sorted column indices.""" names_to_indices = {n: i for i, n in enumerate(column_names)} num_cols = len(column_names) for i, v in enumerate(select_columns): if isinstance(v, int): if v < 0 or v >= num_cols: raise ValueError( "Column ...
"Files have different column names in the header row.") except StopIteration: raise ValueError(("Received StopIteration when reading the header line " "of %s. Empty file?") % filenames[0]) return column_names def _get_sorted_col_indices(select_columns, column...
64
64
199
12
51
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_get_sorted_col_indices
_get_sorted_col_indices
184
205
184
184
b17a05098f59970850c40a44f9c12daa57cfb658
bigcode/the-stack
train
1d9475b2c52418aa91d1304c
train
function
def _is_valid_int32(str_val): try: # Checks equality to prevent int32 overflow return dtypes.int32.as_numpy_dtype(str_val) == dtypes.int64.as_numpy_dtype( str_val) except (ValueError, OverflowError): return False
def _is_valid_int32(str_val):
try: # Checks equality to prevent int32 overflow return dtypes.int32.as_numpy_dtype(str_val) == dtypes.int64.as_numpy_dtype( str_val) except (ValueError, OverflowError): return False
.ops import io_ops from tensorflow.python.platform import gfile from tensorflow.python.util.tf_export import tf_export _ACCEPTABLE_CSV_TYPES = (dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64, dtypes.string) def _is_valid_int32(str_val):
64
64
60
9
55
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_is_valid_int32
_is_valid_int32
51
57
51
51
3682aff2559c70d8a717ac153ca5003e891e3cb2
bigcode/the-stack
train
4d4f8e6595dee93249ee6a38
train
function
def make_tf_record_dataset(file_pattern, batch_size, parser_fn=None, num_epochs=None, shuffle=True, shuffle_buffer_size=None, shuffle_seed=None, ...
def make_tf_record_dataset(file_pattern, batch_size, parser_fn=None, num_epochs=None, shuffle=True, shuffle_buffer_size=None, shuffle_seed=None, ...
"""Reads and optionally parses TFRecord files into a dataset. Provides common functionality such as batching, optional parsing, shuffling, and performant defaults. Args: file_pattern: List of files or patterns of TFRecord file paths. See `tf.io.gfile.glob` for pattern rules. batch_size: ...
'%s' specified in select_columns not a valid column index or " "name." % v) select_columns[i] = names_to_indices[v] # Sort and ensure there are no duplicates result = sorted(set(select_columns)) if len(result) != len(select_columns): raise ValueError("select_columns contains duplicate c...
256
256
915
69
186
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
make_tf_record_dataset
make_tf_record_dataset
223
311
223
233
4c6cef0e4fd4843a101e1c4b0c3e212ee6fdc711
bigcode/the-stack
train