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
d99dd74b0792b8872650cdb7
train
function
def test_duplicate_submission(app, pg_driver, cgci_blgsp, submitter): """ Make sure that concurrent transactions don't cause duplicate submission. """ data = { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects.id": "daa208a7-f57a-562c-a04a-7a7c77542c98", } ...
def test_duplicate_submission(app, pg_driver, cgci_blgsp, submitter):
""" Make sure that concurrent transactions don't cause duplicate submission. """ data = { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects.id": "daa208a7-f57a-562c-a04a-7a7c77542c98", } # convert to TSV (save to file) file_path = os.path.join(DATA...
r = client.get(path, headers=submitter) assert len(r.json) == 1 # TSV multiple node export path = "/v0/submission/CGCI/BLGSP/export/?node_label=experiment" r = client.get(path, headers=submitter) assert r.status_code == 200, r.data assert r.headers["Content-Disposition"].endswith("tsv") ...
191
191
639
18
172
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_duplicate_submission
test_duplicate_submission
1,038
1,118
1,038
1,038
180966415c5f70858d199bae5e22da18b27f89f6
bigcode/the-stack
train
2d38bb6230685d5ffa892a59
train
function
def test_submit_export_encoding(client, pg_driver, cgci_blgsp, submitter): """Test that we can submit and export non-ascii characters without errors""" # submit metadata containing non-ascii characters headers = submitter data = json.dumps( { "type": "experiment", "submit...
def test_submit_export_encoding(client, pg_driver, cgci_blgsp, submitter):
"""Test that we can submit and export non-ascii characters without errors""" # submit metadata containing non-ascii characters headers = submitter data = json.dumps( { "type": "experiment", "submitter_id": "BLGSP-submitter-ü", "projects": {"id": "daa208a7-f57a...
.props = case.props new_case.submitter_id = "case-2" s.add(new_case) case_count = pg_driver.nodes(md.Case).count() path = "/v0/submission/CGCI/BLGSP/export/?node_label=case&format=json" r = client.get(path, headers=submitter) assert r.status_code == 200, r.data assert r.headers["...
138
138
461
19
118
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_submit_export_encoding
test_submit_export_encoding
993
1,035
993
993
69397fc69c6cd50f8e10fb17ecebf93b1afd0856
bigcode/the-stack
train
45f810aea7f00589e24ec76b
train
function
def test_top_level_dictionary_get_entries(client, pg_driver, cgci_blgsp, submitter): resp = client.get("/v0/submission/_dictionary/aliquot") assert json.loads(resp.data)["id"] == "aliquot"
def test_top_level_dictionary_get_entries(client, pg_driver, cgci_blgsp, submitter):
resp = client.get("/v0/submission/_dictionary/aliquot") assert json.loads(resp.data)["id"] == "aliquot"
lgsp, submitter): resp = client.get("/v0/submission/CGCI/BLGSP/_dictionary/aliquot") assert json.loads(resp.data)["id"] == "aliquot" def test_top_level_dictionary_get_entries(client, pg_driver, cgci_blgsp, submitter):
64
64
51
21
43
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_top_level_dictionary_get_entries
test_top_level_dictionary_get_entries
391
393
391
391
159bdeb4d8069de5945e80541f73f5600c287ad0
bigcode/the-stack
train
20372f79489a74b7c6febbb9
train
function
def test_submit_valid_tsv(client, pg_driver, cgci_blgsp, submitter): do_test_submit_valid_tsv(client, submitter)
def test_submit_valid_tsv(client, pg_driver, cgci_blgsp, submitter):
do_test_submit_valid_tsv(client, submitter)
submitter headers["Content-Type"] = "text/tsv" resp = client.put(BLGSP_PATH, headers=headers, data=data) assert resp.status_code == 200, resp.data def test_submit_valid_tsv(client, pg_driver, cgci_blgsp, submitter):
64
64
32
20
43
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_submit_valid_tsv
test_submit_valid_tsv
740
741
740
740
8bf2cc22c70cee4899fd76c9e5f145ae369d2dc8
bigcode/the-stack
train
e850b2f3b1be6308dec8eda7
train
function
def test_project_creation_endpoint(client, pg_driver, submitter): # Does not test authz. resp = put_cgci_blgsp(client, auth=submitter) assert resp.status_code == 200 resp = client.get("/v0/submission/CGCI/") with pg_driver.session_scope(): assert pg_driver.nodes(md.Project).count() == 1 ...
def test_project_creation_endpoint(client, pg_driver, submitter): # Does not test authz.
resp = put_cgci_blgsp(client, auth=submitter) assert resp.status_code == 200 resp = client.get("/v0/submission/CGCI/") with pg_driver.session_scope(): assert pg_driver.nodes(md.Project).count() == 1 n_cgci = pg_driver.nodes(md.Project).path("programs").props(name="CGCI").count() ...
( client, pg_driver, submitter ): path = "/v0/submission/abc/" resp = client.post(path, headers=submitter) assert resp.status_code == 404 def test_project_creation_endpoint(client, pg_driver, submitter): # Does not test authz.
64
64
142
21
42
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_project_creation_endpoint
test_project_creation_endpoint
166
175
166
167
ede21686b26be59e6c5a65b75a4ad1cde33936c2
bigcode/the-stack
train
f4e9b0807e54036225b3896c
train
function
def test_post_example_entities(client, pg_driver, cgci_blgsp, submitter): path = BLGSP_PATH for fname in data_fnames: with open(os.path.join(DATA_DIR, fname), "r") as f: data = json.loads(f.read()) resp = client.post(path, headers=submitter, data=json.dumps(data)) res...
def test_post_example_entities(client, pg_driver, cgci_blgsp, submitter):
path = BLGSP_PATH for fname in data_fnames: with open(os.path.join(DATA_DIR, fname), "r") as f: data = json.loads(f.read()) resp = client.post(path, headers=submitter, data=json.dumps(data)) resp_data = json.loads(resp.data) # could already exist in the DB...
r.json["entities"][2]["errors"][0]["keys"] == ["year_of_birth"], r.data assert r.json["entities"][2]["errors"][0]["type"] == "INVALID_VALUE", r.data def test_post_example_entities(client, pg_driver, cgci_blgsp, submitter):
64
64
156
19
44
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_post_example_entities
test_post_example_entities
306
319
306
306
475e1fc4eb563ebee0c5a3d9c1e58398cc62ca99
bigcode/the-stack
train
700c3be7d7491f37c09230d1
train
function
def test_invalid_json(client, pg_driver, cgci_blgsp, submitter): resp = client.put( BLGSP_PATH, headers=submitter, data="""{ "key1": "valid value", "key2": not a string, }""", ) print(resp.data) assert resp.status_code == 400 assert "Expecting value" in resp.json["mes...
def test_invalid_json(client, pg_driver, cgci_blgsp, submitter):
resp = client.put( BLGSP_PATH, headers=submitter, data="""{ "key1": "valid value", "key2": not a string, }""", ) print(resp.data) assert resp.status_code == 400 assert "Expecting value" in resp.json["message"]
"time_between_clamping_and_freezing": "2018-11-13T20:20:39+00:00", } ), ) assert r.status_code == 200, r.data def test_invalid_json(client, pg_driver, cgci_blgsp, submitter):
64
64
90
18
45
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_invalid_json
test_invalid_json
618
629
618
618
ad3ce7f012c16c78fc818189fcfacae20b338b9a
bigcode/the-stack
train
c5a40358b56bc210742ef41f
train
function
def test_export_all_node_types_and_resubmit_json( client, pg_driver, cgci_blgsp, submitter, require_index_exists_off ): js_id_data = do_test_export( client, pg_driver, submitter, "experimental_metadata", "json" ) js_data = json.loads( get_export_data(client, submitter, "experimental_meta...
def test_export_all_node_types_and_resubmit_json( client, pg_driver, cgci_blgsp, submitter, require_index_exists_off ):
js_id_data = do_test_export( client, pg_driver, submitter, "experimental_metadata", "json" ) js_data = json.loads( get_export_data(client, submitter, "experimental_metadata", "json", True).data ) for o in js_id_data.get("data"): did = o["id"] path = BLGSP_PATH + "ent...
_comma_string(["string", 1, 0.5, True], "tsv") == "string,1,0.5,True" def test_export_all_node_types_and_resubmit_json( client, pg_driver, cgci_blgsp, submitter, require_index_exists_off ):
64
64
183
32
32
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_export_all_node_types_and_resubmit_json
test_export_all_node_types_and_resubmit_json
878
896
878
880
29dcf0316bd6a53aedc0c40d281bd74e05ded41f
bigcode/the-stack
train
0702a0df09d1fbe510b3969e
train
function
def test_update_to_null_invalid_tsv(client, pg_driver, cgci_blgsp, submitter): """ Test that updating a required field (using TSV) to null results in an error """ data = json.dumps( { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects": {"id...
def test_update_to_null_invalid_tsv(client, pg_driver, cgci_blgsp, submitter):
""" Test that updating a required field (using TSV) to null results in an error """ data = json.dumps( { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects": {"id": "daa208a7-f57a-562c-a04a-7a7c77542c98"}, "type_of_sample": "samp...
=True)) assert resp.status_code == 200, resp.data resp = client.get( f"/v0/submission/CGCI/BLGSP/entities/{json.loads(resp.data)['entities'][0]['id']}", headers=headers, ) print(json.dumps(json.loads(resp.data), indent=4, sort_keys=True)) assert ( json.loads(resp.data)["enti...
150
150
503
22
128
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_update_to_null_invalid_tsv
test_update_to_null_invalid_tsv
1,346
1,400
1,346
1,346
24e33f0f95bfc33ea745b61a10e8576c940466f1
bigcode/the-stack
train
00e7e5af5470d8422833ff16
train
function
def test_put_valid_entity_invalid_type(client, pg_driver, cgci_blgsp, submitter): r = client.put( BLGSP_PATH, headers=submitter, data=json.dumps( [ { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", ...
def test_put_valid_entity_invalid_type(client, pg_driver, cgci_blgsp, submitter):
r = client.put( BLGSP_PATH, headers=submitter, data=json.dumps( [ { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects": {"code": "BLGSP"}, }, { ...
]["errors"] assert r.json["entities"][0]["errors"][0]["type"] == "INVALID_LINK" assert ( "[{'project_id': 'CGCI-BLGSP', 'submitter_id': 'missing-case'}]" in r.json["entities"][0]["errors"][0]["message"] ) def test_put_valid_entity_invalid_type(client, pg_driver, cgci_blgsp, submitter):
90
90
303
21
69
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_put_valid_entity_invalid_type
test_put_valid_entity_invalid_type
269
303
269
269
f7861b434643502e87c14a2d80951e6cfb770964
bigcode/the-stack
train
d3b26aafba1f9ec20b9a3700
train
function
def test_submit_valid_csv(client, pg_driver, cgci_blgsp, submitter): """ Test that we can submit a valid CSV file """ data = { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects.id": "daa208a7-f57a-562c-a04a-7a7c77542c98", } # convert to CSV (save to f...
def test_submit_valid_csv(client, pg_driver, cgci_blgsp, submitter):
""" Test that we can submit a valid CSV file """ data = { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects.id": "daa208a7-f57a-562c-a04a-7a7c77542c98", } # convert to CSV (save to file) file_path = os.path.join( os.path.dirname(os.path.re...
resp = client.put(BLGSP_PATH, headers=headers, data=data) assert resp.status_code == 200, resp.data def test_submit_valid_tsv(client, pg_driver, cgci_blgsp, submitter): do_test_submit_valid_tsv(client, submitter) def test_submit_valid_csv(client, pg_driver, cgci_blgsp, submitter):
79
79
264
19
60
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_submit_valid_csv
test_submit_valid_csv
744
774
744
744
e5e526c57f1f94368c3643d358a0cdc02345e3f3
bigcode/the-stack
train
cff1fa4577e9e04471388b15
train
function
def test_validator_error_types(client, pg_driver, cgci_blgsp, submitter): assert put_example_entities_together(client, submitter).status_code == 200 r = client.put( BLGSP_PATH, headers=submitter, data=json.dumps( { "type": "sample", "cases": {...
def test_validator_error_types(client, pg_driver, cgci_blgsp, submitter):
assert put_example_entities_together(client, submitter).status_code == 200 r = client.put( BLGSP_PATH, headers=submitter, data=json.dumps( { "type": "sample", "cases": {"submitter_id": "BLGSP-71-06-00019"}, "is_ffpe": "maybe", ...
_validate", just_raise_exception) try: r = put_example_entities_together(client, submitter) assert len(r.json["transactional_errors"]) == 1, r.data except: raise def test_validator_error_types(client, pg_driver, cgci_blgsp, submitter):
64
64
208
19
44
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_validator_error_types
test_validator_error_types
552
572
552
552
239faf4e4c69f182a3907fe9e03976fef225789e
bigcode/the-stack
train
368bd36afbd180d7983a3b67
train
function
def test_program_creation_unauthorized( client, pg_driver, submitter, mock_arborist_requests ): # Just checks that this is guarded with an Arborist auth request. # (Does not check that the auth request is for the Sheepdog admin policy.) mock_arborist_requests(authorized=False) path = "/v0/submission...
def test_program_creation_unauthorized( client, pg_driver, submitter, mock_arborist_requests ): # Just checks that this is guarded with an Arborist auth request. # (Does not check that the auth request is for the Sheepdog admin policy.)
mock_arborist_requests(authorized=False) path = "/v0/submission/" headers = submitter data = json.dumps({"name": "CGCI", "type": "program"}) resp = client.put(path, headers=headers, data=data) assert resp.status_code == 403
condition_to_check, resp.json def test_program_creation_unauthorized( client, pg_driver, submitter, mock_arborist_requests ): # Just checks that this is guarded with an Arborist auth request. # (Does not check that the auth request is for the Sheepdog admin policy.)
64
64
122
57
6
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_program_creation_unauthorized
test_program_creation_unauthorized
145
155
145
149
1463177411a4ffa955d3293746342f1d1efad518
bigcode/the-stack
train
add6509adfe91410836b592c
train
function
def test_export_all_node_types_and_resubmit_json_with_empty_field( client, pg_driver, cgci_blgsp, submitter, require_index_exists_off ): """ Test we can export an entity with empty fields (as json) then resubmit it. The exported entity should have the empty fields omitted. """ js_id_data = do_te...
def test_export_all_node_types_and_resubmit_json_with_empty_field( client, pg_driver, cgci_blgsp, submitter, require_index_exists_off ):
""" Test we can export an entity with empty fields (as json) then resubmit it. The exported entity should have the empty fields omitted. """ js_id_data = do_test_export(client, pg_driver, submitter, "experiment", "json") assert js_id_data js_data = json.loads( get_export_data(client,...
data=str_data) print(json.dumps(json.loads(resp.data), indent=4, sort_keys=True)) assert resp.status_code == 201, resp.data def test_export_all_node_types_and_resubmit_json_with_empty_field( client, pg_driver, cgci_blgsp, submitter, require_index_exists_off ):
68
68
228
35
32
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_export_all_node_types_and_resubmit_json_with_empty_field
test_export_all_node_types_and_resubmit_json_with_empty_field
924
945
924
926
965de2d8c61f2e3407f82671b7677079afa4fb09
bigcode/the-stack
train
c11cd316b47c51305df65ab5
train
function
def do_test_delete_entity(client, submitter): resp = client.put( BLGSP_PATH, headers=submitter, data=json.dumps( { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects": {"id": "daa208a7-f57a-562c-a04a-7a7c77542c98"}...
def do_test_delete_entity(client, submitter):
resp = client.put( BLGSP_PATH, headers=submitter, data=json.dumps( { "type": "experiment", "submitter_id": "BLGSP-71-06-00019", "projects": {"id": "daa208a7-f57a-562c-a04a-7a7c77542c98"}, } ), ) assert re...
_recurrence": -1, "days_to_last_known_disease_status": -1, } resp = client.put(BRCA_PATH, headers=submitter, data=json.dumps(data)) assert resp.status_code == 400, resp.data def do_test_delete_entity(client, submitter):
64
64
159
10
53
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
do_test_delete_entity
do_test_delete_entity
512
528
512
512
ff24473a41ec6bb8ca0741480b84927ca529d290
bigcode/the-stack
train
03aa1878d09cc5214a933ff2
train
function
def test_post_example_entities_together(client, pg_driver, cgci_blgsp, submitter): do_test_post_example_entities_together(client, submitter)
def test_post_example_entities_together(client, pg_driver, cgci_blgsp, submitter):
do_test_post_example_entities_together(client, submitter)
resp.status_code == 400 and "already exists in the DB" in resp_data["entities"][0]["errors"][0]["message"] ) assert condition_to_check, resp.data def test_post_example_entities_together(client, pg_driver, cgci_blgsp, submitter):
64
64
34
21
42
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_post_example_entities_together
test_post_example_entities_together
359
360
359
359
0cf7e5de55748bcafa8182de04c7cf20ceae83b9
bigcode/the-stack
train
2c4b687424c1014ae0ea8ca5
train
function
def test_put_valid_entity_missing_target(client, pg_driver, cgci_blgsp, submitter): with open(os.path.join(DATA_DIR, "sample.json"), "r") as f: sample = json.loads(f.read()) sample["cases"] = {"submitter_id": "missing-case"} r = client.put(BLGSP_PATH, headers=submitter, data=json.dumps(sample))...
def test_put_valid_entity_missing_target(client, pg_driver, cgci_blgsp, submitter):
with open(os.path.join(DATA_DIR, "sample.json"), "r") as f: sample = json.loads(f.read()) sample["cases"] = {"submitter_id": "missing-case"} r = client.put(BLGSP_PATH, headers=submitter, data=json.dumps(sample)) print(r.data) assert r.status_code == 400, r.data assert r.status_code...
": {"id": "daa208a7-f57a-562c-a04a-7a7c77542c98"}, } ), ) assert resp.status_code == 403 def test_put_valid_entity_missing_target(client, pg_driver, cgci_blgsp, submitter):
64
64
208
21
42
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
test_put_valid_entity_missing_target
test_put_valid_entity_missing_target
249
266
249
249
f6f63f813b6fd6842b7b18ee9b23930c0ee617c2
bigcode/the-stack
train
f0c03441855752e0980f86db
train
function
def mock_request(f): def wrapper(*args, **kwargs): mock = mock_s3() mock.start(reset=False) conn = boto.connect_s3() conn.create_bucket("test_submission") result = f(*args, **kwargs) mock.stop() return result return wrapper
def mock_request(f):
def wrapper(*args, **kwargs): mock = mock_s3() mock.start(reset=False) conn = boto.connect_s3() conn.create_bucket("test_submission") result = f(*args, **kwargs) mock.stop() return result return wrapper
s3_conn(): mock = mock_s3() mock.start(reset=False) conn = boto.connect_s3() yield conn bucket = conn.get_bucket("test_submission") for part in bucket.list_multipart_uploads(): part.cancel_upload() mock.stop() def mock_request(f):
64
64
65
5
59
rpatil524/sheepdog
tests/integration/datadict/submission/test_endpoints.py
Python
mock_request
mock_request
48
59
48
48
022c68117f8e48eddcdea62c6e3249f4076fb9e9
bigcode/the-stack
train
59eccb4a4e8eb072fc264bf4
train
class
class MichelineCodingTestKT1FfZ(TestCase): @classmethod def setUpClass(cls): cls.maxDiff = None cls.code = get_data( path='contracts/KT1FfZcfsbxXgNKGHpnGWaokXXrvvW1wddGp/code_KT1FfZ.json') cls.schema = dict( parameter=build_schema(cls.code[0]), st...
class MichelineCodingTestKT1FfZ(TestCase): @classmethod
def setUpClass(cls): cls.maxDiff = None cls.code = get_data( path='contracts/KT1FfZcfsbxXgNKGHpnGWaokXXrvvW1wddGp/code_KT1FfZ.json') cls.schema = dict( parameter=build_schema(cls.code[0]), storage=build_schema(cls.code[1]) ) def test_micheline...
from unittest import TestCase from tests import get_data from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline class MichelineCodingTestKT1FfZ(TestCase): @classmethod
52
256
898
18
33
juztin/pytezos-1
tests/contracts/KT1FfZcfsbxXgNKGHpnGWaokXXrvvW1wddGp/test_micheline_coding_KT1FfZ.py
Python
MichelineCodingTestKT1FfZ
MichelineCodingTestKT1FfZ
7
73
7
9
45bb50f710d75ef5c4358bf262952a907d4c7b99
bigcode/the-stack
train
ec629f820c01ddef958704a2
train
class
class TestApp(TestBase): @patch("dawdle.components.swagger.blueprints.send_from_directory") def test_500(self, send_from_directory): # do this temporarily to stop exceptions being thrown by app self._app.config.update({"DEBUG": False, "TESTING": False}) send_from_directory.side_effect =...
class TestApp(TestBase): @patch("dawdle.components.swagger.blueprints.send_from_directory")
def test_500(self, send_from_directory): # do this temporarily to stop exceptions being thrown by app self._app.config.update({"DEBUG": False, "TESTING": False}) send_from_directory.side_effect = Exception() response = self._client.get(url_for("swagger_ui.template_GET")) self...
from unittest.mock import patch from flask import url_for from tests.helpers import TestBase class TestApp(TestBase): @patch("dawdle.components.swagger.blueprints.send_from_directory")
40
64
94
21
18
vanillaSlice/dawdle
api/tests/test_app.py
Python
TestApp
TestApp
8
16
8
10
686b14bdb2537656a0d87488202fad45605e15c9
bigcode/the-stack
train
38f50fe47c35dc35825b2fa3
train
class
class Solution: def letterCombinations(self, digits: str) -> List[str]: map_dict = { '2': "abc", '3': "def", '4': "ghi", '5': "jkl", '6': "mno", '7': "pqrs", '8': "tuv", '9': "wxyz" } path = "" #...
class Solution:
def letterCombinations(self, digits: str) -> List[str]: map_dict = { '2': "abc", '3': "def", '4': "ghi", '5': "jkl", '6': "mno", '7': "pqrs", '8': "tuv", '9': "wxyz" } path = "" # a single path ...
class Solution:
3
66
221
3
0
Aden-Q/leetcode
code/LeetCode_17_backtracking.py
Python
Solution
Solution
1
34
1
1
fa4ed86de79c5a50854fc066f1ce54f3e7e5e5f5
bigcode/the-stack
train
94236d26b0ca9320f186d89e
train
class
class Constants(BaseConstants): name_in_url = 'rubinstein' players_per_group = 2 num_rounds = 8 initial_pie = c(100) dimnishing = c(25)
class Constants(BaseConstants):
name_in_url = 'rubinstein' players_per_group = 2 num_rounds = 8 initial_pie = c(100) dimnishing = c(25)
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range, ) author = 'Your name here' doc = """ Your app description """ class Constants(BaseConstants):
59
64
49
5
54
seyhunsaral/otree-course
example_apps/rubinstein/models.py
Python
Constants
Constants
20
26
20
20
baf76b46454637158d42d3109f3f653bd277d342
bigcode/the-stack
train
8b991301c59584d1dea98487
train
class
class Player(BasePlayer): def role(self): if self.round_number % 2 == 1: return {1: 'proposer', 2: 'responder'}[self.id_in_group] else: return {2: 'proposer', 1: 'responder'}[self.id_in_group]
class Player(BasePlayer):
def role(self): if self.round_number % 2 == 1: return {1: 'proposer', 2: 'responder'}[self.id_in_group] else: return {2: 'proposer', 1: 'responder'}[self.id_in_group]
def set_payoffs(self): import random self.selected_part = random.choice([1,2]) print("running") for p in self.get_players(): p.payoff = p.participant.vars['payoff_list'][self.selected_part - 1] class Player(BasePlayer):
62
64
69
5
57
seyhunsaral/otree-course
example_apps/rubinstein/models.py
Python
Player
Player
74
79
74
74
242500d93252f397ed32412b7a6c5353c814c313
bigcode/the-stack
train
0e3fa9f32536981e586fadff
train
class
class Subsession(BaseSubsession): def creating_session(self): print("Creating session is executed") print(self.round_number) print(self.round_number in [1,5]) if self.round_number in [1,5]: self.group_randomly() print("Creating session is executed conditionall...
class Subsession(BaseSubsession):
def creating_session(self): print("Creating session is executed") print(self.round_number) print(self.round_number in [1,5]) if self.round_number in [1,5]: self.group_randomly() print("Creating session is executed conditionally") else: sel...
doc = """ Your app description """ class Constants(BaseConstants): name_in_url = 'rubinstein' players_per_group = 2 num_rounds = 8 initial_pie = c(100) dimnishing = c(25) class Subsession(BaseSubsession):
64
64
106
7
57
seyhunsaral/otree-course
example_apps/rubinstein/models.py
Python
Subsession
Subsession
29
44
29
29
416208e863a2e5c1259078ca19713bbcb4fd18d8
bigcode/the-stack
train
062890d1b75a5762ce677223
train
class
class Group(BaseGroup): offer = models.CurrencyField(min=0, label = "How much would you like to offer?", widget = widgets.Slider()) response = models.StringField(choices = ["accept", "reject"], label = "Please tell your response",) current_pie = models.CurrencyField() selected_part = models.IntegerField...
class Group(BaseGroup):
offer = models.CurrencyField(min=0, label = "How much would you like to offer?", widget = widgets.Slider()) response = models.StringField(choices = ["accept", "reject"], label = "Please tell your response",) current_pie = models.CurrencyField() selected_part = models.IntegerField() # def calculate_c...
]: self.group_randomly() print("Creating session is executed conditionally") else: self.group_like_round(self.round_number -1) print(self.get_group_matrix()) for p in self.get_players(): p.participant.vars['payoff_list'] = [] class Group(BaseGro...
63
64
188
5
58
seyhunsaral/otree-course
example_apps/rubinstein/models.py
Python
Group
Group
49
69
49
49
b579af3b25fa8366e5534587ee94327815571095
bigcode/the-stack
train
035c38b855ec5f0a6244f9c8
train
class
class TupleArg(Tuple): def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args])
class TupleArg(Tuple):
def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args])
py.functions import (sqrt, exp, log, sin, cos, asin, atan, sinh, cosh, asinh, acosh, atanh, acoth, Abs, re, factorial, RisingFactorial) from sympy.logic.boolalg import (And, Or) class TupleArg(Tuple):
64
64
62
6
58
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
TupleArg
TupleArg
19
24
19
19
2c68d44f1af591556ab6fd101f041f2cad2b695c
bigcode/the-stack
train
02d1a384406bc29dd4a5a8bc
train
class
class HyperRep_asin2(HyperRep): """ Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """ # TODO this can be nicer @classmethod def _expr_small(cls, z): return HyperRep_asin1._expr_small(z) \ /HyperRep_power1._expr_small(S.Half, z) @classmethod def _expr_...
class HyperRep_asin2(HyperRep):
""" Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """ # TODO this can be nicer @classmethod def _expr_small(cls, z): return HyperRep_asin1._expr_small(z) \ /HyperRep_power1._expr_small(S.Half, z) @classmethod def _expr_small_minus(cls, z): ret...
qrt(z) + I*acosh(sqrt(z))/sqrt(z)) @classmethod def _expr_big_minus(cls, z, n): return S.NegativeOne**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z)) class HyperRep_asin2(HyperRep):
69
69
232
10
59
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_asin2
HyperRep_asin2
951
972
951
951
95f2a7394e617065cd316a8f3801fa29632d81af
bigcode/the-stack
train
10a24a87c59e5c4f9f7ceaad
train
class
class HyperRep_asin1(HyperRep): """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cl...
class HyperRep_asin1(HyperRep):
""" Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cls, z, n): return S.Negat...
- I*pi/2)/sqrt(x) def _expr_big_minus(cls, x, n): if n.is_even: return atan(sqrt(x))/sqrt(x) else: return (atan(sqrt(x)) - pi)/sqrt(x) class HyperRep_asin1(HyperRep):
64
64
181
10
54
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_asin1
HyperRep_asin1
932
948
932
932
ce90cefb23ec7240e1ad9141a8b31c519ac08a6c
bigcode/the-stack
train
f7121e6ce171b49604881bfd
train
class
class HyperRep_sinasin(HyperRep): """ Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): re...
class HyperRep_sinasin(HyperRep):
""" Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return -sqrt(z)/sqrt(1 + z)*sinh(2*a...
*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class HyperRep_sinasin(HyperRep):
71
71
239
10
61
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_sinasin
HyperRep_sinasin
1,082
1,100
1,082
1,082
982f66945cc3f55faf9324cc3b6d60f13e2497c3
bigcode/the-stack
train
7399881df33788365dcf10b1
train
class
class HyperRep(Function): """ A base class for "hyper representation functions". This is used exclusively in ``hyperexpand()``, but fits more logically here. pFq is branched at 1 if p == q+1. For use with slater-expansion, we want define an "analytic continuation" to all polar numbers, which is ...
class HyperRep(Function):
""" A base class for "hyper representation functions". This is used exclusively in ``hyperexpand()``, but fits more logically here. pFq is branched at 1 if p == q+1. For use with slater-expansion, we want define an "analytic continuation" to all polar numbers, which is continuous on circles an...
+ self.args[1][1])) @property def bother(self): """ Second set of denominator parameters. """ return Tuple(*self.args[1][1]) @property def _diffargs(self): return self.ap + self.bq @property def nu(self): """ A quantity related to the convergence region of the...
187
187
624
5
181
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep
HyperRep
767
836
767
767
97a58d4132be6029e2b7636a3b92c7d1d4f78bd2
bigcode/the-stack
train
5d060c2a68adb208c5e9198e
train
class
class HyperRep_log1(HyperRep): """ Represent -z*hyper([1, 1], [2], z) == log(1 - z). """ @classmethod def _expr_small(cls, x): return log(1 - x) @classmethod def _expr_small_minus(cls, x): return log(1 + x) @classmethod def _expr_big(cls, x, n): return log(x - 1) + ...
class HyperRep_log1(HyperRep):
""" Represent -z*hyper([1, 1], [2], z) == log(1 - z). """ @classmethod def _expr_small(cls, x): return log(1 - x) @classmethod def _expr_small_minus(cls, x): return log(1 + x) @classmethod def _expr_big(cls, x, n): return log(x - 1) + (2*n - 1)*pi*I @classmetho...
if n.is_odd: sgn = -1 return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n) class HyperRep_log1(HyperRep):
64
64
145
9
55
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_log1
HyperRep_log1
891
907
891
891
a1220ba8772dce40a95aece74aaa130becdadf49
bigcode/the-stack
train
afa89062af4c73e69b76f1f2
train
class
class HyperRep_sqrts2(HyperRep): """ Return a representative for sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a] == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)""" @classmethod def _expr_small(cls, a, z): return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2 @...
class HyperRep_sqrts2(HyperRep):
""" Return a representative for sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a] == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)""" @classmethod def _expr_small(cls, a, z): return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_m...
1)**(2*a)*exp(2*pi*I*a*n))/2 @classmethod def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_sqrts2(HyperRep):
117
117
393
11
106
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_sqrts2
HyperRep_sqrts2
1,004
1,032
1,004
1,004
82699b75ae60a57902cbac93e23f1d7e6174070b
bigcode/the-stack
train
50a3e55fc710868d7e3c50d1
train
class
class HyperRep_power2(HyperRep): """ Return a representative for hyper([a, a - 1/2], [2*a], z). """ @classmethod def _expr_small(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a) @classmethod def _expr_small_minus(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2...
class HyperRep_power2(HyperRep):
""" Return a representative for hyper([a, a - 1/2], [2*a], z). """ @classmethod def _expr_small(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a) @classmethod def _expr_small_minus(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a) @classmethod def _ex...
) return (x - 1)**a*exp((2*n - 1)*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): if a.is_integer: return cls._expr_small_minus(a, x) return (1 + x)**a*exp(2*n*pi*I*a) class HyperRep_power2(HyperRep):
86
86
288
9
77
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_power2
HyperRep_power2
863
888
863
863
b60dd6ae8bcab6132aa4f498d73e0db3addccdc2
bigcode/the-stack
train
8ec3a32411aa68e34188b731
train
function
def _prep_tuple(v): """ Turn an iterable argument *v* into a tuple and unpolarify, since both hypergeometric and meijer g-functions are unbranched in their parameters. Examples ======== >>> from sympy.functions.special.hyper import _prep_tuple >>> _prep_tuple([1, 2, 3]) (1, 2, 3) >...
def _prep_tuple(v):
""" Turn an iterable argument *v* into a tuple and unpolarify, since both hypergeometric and meijer g-functions are unbranched in their parameters. Examples ======== >>> from sympy.functions.special.hyper import _prep_tuple >>> _prep_tuple([1, 2, 3]) (1, 2, 3) >>> _prep_tuple((4, 5...
xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args]) # TODO should __new__ accept **options? # TODO should constructors should check if parameters are sensible? def _prep_tuple(v):
64
64
163
6
58
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
_prep_tuple
_prep_tuple
31
49
31
31
a3af541ad516e7a856478038e8478886cc748029
bigcode/the-stack
train
bf1ea17ec650388dc0e290c1
train
class
class HyperRep_atanh(HyperRep): """ Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, x): return atanh(sqrt(x))/sqrt(x) def _expr_small_minus(cls, x): return atan(sqrt(x))/sqrt(x) def _expr_big(cls, x, n): if n.is_even: ...
class HyperRep_atanh(HyperRep):
""" Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, x): return atanh(sqrt(x))/sqrt(x) def _expr_small_minus(cls, x): return atan(sqrt(x))/sqrt(x) def _expr_big(cls, x, n): if n.is_even: return (acoth(sqrt(x)) ...
, n): return log(x - 1) + (2*n - 1)*pi*I @classmethod def _expr_big_minus(cls, x, n): return log(1 + x) + 2*n*pi*I class HyperRep_atanh(HyperRep):
64
64
184
9
54
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_atanh
HyperRep_atanh
910
929
910
910
939b5235bcdd0e102ae31a6d23ca07d2e2360d3c
bigcode/the-stack
train
55d21340cb9b0c01c42464b6
train
class
class HyperRep_power1(HyperRep): """ Return a representative for hyper([-a], [], z) == (1 - z)**a. """ @classmethod def _expr_small(cls, a, x): return (1 - x)**a @classmethod def _expr_small_minus(cls, a, x): return (1 + x)**a @classmethod def _expr_big(cls, a, x, n): ...
class HyperRep_power1(HyperRep):
""" Return a representative for hyper([-a], [], z) == (1 - z)**a. """ @classmethod def _expr_small(cls, a, x): return (1 - x)**a @classmethod def _expr_small_minus(cls, a, x): return (1 + x)**a @classmethod def _expr_big(cls, a, x, n): if a.is_integer: ...
x, n = self.args[-1].extract_branch_factor(allow_half=True) args = self.args[:-1] + (x,) if not n.is_Integer: return self._expr_small_minus(*args) return self._expr_small(*args) class HyperRep_power1(HyperRep):
64
64
189
9
55
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_power1
HyperRep_power1
839
860
839
839
17477d22135a912ca8a58b6513e10983a730946d
bigcode/the-stack
train
4b6624d69563474c245e3e51
train
class
class HyperRep_cosasin(HyperRep): """ Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """ # Note there are many alternative expressions, e.g. as powers of a sum of # square roots. @classmethod def _expr_small(cls, a, z): return cos(2*a*asin(sqrt(z))) @classmethod def ...
class HyperRep_cosasin(HyperRep):
""" Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """ # Note there are many alternative expressions, e.g. as powers of a sum of # square roots. @classmethod def _expr_small(cls, a, z): return cos(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): ...
, z, n): if n.is_even: return pi*I*n + log(S.Half + sqrt(1 + z)/2) else: return pi*I*n + log(sqrt(1 + z)/2 - S.Half) class HyperRep_cosasin(HyperRep):
64
64
203
9
55
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_cosasin
HyperRep_cosasin
1,060
1,079
1,060
1,060
12a8f5728d28c1b5065aa96e9c8591494083f9d2
bigcode/the-stack
train
01abd10d7147aecab1f72bb8
train
class
class hyper(TupleParametersBase): r""" The generalized hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain. Explanation =========== ...
class hyper(TupleParametersBase):
r""" The generalized hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain. Explanation =========== The hypergeometric function dep...
3) >>> _prep_tuple((4, 5)) (4, 5) >>> _prep_tuple((7, 8, 9)) (7, 8, 9) """ from sympy.functions.elementary.complexes import unpolarify return TupleArg(*[unpolarify(x) for x in v]) class TupleParametersBase(Function): """ Base class that takes care of differentiation, when some of ...
256
256
2,586
7
249
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
hyper
hyper
71
359
71
71
070bd0079c3991c6bcf161ef36dc064428d0e462
bigcode/the-stack
train
93f2574d21c34b4de25d4fc4
train
class
class HyperRep_log2(HyperRep): """ Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """ @classmethod def _expr_small(cls, z): return log(S.Half + sqrt(1 - z)/2) @classmethod def _expr_small_minus(cls, z): return log(S.Half + sqrt(1 + z)/2) @classmethod ...
class HyperRep_log2(HyperRep):
""" Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """ @classmethod def _expr_small(cls, z): return log(S.Half + sqrt(1 - z)/2) @classmethod def _expr_small_minus(cls, z): return log(S.Half + sqrt(1 + z)/2) @classmethod def _expr_big(cls, z, n): ...
a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \ *sin(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_log2(HyperRep):
76
76
256
9
67
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_log2
HyperRep_log2
1,035
1,057
1,035
1,035
0fc067ea3d8a6efe754fb35f645da0617a5e06cc
bigcode/the-stack
train
c88b8953beed0b5b0a45ce08
train
class
class appellf1(Function): r""" This is the Appell hypergeometric function of two variables as: .. math :: F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}} \frac{x^m y^n}{m! n!}. Examples ======== >>> from sympy ...
class appellf1(Function):
r""" This is the Appell hypergeometric function of two variables as: .. math :: F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}} \frac{x^m y^n}{m! n!}. Examples ======== >>> from sympy import appellf1, symbols ...
+ a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z))) @classmethod ...
219
219
732
6
213
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
appellf1
appellf1
1,102
1,158
1,102
1,102
fd5bc19e1abc43375c0bddeab7d58b9fed5027c5
bigcode/the-stack
train
0183f983da5ddfccc214d151
train
class
class HyperRep_sqrts1(HyperRep): """ Return a representative for hyper([-a, 1/2 - a], [1/2], z). """ @classmethod def _expr_small(cls, a, z): return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return (1 + z)**a*cos(2*a*atan(sqrt(z)...
class HyperRep_sqrts1(HyperRep):
""" Return a representative for hyper([-a, 1/2 - a], [1/2], z). """ @classmethod def _expr_small(cls, a, z): return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return (1 + z)**a*cos(2*a*atan(sqrt(z))) @classmethod def _exp...
expr_big(cls, z, n): return HyperRep_asin1._expr_big(z, n) \ /HyperRep_power1._expr_big(S.Half, z, n) @classmethod def _expr_big_minus(cls, z, n): return HyperRep_asin1._expr_big_minus(z, n) \ /HyperRep_power1._expr_big_minus(S.Half, z, n) class HyperRep_sqrts1(HyperRep)...
101
101
338
11
90
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
HyperRep_sqrts1
HyperRep_sqrts1
975
1,001
975
975
a00cff6ea1ecf770900f6db118c972eba66c4fa7
bigcode/the-stack
train
5b34e59721293cefbbc097cf
train
class
class TupleParametersBase(Function): """ Base class that takes care of differentiation, when some of the arguments are actually tuples. """ # This is not deduced automatically since there are Tuples as arguments. is_commutative = True def _eval_derivative(self, s): try: res ...
class TupleParametersBase(Function):
""" Base class that takes care of differentiation, when some of the arguments are actually tuples. """ # This is not deduced automatically since there are Tuples as arguments. is_commutative = True def _eval_derivative(self, s): try: res = 0 if self.args[0].has(s...
) >>> _prep_tuple((7, 8, 9)) (7, 8, 9) """ from sympy.functions.elementary.complexes import unpolarify return TupleArg(*[unpolarify(x) for x in v]) class TupleParametersBase(Function):
64
64
171
6
58
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
TupleParametersBase
TupleParametersBase
52
68
52
52
9392f99c0911b0ab1116b157e5108cbb62c7b3cf
bigcode/the-stack
train
39e29560320179e61603ca99
train
class
class meijerg(TupleParametersBase): r""" The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalizes the hypergeometric functions. Explanation =========== The Meijer G-function depends on four sets of parameters. There are ...
class meijerg(TupleParametersBase):
r""" The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalizes the hypergeometric functions. Explanation =========== The Meijer G-function depends on four sets of parameters. There are "*numerator parameters*" $a_1,...
is a polynomial. return oo if len(self.ap) == len(self.bq) + 1: return S.One elif len(self.ap) <= len(self.bq): return oo else: return S.Zero @property def convergence_statement(self): """ Return a condition on z under which t...
256
256
3,819
9
247
utkarshdeorah/sympy
sympy/functions/special/hyper.py
Python
meijerg
meijerg
362
764
362
362
ea219ae27a96218c5a60d12fd7407e548f1b978b
bigcode/the-stack
train
37b62979227a550389fdcb54
train
class
class DocumentVersionPageOCRContentManager(models.Manager): def delete_content_for(self, document_version, user=None): self.filter(document_version_page__document_version=document_version).delete() event_ocr_document_version_content_deleted.commit( actor=user, action_object=document_ver...
class DocumentVersionPageOCRContentManager(models.Manager):
def delete_content_for(self, document_version, user=None): self.filter(document_version_page__document_version=document_version).delete() event_ocr_document_version_content_deleted.commit( actor=user, action_object=document_version.document, target=document_version )...
import logging from django.apps import apps from django.db import models from mayan.apps.converter.settings import setting_image_generation_timeout from mayan.apps.lock_manager.backends.base import LockingBackend from .classes import OCRBackendBase from .events import event_ocr_document_version_content_deleted logg...
80
121
406
10
70
atitaya1412/Mayan-EDMS
mayan/apps/ocr/managers.py
Python
DocumentVersionPageOCRContentManager
DocumentVersionPageOCRContentManager
15
75
15
15
cee2662bdab49ea5d0cb1243886a91bb1987eb38
bigcode/the-stack
train
0979ff59e63d008cc1161ec6
train
class
class DocumentTypeSettingsManager(models.Manager): def get_by_natural_key(self, document_type_natural_key): DocumentType = apps.get_model( app_label='documents', model_name='DocumentType' ) try: document_type = DocumentType.objects.get_by_natural_key( ...
class DocumentTypeSettingsManager(models.Manager):
def get_by_natural_key(self, document_type_natural_key): DocumentType = apps.get_model( app_label='documents', model_name='DocumentType' ) try: document_type = DocumentType.objects.get_by_natural_key( document_type_natural_key ) exc...
_info=True ) raise else: logger.info( 'Finished processing page: %d of document version: %s', document_version_page.page_number, document_version_page.document_version ) fi...
64
64
98
8
56
atitaya1412/Mayan-EDMS
mayan/apps/ocr/managers.py
Python
DocumentTypeSettingsManager
DocumentTypeSettingsManager
78
90
78
78
eaf189018076067a45f4cee5d026569cef85c160
bigcode/the-stack
train
30eadf6bec049654e110f5b4
train
class
class TestRStudioEndpoints(object): pipeline_id = None run_ids = [] nodes = set() state = FailureIndicator() custom_dns_swap_flags = {} test_case = '' custom_dns_hosted_zone = '' custom_dns_hosted_zone_id = '' @classmethod def setup_class(cls): logging.basicConfig(filen...
class TestRStudioEndpoints(object):
pipeline_id = None run_ids = [] nodes = set() state = FailureIndicator() custom_dns_swap_flags = {} test_case = '' custom_dns_hosted_zone = '' custom_dns_hosted_zone_id = '' @classmethod def setup_class(cls): logging.basicConfig(filename=get_log_filename(), level=loggin...
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
155
256
1,790
7
147
ZMaratovna/cloud-pipeline
e2e/cli/endpoints/test_rstudio_custom_dns_record_endpoint.py
Python
TestRStudioEndpoints
TestRStudioEndpoints
19
183
19
19
392c16b7ac6275740633c40eebffc2c580bbe3a5
bigcode/the-stack
train
3777410befce0f648c4bd7f5
train
class
class AwaitableGetActiveSessionsResult(GetActiveSessionsResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetActiveSessionsResult( next_link=self.next_link, value=self.value)
class AwaitableGetActiveSessionsResult(GetActiveSessionsResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetActiveSessionsResult( next_link=self.next_link, value=self.value)
(self) -> Optional[Sequence['outputs.BastionActiveSessionResponseResult']]: """ List of active sessions on the bastion. """ return pulumi.get(self, "value") class AwaitableGetActiveSessionsResult(GetActiveSessionsResult): # pylint: disable=using-constant-test
64
64
57
23
41
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/network/v20200501/get_active_sessions.py
Python
AwaitableGetActiveSessionsResult
AwaitableGetActiveSessionsResult
48
55
48
49
8a2039919e3bd7bf7378d419b018e73c761f0780
bigcode/the-stack
train
1ab7d0fee7a1b9c1edb158af
train
class
@pulumi.output_type class GetActiveSessionsResult: """ Response for GetActiveSessions. """ def __init__(__self__, next_link=None, value=None): if next_link and not isinstance(next_link, str): raise TypeError("Expected argument 'next_link' to be a str") pulumi.set(__self__, "n...
@pulumi.output_type class GetActiveSessionsResult:
""" Response for GetActiveSessions. """ def __init__(__self__, next_link=None, value=None): if next_link and not isinstance(next_link, str): raise TypeError("Expected argument 'next_link' to be a str") pulumi.set(__self__, "next_link", next_link) if value and not isin...
typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'GetActiveSessionsResult', 'AwaitableGetActiveSessionsResult', 'get_active_sessions', ] @pulumi.output_type class GetActiveSessionsResult:
66
66
223
12
54
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/network/v20200501/get_active_sessions.py
Python
GetActiveSessionsResult
GetActiveSessionsResult
18
45
18
19
ce80b10bf98b9e9f30bdd5f6c4671eeb57a2c8ee
bigcode/the-stack
train
0d509fdf97adde745b647eee
train
function
def get_active_sessions(bastion_host_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetActiveSessionsResult: """ Response for GetActiveSessions. :param str bastion_host_name: Th...
def get_active_sessions(bastion_host_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetActiveSessionsResult:
""" Response for GetActiveSessions. :param str bastion_host_name: The name of the Bastion Host. :param str resource_group_name: The name of the resource group. """ __args__ = dict() __args__['bastionHostName'] = bastion_host_name __args__['resourceGroupName'] = resource_group_name ...
return GetActiveSessionsResult( next_link=self.next_link, value=self.value) def get_active_sessions(bastion_host_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awaitabl...
67
67
225
48
19
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/network/v20200501/get_active_sessions.py
Python
get_active_sessions
get_active_sessions
58
79
58
60
f92b6afb3da4182b06eb838e92128152b760e98b
bigcode/the-stack
train
a240ba475e893f8193a34c10
train
function
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--net', dest='...
def parse_args():
""" Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--net', dest='net', ...
# Written by Jiasen Lu, Jianwei Yang, based on code from Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths import os import sys import numpy as np import argparse impor...
217
217
726
4
212
prachigarg23/faster-rcnn.pytorch
trainval_net.py
Python
parse_args
parse_args
36
120
36
36
318aad3cededa7be2cbfedfd53c39fc03e4edf27
bigcode/the-stack
train
7ee8f3e75439d962d42506be
train
class
class sampler(Sampler): def __init__(self, train_size, batch_size): self.num_data = train_size self.num_per_batch = int(train_size / batch_size) #number of batches self.batch_size = batch_size #number of elements per batch self.range = torch.arange(0,batch_size).view(1, batch_size).long() #if batch_si...
class sampler(Sampler):
def __init__(self, train_size, batch_size): self.num_data = train_size self.num_per_batch = int(train_size / batch_size) #number of batches self.batch_size = batch_size #number of elements per batch self.range = torch.arange(0,batch_size).view(1, batch_size).long() #if batch_size=4, we get range = [0 ...
=1, type=int) parser.add_argument('--checkpoint', dest='checkpoint', help='checkpoint to load model', default=0, type=int) # log and display parser.add_argument('--use_tfb', dest='use_tfboard', help='whether use tensorboard', ac...
83
83
279
5
77
prachigarg23/faster-rcnn.pytorch
trainval_net.py
Python
sampler
sampler
123
146
123
123
0437ceb1e3239df3a7f06f7c145840175351db5b
bigcode/the-stack
train
4f409859c0923a3fde25afb5
train
class
class CombineMethodEnum(object): """Implementation of the 'CombineMethod' enum. Specifies how to combine the children of this node. The combining strategy for child devices. Some of these strategies imply constraint on the number of child devices. e.g. RAID5 will have 5 children. 'LINEAR' indi...
class CombineMethodEnum(object):
"""Implementation of the 'CombineMethod' enum. Specifies how to combine the children of this node. The combining strategy for child devices. Some of these strategies imply constraint on the number of child devices. e.g. RAID5 will have 5 children. 'LINEAR' indicates children are juxtaposed to f...
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class CombineMethodEnum(object):
23
103
346
6
17
chandrashekar-cohesity/management-sdk-python
cohesity_management_sdk/models/combine_method_enum.py
Python
CombineMethodEnum
CombineMethodEnum
4
59
4
5
69009ed7e27e6a0e4e3e406d42340ffb2d087d8e
bigcode/the-stack
train
748e3dd8da4b8057c8e18ba5
train
class
class UnitTest(unittest.TestCase): """Class: UnitTest Description: Class which is a representation of a unit testing. Methods: setUp test_query """ def setUp(self): """Function: setUp Description: Initialization for unit testing. Arguments: ...
class UnitTest(unittest.TestCase):
"""Class: UnitTest Description: Class which is a representation of a unit testing. Methods: setUp test_query """ def setUp(self): """Function: setUp Description: Initialization for unit testing. Arguments: """ self.name = "Mongo_Se...
): """Class: CollOpts Description: Class stub holder for Coll class. Methods: options """ def options(self): """Function: options Description: Stub for Coll.coll_options method. Arguments: """ return True class UnitTest(unittest.TestCase)...
67
67
224
7
59
deepcoder42/mongo-lib
test/unit/mongo_class/repsetcoll_coll_options.py
Python
UnitTest
UnitTest
60
107
60
61
e36f01c4a2040a21ff39365562ed1bdd852b1532
bigcode/the-stack
train
fb4ec84795f79886937380f0
train
class
class CollOpts(object): """Class: CollOpts Description: Class stub holder for Coll class. Methods: options """ def options(self): """Function: options Description: Stub for Coll.coll_options method. Arguments: """ return True
class CollOpts(object):
"""Class: CollOpts Description: Class stub holder for Coll class. Methods: options """ def options(self): """Function: options Description: Stub for Coll.coll_options method. Arguments: """ return True
import sys import os if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Third-party # Local sys.path.append(os.getcwd()) import mongo_class import version __version__ = version.__version__ class CollOpts(object):
63
64
64
5
58
deepcoder42/mongo-lib
test/unit/mongo_class/repsetcoll_coll_options.py
Python
CollOpts
CollOpts
36
57
36
37
24b2e38e4644d65eaff8c80beec0f71f9d4d00f2
bigcode/the-stack
train
c070bf1a96cff8290333510b
train
class
class Client(simple.Client): def __init__(self, model=None, datasource=None, trainer=None): super().__init__() self.model_received = False self.gradient_received = False def load_payload(self, server_payload): """Loading the server model onto this client.""" if self.mod...
class Client(simple.Client):
def __init__(self, model=None, datasource=None, trainer=None): super().__init__() self.model_received = False self.gradient_received = False def load_payload(self, server_payload): """Loading the server model onto this client.""" if self.model_received == True and self....
""" A split learning client. """ import logging from dataclasses import dataclass from plato.config import Config from plato.clients import simple @dataclass class Report: """Client report sent to the split learning server.""" num_samples: int payload_length: int class Client(simple.Client):
63
108
362
5
57
iQua/plato
plato/clients/split_learning.py
Python
Client
Client
20
65
20
20
af192bb6852849ae41b3636db7cb094aac850ee3
bigcode/the-stack
train
06e3c4f845800e4f2cad71e9
train
class
@dataclass class Report: """Client report sent to the split learning server.""" num_samples: int payload_length: int
@dataclass class Report:
"""Client report sent to the split learning server.""" num_samples: int payload_length: int
""" A split learning client. """ import logging from dataclasses import dataclass from plato.config import Config from plato.clients import simple @dataclass class Report:
35
64
29
6
28
iQua/plato
plato/clients/split_learning.py
Python
Report
Report
13
17
13
14
1836bd71d55d0e5b0759143fa41a942b6d18542a
bigcode/the-stack
train
1a9ba9aa1a470c6c3cce9b12
train
function
def install(): install_std_handler() install_error_panel_handler() settings = sublime.load_settings("SublimeLinter.sublime-settings") settings.add_on_change('SublimeLinter._logging', install_std_handler)
def install():
install_std_handler() install_error_panel_handler() settings = sublime.load_settings("SublimeLinter.sublime-settings") settings.add_on_change('SublimeLinter._logging', install_std_handler)
import logging import sublime from .lint import util DEBUG_FALSE_LEVEL = logging.WARNING DEBUG_TRUE_LEVEL = logging.INFO ERROR_PANEL_LEVEL = logging.ERROR logger = logging.getLogger('SublimeLinter') logger.setLevel(logging.DEBUG) handler = None error_panel_handler = None def install():
64
64
49
3
60
jaraco/SublimeLinter
log_handler.py
Python
install
install
18
23
18
18
e191f0f647fe6d9630b143e6c220b9d3a9d59c7e
bigcode/the-stack
train
e30b83cb2c1b4c04f102dcbc
train
function
def install_error_panel_handler(): global error_panel_handler if error_panel_handler: logger.removeHandler(error_panel_handler) formatter = TaskNumberFormatter( fmt="SublimeLinter: {TASK_NUMBER}{LINTER_NAME}{FILENAME}{levelname}:\n\n" "{message}", style='{') error_pa...
def install_error_panel_handler():
global error_panel_handler if error_panel_handler: logger.removeHandler(error_panel_handler) formatter = TaskNumberFormatter( fmt="SublimeLinter: {TASK_NUMBER}{LINTER_NAME}{FILENAME}{levelname}:\n\n" "{message}", style='{') error_panel_handler = ErrorPanelHandler() ...
handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(level) logger.addHandler(handler) logger.setLevel(min(ERROR_PANEL_LEVEL, level)) logger.info( 'Logging installed; log level {}'.format(logging.getLevelName(level)) ) def install_error_panel_ha...
64
64
104
6
58
jaraco/SublimeLinter
log_handler.py
Python
install_error_panel_handler
install_error_panel_handler
74
87
74
74
aacaade8a22fbebe9fc41072108b7f5894bf85b4
bigcode/the-stack
train
b2d291e7202431c730f949d6
train
class
class ErrorPanelHandler(logging.Handler): def emit(self, record): try: msg = self.format(record) lines = msg.splitlines() header, rest = lines[0], '\n'.join(lines[1:]) window = record.VIEW.window() if record.VIEW else sublime.active_window() if no...
class ErrorPanelHandler(logging.Handler):
def emit(self, record): try: msg = self.format(record) lines = msg.splitlines() header, rest = lines[0], '\n'.join(lines[1:]) window = record.VIEW.window() if record.VIEW else sublime.active_window() if not window: return ...
.VIEW = None levelno = record.levelno if levelno > logging.INFO: record.LEVELNAME = record.levelname + ': ' else: record.LEVELNAME = '' return super().format(record) shown_error_messages = defaultdict(set) class ErrorPanelHandler(logging.Handler):
64
64
142
7
57
jaraco/SublimeLinter
log_handler.py
Python
ErrorPanelHandler
ErrorPanelHandler
117
137
117
117
586041821b371e747a3e6ddc33c78f4a778a7a42
bigcode/the-stack
train
8ade1ac4d49c4a1e94718197
train
function
def plugin_unloaded(): if handler: logger.removeHandler(handler) if error_panel_handler: logger.removeHandler(error_panel_handler) settings = sublime.load_settings("SublimeLinter.sublime-settings") settings.clear_on_change('SublimeLinter._logging')
def plugin_unloaded():
if handler: logger.removeHandler(handler) if error_panel_handler: logger.removeHandler(error_panel_handler) settings = sublime.load_settings("SublimeLinter.sublime-settings") settings.clear_on_change('SublimeLinter._logging')
handler = None error_panel_handler = None def install(): install_std_handler() install_error_panel_handler() settings = sublime.load_settings("SublimeLinter.sublime-settings") settings.add_on_change('SublimeLinter._logging', install_std_handler) def plugin_unloaded():
64
64
60
5
59
jaraco/SublimeLinter
log_handler.py
Python
plugin_unloaded
plugin_unloaded
26
33
26
26
c5775d0ba33bf1520ff82b596f8ace6d966a73eb
bigcode/the-stack
train
bd9b07865cc87aa715b157f5
train
function
def _install_std_handler(level=False): global handler if handler: logger.removeHandler(handler) if level is False: level = DEBUG_FALSE_LEVEL formatter = TaskNumberFormatter( fmt="SublimeLinter: {LEVELNAME}{message}", style='{') handler = logging.Strea...
def _install_std_handler(level=False):
global handler if handler: logger.removeHandler(handler) if level is False: level = DEBUG_FALSE_LEVEL formatter = TaskNumberFormatter( fmt="SublimeLinter: {LEVELNAME}{message}", style='{') handler = logging.StreamHandler() handler.setFormatter...
ime-settings") settings.clear_on_change('SublimeLinter._logging') def install_std_handler(): settings = sublime.load_settings("SublimeLinter.sublime-settings") level = settings.get('debug', False) _install_std_handler(level) def _install_std_handler(level=False):
64
64
197
8
56
jaraco/SublimeLinter
log_handler.py
Python
_install_std_handler
_install_std_handler
42
71
42
42
757356d3354901233f5e3df4ae2be8ac21774a22
bigcode/the-stack
train
d653b0aa5ef8760e906fd4c6
train
class
class TaskNumberFormatter(logging.Formatter): def format(self, record): thread_name = record.threadName if thread_name.startswith('LintTask|'): _, task_number, linter_name, filename, vid = thread_name.split('|') record.TASK_NUMBER = '#{} '.format(task_number) reco...
class TaskNumberFormatter(logging.Formatter):
def format(self, record): thread_name = record.threadName if thread_name.startswith('LintTask|'): _, task_number, linter_name, filename, vid = thread_name.split('|') record.TASK_NUMBER = '#{} '.format(task_number) record.LINTER_NAME = linter_name + ' ' ...
_NAME}{FILENAME}{levelname}:\n\n" "{message}", style='{') error_panel_handler = ErrorPanelHandler() error_panel_handler.setFormatter(formatter) error_panel_handler.setLevel(ERROR_PANEL_LEVEL) logger.addHandler(error_panel_handler) class TaskNumberFormatter(logging.Formatter):
64
64
171
8
56
jaraco/SublimeLinter
log_handler.py
Python
TaskNumberFormatter
TaskNumberFormatter
90
111
90
90
8085af5b7e1b135b70d8218502aae483e832f857
bigcode/the-stack
train
8cddc9b6c46acbd2596d2660
train
function
def install_std_handler(): settings = sublime.load_settings("SublimeLinter.sublime-settings") level = settings.get('debug', False) _install_std_handler(level)
def install_std_handler():
settings = sublime.load_settings("SublimeLinter.sublime-settings") level = settings.get('debug', False) _install_std_handler(level)
plugin_unloaded(): if handler: logger.removeHandler(handler) if error_panel_handler: logger.removeHandler(error_panel_handler) settings = sublime.load_settings("SublimeLinter.sublime-settings") settings.clear_on_change('SublimeLinter._logging') def install_std_handler():
64
64
39
5
59
jaraco/SublimeLinter
log_handler.py
Python
install_std_handler
install_std_handler
36
39
36
36
72190ec04c5917c3fb8a09524fac9471bd2239ba
bigcode/the-stack
train
0610838d15fe1bc79bab39f0
train
function
def make_nets(specs, device): ret = {} for net_name, spec in specs.items(): net_class = getattr(networks, spec["class"]) net_args = spec.get("net_kwargs", {}) net = net_class(**net_args).to(device) ret[net_name] = { "net": net, "opt": getattr(optim, spec["...
def make_nets(specs, device):
ret = {} for net_name, spec in specs.items(): net_class = getattr(networks, spec["class"]) net_args = spec.get("net_kwargs", {}) net = net_class(**net_args).to(device) ret[net_name] = { "net": net, "opt": getattr(optim, spec["opt"])(net.parameters(), **spe...
dom import yaml from easydict import EasyDict from torch import optim # from . import args, networks, train_fixture import args import networks import train_fixture from args import g from dataset import DatasetSourceTargetPairMultiframeDst def make_nets(specs, device):
64
64
100
9
54
Jbwasse2/rmp_nav
topological_nav/controller/train_multiframe_dst.py
Python
make_nets
make_nets
21
31
21
21
8119b122006ea094aff35ac7a1cb2ea0433ebf4b
bigcode/the-stack
train
1ece5d2d7b47b8f50b63d5b6
train
function
def class_balanced_cross_entropy_loss(output, label): """Define the class balanced cross entropy loss to train the network Args: output: Output of the network label: Ground truth label Returns: Tensor that evaluates the loss """ labels = tf.cast(tf.greater(label, 0.5), tf.float32) nu...
def class_balanced_cross_entropy_loss(output, label):
"""Define the class balanced cross entropy loss to train the network Args: output: Output of the network label: Ground truth label Returns: Tensor that evaluates the loss """ labels = tf.cast(tf.greater(label, 0.5), tf.float32) num_labels_pos = tf.reduce_sum(labels) num_labels_ne...
tf.multiply(1.0 - labels, loss_val)) # final_loss = num_labels_neg / num_total * loss_pos + num_labels_pos / num_total * loss_neg # return final_loss # ADDED ON APRIL 6, 2021. def class_balanced_cross_entropy_loss(output, label):
67
68
229
11
56
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
class_balanced_cross_entropy_loss
class_balanced_cross_entropy_loss
272
292
272
272
80b3d4e6c1087e48d250cd8e895f10b17ccd311b
bigcode/the-stack
train
c7923f9f9f217bb8681bf5ab
train
function
def crop_features(feature, out_size): """Crop the center of a feature map Args: feature: Feature map to crop out_size: Size of the output feature map Returns: Tensor that performs the cropping """ up_size = tf.shape(feature) ini_w = tf.div(tf.subtract(up_size[1], out_size[1]), 2) ...
def crop_features(feature, out_size):
"""Crop the center of a feature map Args: feature: Feature map to crop out_size: Size of the output feature map Returns: Tensor that performs the cropping """ up_size = tf.shape(feature) ini_w = tf.div(tf.subtract(up_size[1], out_size[1]), 2) ini_h = tf.div(tf.subtract(up_size[2]...
weights_initializer=tf.random_normal_initializer(stddev=0.001), weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer, biases_regularizer=None, padding='SAME')...
64
64
171
8
55
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
crop_features
crop_features
41
53
41
41
b1320004d66782f6829e4f29f5863b7af7d3c341
bigcode/the-stack
train
6e47065875a5c92e3d0fe769
train
function
def parameter_lr(): """Specify the learning rate for every parameter Args: Returns: Dictionary with the learning rate for every parameter """ vars_corresp = dict() vars_corresp['seg_liver/conv1/conv1_1/weights'] = 1 vars_corresp['seg_liver/conv1/conv1_1/biases'] = 2 vars_corresp['se...
def parameter_lr():
"""Specify the learning rate for every parameter Args: Returns: Dictionary with the learning rate for every parameter """ vars_corresp = dict() vars_corresp['seg_liver/conv1/conv1_1/weights'] = 1 vars_corresp['seg_liver/conv1/conv1_1/biases'] = 2 vars_corresp['seg_liver/conv1/conv1_...
loss_val)) loss_neg = tf.reduce_sum(-tf.multiply(1.0 - labels, loss_val)) final_loss = 0.931 * loss_pos + 0.069 * loss_neg return final_loss def dice_coef_theoretical(y_pred, y_true): """Define the dice coefficient Args: y_pred: Prediction y_true: Ground truth Label R...
256
256
1,067
4
251
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
parameter_lr
parameter_lr
319
378
319
319
ea492ebe3a27ceccaa6fccefe1a8731d1f6b7d90
bigcode/the-stack
train
dcf60077e1acd426a03d4e9f
train
function
def train_seg(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=2, loss=1, momentum=0.9, resume_training=False, ...
def train_seg(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=2, loss=1, momentum=0.9, resume_training=False, ...
"""Train parent network Args: See _train() Returns: """ _train(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices, volume, iter_mean_grad, batch_size, task_id, loss, momentum, ...
def train_seg(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=2, loss=1, momentum=0.9, resume_training=False, ...
85
64
173
85
0
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
train_seg
train_seg
648
660
648
651
42f8533f46be3d297fbd2c10074a1db0bbcd3328
bigcode/the-stack
train
6c80a799ec1c00692914a90b
train
function
def seg_liver_arg_scope(weight_decay=0.0002): """Defines the arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.convolution2d_transpose], activation_fn=tf.nn.relu, ...
def seg_liver_arg_scope(weight_decay=0.0002):
"""Defines the arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.convolution2d_transpose], activation_fn=tf.nn.relu, weights_initializer=tf.random_normal_initiali...
import sys from datetime import datetime import os import scipy.misc from PIL import Image slim = tf.contrib.slim import scipy.io import timeit # import matplotlib.pyplot as plt DTYPE = tf.float32 def seg_liver_arg_scope(weight_decay=0.0002):
64
64
128
14
49
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
seg_liver_arg_scope
seg_liver_arg_scope
24
38
24
24
fb578ca1323eb0b88c4b146333a84bfc0f2e467f
bigcode/the-stack
train
7264164bad0a688fe443e313
train
function
def test(dataset, checkpoint_path, result_path, number_slices=1, volume=False, config=None): """Test one sequence Args: dataset: Reference to a Dataset object instance checkpoint_path: Path of the checkpoint to use for the evaluation result_path: Path to save the output images config: Reference ...
def test(dataset, checkpoint_path, result_path, number_slices=1, volume=False, config=None):
"""Test one sequence Args: dataset: Reference to a Dataset object instance checkpoint_path: Path of the checkpoint to use for the evaluation result_path: Path to save the output images config: Reference to a Configuration object used in the creation of a Session Returns: net: """ ...
: %s" % save_path) print('Finished training.') def train_seg(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=2, loss...
210
210
702
22
188
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
test
test
663
726
663
663
4fd53f46e18f268420a2fa9d36ee358d5060fff1
bigcode/the-stack
train
a42857508cdb3f640679f6a5
train
function
def dice_coef_theoretical(y_pred, y_true): """Define the dice coefficient Args: y_pred: Prediction y_true: Ground truth Label Returns: Dice coefficient """ y_true_f = tf.cast(tf.reshape(y_true, [-1]), tf.float32) y_pred_f = tf.nn.sigmoid(y_pred) y_pred_f...
def dice_coef_theoretical(y_pred, y_true):
"""Define the dice coefficient Args: y_pred: Prediction y_true: Ground truth Label Returns: Dice coefficient """ y_true_f = tf.cast(tf.reshape(y_true, [-1]), tf.float32) y_pred_f = tf.nn.sigmoid(y_pred) y_pred_f = tf.cast(tf.greater(y_pred_f, 0.5), tf.fl...
(-tf.multiply(labels, loss_val)) loss_neg = tf.reduce_sum(-tf.multiply(1.0 - labels, loss_val)) final_loss = 0.931 * loss_pos + 0.069 * loss_neg return final_loss def dice_coef_theoretical(y_pred, y_true):
64
64
204
11
52
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
dice_coef_theoretical
dice_coef_theoretical
294
316
294
294
ffc80efe78c0e51288229a8aba7ce66b860d084a
bigcode/the-stack
train
3e28e08b913e183b502eefac
train
function
def preprocess_img(image, number_slices): """Preprocess the image to adapt it to network requirements Args: Image we want to input the network (W,H,3) numpy array Returns: Image ready to input the network (1,W,H,3) """ images = [[] for i in range(np.array(image).shape[0])] if number_slices...
def preprocess_img(image, number_slices):
"""Preprocess the image to adapt it to network requirements Args: Image we want to input the network (W,H,3) numpy array Returns: Image ready to input the network (1,W,H,3) """ images = [[] for i in range(np.array(image).shape[0])] if number_slices > 2: for j in range(np.array(imag...
need to be square') raise up_filter = upsample_filt(int(h)) tmp[range(m), range(k), :, :] = up_filter interp_tensors.append(tf.assign(v, tmp.transpose((2, 3, 1, 0)), validate_shape=True, use_locking=True)) return interp_tensors def preprocess_img(image, number_sl...
81
81
273
9
71
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
preprocess_img
preprocess_img
172
199
172
172
8cb5520b2f347a148ebdebddd5747f0fbe37646d
bigcode/the-stack
train
205e7cab9045b6d583b18d9f
train
function
def load_vgg_imagenet(ckpt_path, number_slices): """Initialize the network parameters from the VGG-16 pre-trained model provided by TF-SLIM Args: Path to the checkpoint Returns: Function that takes a session and initializes the network """ reader = tf.train.NewCheckpointReader(ckpt_path) ...
def load_vgg_imagenet(ckpt_path, number_slices):
"""Initialize the network parameters from the VGG-16 pre-trained model provided by TF-SLIM Args: Path to the checkpoint Returns: Function that takes a session and initializes the network """ reader = tf.train.NewCheckpointReader(ckpt_path) var_to_shape_map = reader.get_variable_to_shape_...
, 2, 0)) max_mask = np.max(label) * 0.5 label = np.greater(label, max_mask) label = np.expand_dims(label, axis=0) return label def load_vgg_imagenet(ckpt_path, number_slices):
64
64
189
16
47
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
load_vgg_imagenet
load_vgg_imagenet
225
242
225
225
ceeadd5ff6fe6a5f51cfc27711a09dce66e994d8
bigcode/the-stack
train
a92e8950b9afcc7b59d07308
train
function
def seg_liver(inputs, number_slices=1, volume=False, scope='seg_liver'): """Defines the network Args: inputs: Tensorflow placeholder that contains the input image scope: Scope name for the network Returns: net: Output Tensor of the network end_points: Dictionary with all Tensors of the netwo...
def seg_liver(inputs, number_slices=1, volume=False, scope='seg_liver'):
"""Defines the network Args: inputs: Tensorflow placeholder that contains the input image scope: Scope name for the network Returns: net: Output Tensor of the network end_points: Dictionary with all Tensors of the network """ im_size = tf.shape(inputs) with tf.variable_scope(sco...
crop_features(feature, out_size): """Crop the center of a feature map Args: feature: Feature map to crop out_size: Size of the output feature map Returns: Tensor that performs the cropping """ up_size = tf.shape(feature) ini_w = tf.div(tf.subtract(up_size[1], out_size[1]), 2) in...
256
256
1,425
21
235
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
seg_liver
seg_liver
64
138
64
64
823ff88ff0d9c02e61f3f4ae8ecb3cdc033f6955
bigcode/the-stack
train
811296cbebea670eeea9cf53
train
function
def preprocess_labels(label, number_slices): """Preprocess the labels to adapt them to the loss computation requirements Args: Label corresponding to the input image (W,H) numpy array Returns: Label ready to compute the loss (1,W,H,1) """ labels = [[] for i in range(np.array(label).shape[0])...
def preprocess_labels(label, number_slices):
"""Preprocess the labels to adapt them to the loss computation requirements Args: Label corresponding to the input image (W,H) numpy array Returns: Label ready to compute the loss (1,W,H,1) """ labels = [[] for i in range(np.array(label).shape[0])] for j in range(np.array(label).shape[0...
_ = np.array(images[0]) in_ = in_.transpose((1, 2, 0)) #in_ = in_[:, :, ::-1] in_ = np.expand_dims(in_, axis=0) return in_ def preprocess_labels(label, number_slices):
63
64
193
9
54
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
preprocess_labels
preprocess_labels
202
222
202
202
4ec3705b775ab02fe53e501cc7791007c1548491
bigcode/the-stack
train
6ce1d4570dbc33ef78e5174f
train
function
def interp_surgery(variables): interp_tensors = [] for v in variables: if '-up' in v.name: h, w, k, m = v.get_shape() tmp = np.zeros((m, k, h, w)) if m != k: print ('input + output channels need to be the same') raise if h !...
def interp_surgery(variables):
interp_tensors = [] for v in variables: if '-up' in v.name: h, w, k, m = v.get_shape() tmp = np.zeros((m, k, h, w)) if m != k: print ('input + output channels need to be the same') raise if h != w: print ('fi...
og[0] - center) / factor) * \ (1 - abs(og[1] - center) / factor) # set parameters s.t. deconvolutional layers compute bilinear interpolation # N.B. this is for deconvolution without groups def interp_surgery(variables):
64
64
159
7
56
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
interp_surgery
interp_surgery
154
169
154
154
8a4589d945686e8b4e8e4a55ca0ab9c054dc2320
bigcode/the-stack
train
8608f1aa22aa89e68ca57609
train
function
def _bias_variable(name, shape): return tf.get_variable(name, shape, DTYPE, tf.constant_initializer(0.1, dtype=DTYPE))
def _bias_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.constant_initializer(0.1, dtype=DTYPE))
(feature.get_shape()[0]), out_size[1], out_size[2], int(feature.get_shape()[3])]) def _weight_variable(name, shape): return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1)) def _bias_variable(name, shape):
64
64
33
8
56
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
_bias_variable
_bias_variable
60
61
60
60
b7c2e6c3b23146ed92dc02af5528e825548ac66c
bigcode/the-stack
train
52e9dd32b99fc612bdd237b7
train
function
def upsample_filt(size): factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] return (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1] - center) / factor)
def upsample_filt(size):
factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] return (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1] - center) / factor)
side_5_f], 3) net = slim.conv2d(concat_side, number_slices, [1, 1], scope='upscore-fuse') end_points = slim.utils.convert_collection_to_dict(end_points_collection) return net, end_points def upsample_filt(size):
64
64
99
7
56
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
upsample_filt
upsample_filt
141
149
141
141
7dff57e876b04775e739b90657572aaa7e7e696d
bigcode/the-stack
train
046f27909eff889eefcba06a
train
function
def _weight_variable(name, shape): return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1))
def _weight_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1))
, ini_h, 0), (-1, out_size[1], out_size[2], -1)) return tf.reshape(slice_input, [int(feature.get_shape()[0]), out_size[1], out_size[2], int(feature.get_shape()[3])]) def _weight_variable(name, shape):
64
64
32
8
56
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
_weight_variable
_weight_variable
56
57
56
56
1fb4bcb38ae94cce82812ba476bc958cebc406e6
bigcode/the-stack
train
f3fd372688c476df3c3ef7da
train
function
def _train(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=2, loss=1, momentum=0.9, resume_training=False, config=None, finetune=0): """Train netw...
def _train(dataset, trained_weights, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step, global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=2, loss=1, momentum=0.9, resume_training=False, config=None, finetune=0):
"""Train network Args: dataset: Reference to a Dataset object instance initial_ckpt: Path to the checkpoint to initialize the network (May be parent network or pre-trained Imagenet) supervison: Level of the side outputs supervision: 1-Strong 2-Weak 3-No supervision learning_rate: Value for the l...
= 0.1 vars_corresp['seg_liver/score-dsn_3/biases'] = 0.2 vars_corresp['seg_liver/score-dsn_4/weights'] = 0.1 vars_corresp['seg_liver/score-dsn_4/biases'] = 0.2 vars_corresp['seg_liver/score-dsn_5/weights'] = 0.1 vars_corresp['seg_liver/score-dsn_5/biases'] = 0.2 vars_corresp['seg_liver/upscore...
256
256
3,056
83
172
OpenVessel/liverseg-2017-nipsws
seg_liver.py
Python
_train
_train
381
645
381
382
7b905692bd4dd83b4e481dc0d211bd1aad58d314
bigcode/the-stack
train
f6d0fc2cc63f04c43a7a09b5
train
class
class ImmutableKey(Base): """A model with a unique immutable key.""" key = models.CharField(max_length=255, unique=True, verbose_name='Immutable Key', editable=False, blank=True) def _make_random_key( self, seed, ja, l, chars=string.ascii_u...
class ImmutableKey(Base):
"""A model with a unique immutable key.""" key = models.CharField(max_length=255, unique=True, verbose_name='Immutable Key', editable=False, blank=True) def _make_random_key( self, seed, ja, l, chars=string.ascii_uppercase + string.digits):...
PS: GROUP_SETTINGS = PROTOCOL_PROPS.get(GROUP) if GROUP_SETTINGS: return GROUP_SETTINGS.get(KEY, default) else: return default else: return default # TODO: Is this necessary? def save(self, *args, **kwargs): # Creat...
105
105
350
5
99
chop-dbhi/biorepo-portal
api/models/base.py
Python
ImmutableKey
ImmutableKey
61
102
61
61
3fdee66b77e0f174509bf31072c75934417bbd98
bigcode/the-stack
train
ded734fa633f7dae163aeb74
train
class
class CreatedModified(models.Model): """A model with created and modified timestamps.""" date_help_text = "Please use date format: <em>YYYY-MM-DD</em>" created = models.DateTimeField( default=timezone.now, verbose_name='Record Creation DateTime', help_text=date_help_text) modi...
class CreatedModified(models.Model):
"""A model with created and modified timestamps.""" date_help_text = "Please use date format: <em>YYYY-MM-DD</em>" created = models.DateTimeField( default=timezone.now, verbose_name='Record Creation DateTime', help_text=date_help_text) modified = AutoDateTimeField( def...
import timezone from django.conf import settings class AutoDateTimeField(models.DateTimeField): """A last-modified-style date field.""" # TODO: Why doesn't `auto_now` work here? def pre_save(self, model_instance, add): return timezone.now() class CreatedModified(models.Model):
64
64
108
6
58
chop-dbhi/biorepo-portal
api/models/base.py
Python
CreatedModified
CreatedModified
18
34
18
18
195ee623f3bdde12382e8b534d58d22c371fb1c8
bigcode/the-stack
train
e9ff1787729016440ead005b
train
class
class Base(CreatedModified): """A model that provides access to settings props.""" def _settings_prop(self, GROUP, KEY, default=None): PROTOCOL_PROPS = settings.PROTOCOL_PROPS if PROTOCOL_PROPS: GROUP_SETTINGS = PROTOCOL_PROPS.get(GROUP) if GROUP_SETTINGS: ...
class Base(CreatedModified):
"""A model that provides access to settings props.""" def _settings_prop(self, GROUP, KEY, default=None): PROTOCOL_PROPS = settings.PROTOCOL_PROPS if PROTOCOL_PROPS: GROUP_SETTINGS = PROTOCOL_PROPS.get(GROUP) if GROUP_SETTINGS: return GROUP_SETTINGS.get(K...
, verbose_name='Record Creation DateTime', help_text=date_help_text) modified = AutoDateTimeField( default=timezone.now, verbose_name='Record Last Modified DateTime', help_text=date_help_text) class Meta(object): abstract = True class Base(CreatedModified):
64
64
148
6
57
chop-dbhi/biorepo-portal
api/models/base.py
Python
Base
Base
37
58
37
37
562b5cbf07314e915ec24157a85ba9df25299518
bigcode/the-stack
train
f6ebf5fb4472e6730bd29e1e
train
class
class BaseWithImmutableKey(Base): """A timestamped model with settings access and an immutable key. The immutable_key will serve as a unique identifier for the Organization which never changes """ # TODO: Why is this a relation? immutable_key = models.OneToOneField( ImmutableKey, edita...
class BaseWithImmutableKey(Base):
"""A timestamped model with settings access and an immutable key. The immutable_key will serve as a unique identifier for the Organization which never changes """ # TODO: Why is this a relation? immutable_key = models.OneToOneField( ImmutableKey, editable=False, blank=True, unique=True...
default) def _key_length(self, default=15): return self._settings_prop('IMMUTABLE_KEYS', 'length', default) def save(self, *args, **kwargs): self._set_key() super(ImmutableKey, self).save() class BaseWithImmutableKey(Base):
64
64
207
7
57
chop-dbhi/biorepo-portal
api/models/base.py
Python
BaseWithImmutableKey
BaseWithImmutableKey
105
134
105
105
8dd21eaca295a7d963d6e1322f87fa4483ef91dd
bigcode/the-stack
train
e53fb8dff8da9b555283945e
train
class
class AutoDateTimeField(models.DateTimeField): """A last-modified-style date field.""" # TODO: Why doesn't `auto_now` work here? def pre_save(self, model_instance, add): return timezone.now()
class AutoDateTimeField(models.DateTimeField):
"""A last-modified-style date field.""" # TODO: Why doesn't `auto_now` work here? def pre_save(self, model_instance, add): return timezone.now()
import random import string from django.db import models from django.utils import timezone from django.conf import settings class AutoDateTimeField(models.DateTimeField):
34
64
49
10
23
chop-dbhi/biorepo-portal
api/models/base.py
Python
AutoDateTimeField
AutoDateTimeField
9
15
9
9
4f6dd6db2d8c11d33ed8543209a7c07f1129d05e
bigcode/the-stack
train
c58a24ff7da71cb32a3d7f9e
train
function
def validate(form): pid=form.vars.id emailid=form.vars.contact if db(db.Problems.id==pid).count()==0: form.errors.p_id="Invalid problem id.Problem doesn't exist in the database" emailid=form.vars.contact if chk.check_mail(emailid): return else: form.errors.contact = 'Inva...
def validate(form):
pid=form.vars.id emailid=form.vars.contact if db(db.Problems.id==pid).count()==0: form.errors.p_id="Invalid problem id.Problem doesn't exist in the database" emailid=form.vars.contact if chk.check_mail(emailid): return else: form.errors.contact = 'Invalid Email Address,pl...
leges.c_email): snd.send(emails.c_email,pp) def checkMail(form): emailid=form.vars.p_userid if chk.check_mail(emailid): return else: form.errors.p_userid = 'Invalid Email Address,please check your email address' def validate(form):
64
64
85
4
60
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
validate
validate
34
43
34
34
b5c165e130a485dfd48a65c5af207160fe9e71fa
bigcode/the-stack
train
335f47e8fba1bef4ce817cb7
train
function
@auth.requires_login() def upload_sol(): form=SQLFORM(db.Solutions) if form.process().accepted: #onvalidation=validate response.flash='Thank You, Your Solution Has Been Successfully Submitted' redirect(URL(r=request,f='index')) elif form.errors: response.flash='Please Check The Form...
@auth.requires_login() def upload_sol():
form=SQLFORM(db.Solutions) if form.process().accepted: #onvalidation=validate response.flash='Thank You, Your Solution Has Been Successfully Submitted' redirect(URL(r=request,f='index')) elif form.errors: response.flash='Please Check The Form Again' else: response.flash='...
: form.errors.p_id="Invalid problem id.Problem doesn't exist in the database" emailid=form.vars.contact if chk.check_mail(emailid): return else: form.errors.contact = 'Invalid Email Address,please check your email address' @auth.requires_login() def upload_sol():
64
64
86
9
55
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
upload_sol
upload_sol
46
57
46
48
8351dea9c5c6371bd19d945928f364df62447be7
bigcode/the-stack
train
a8f0c9678547f31fb7d12e70
train
function
def checkMail(form): emailid=form.vars.p_userid if chk.check_mail(emailid): return else: form.errors.p_userid = 'Invalid Email Address,please check your email address'
def checkMail(form):
emailid=form.vars.p_userid if chk.check_mail(emailid): return else: form.errors.p_userid = 'Invalid Email Address,please check your email address'
def sendMailToCollege(pp): for probs in db(db.Problems.id==pp).select(db.Problems.p_loc): for emails in db(db.Colleges.c_loc==probs.p_loc).select(db.Colleges.c_email): snd.send(emails.c_email,pp) def checkMail(form):
64
64
46
5
59
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
checkMail
checkMail
28
33
28
28
35c1625ffdbf5131d2df32b8b10426f49e63a7a3
bigcode/the-stack
train
6afec6be9c50afaf5d7e2847
train
function
def sendMailToCollege(pp): for probs in db(db.Problems.id==pp).select(db.Problems.p_loc): for emails in db(db.Colleges.c_loc==probs.p_loc).select(db.Colleges.c_email): snd.send(emails.c_email,pp)
def sendMailToCollege(pp):
for probs in db(db.Problems.id==pp).select(db.Problems.p_loc): for emails in db(db.Colleges.c_loc==probs.p_loc).select(db.Colleges.c_email): snd.send(emails.c_email,pp)
verifyMail') city=local_import('states') rnk=local_import('ranking') #!/usr/bin/env python # -*- coding: utf-8 -*- from gluon import * def stackrank(): #r_tb=db().select(db.Rankings) return locals() def sendMailToCollege(pp):
64
64
59
7
57
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
sendMailToCollege
sendMailToCollege
24
27
24
24
d591d3ae1639a1836667aa0b4925af0a7ded8cd3
bigcode/the-stack
train
44da3686ca6b523c5fd0c5a2
train
function
def upload_prob(): portal="portal" status="Pending" Prob=db.Problems(request.args(0)) pp=ids.generate_pid(request) db.Problems.p_id.default=pp form=SQLFORM(db.Problems) #snd=local_import('sendMail') dp=form.vars.loc #db.Problems.posted_on.default=request.now if form.process().acc...
def upload_prob():
portal="portal" status="Pending" Prob=db.Problems(request.args(0)) pp=ids.generate_pid(request) db.Problems.p_id.default=pp form=SQLFORM(db.Problems) #snd=local_import('sendMail') dp=form.vars.loc #db.Problems.posted_on.default=request.now if form.process().accepted: #onvalidatio...
else: constraints={'Problems':db.Problems.p_id>0} form=SQLFORM.smartgrid(db.Problems,constraints=constraints,searchable=False,sortable=True,paginate=10,headers=headers,fields=fields,selectable=None,exportclasses=export_classes,maxtextlength =64,csv=False,links=links,user_signature=True) return loc...
82
82
274
4
78
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
upload_prob
upload_prob
97
128
97
97
7b842c100d416e565201eb5c36ea34a4040b915a
bigcode/the-stack
train
64f4b38d2f4533fe2491b00d
train
function
def postMessage(): v=db(db.Slck.user_id==uid).select(db.Slck.slack_pass) sc = SlackClient(v) x=sc.api_call("chat.postMessage",name="MyChannel",text=request.vars.text) y=db(db.Col).select(db.Col.ch_id).first() x=sc.api_call("channels.history",channel=y.ch_id) db(db.Col.ch_id==y.ch_id).update(json...
def postMessage():
v=db(db.Slck.user_id==uid).select(db.Slck.slack_pass) sc = SlackClient(v) x=sc.api_call("chat.postMessage",name="MyChannel",text=request.vars.text) y=db(db.Col).select(db.Col.ch_id).first() x=sc.api_call("channels.history",channel=y.ch_id) db(db.Col.ch_id==y.ch_id).update(json_data=x)
_pass) sc = SlackClient(v) x = sc.api_call("channels.join",name="MyChannel") x=x["channel"]["id"] y = db(db.Col).select(db.Col.ch_id) if y==None: db.Col.insert(ch_id=x) def postMessage():
63
64
96
4
59
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
postMessage
postMessage
235
241
235
235
09b35285f96e65233522ba630a8dedc7daa600c3
bigcode/the-stack
train
c2b9c4e19466223907853e45
train
function
def browse_sol_admin(): export_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) sol = SQLFORM.grid(db.Solutions, showbuttontext=False,user_signature=False) return dict(sol=sol)
def browse_sol_admin():
export_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) sol = SQLFORM.grid(db.Solutions, showbuttontext=False,user_signature=False) return dict(sol=sol)
_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) prob = SQLFORM.grid(db.Problems, showbuttontext=False,user_signature=False) return dict(prob=prob) def browse_sol_admin():
64
64
66
5
59
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
browse_sol_admin
browse_sol_admin
203
208
203
203
f0522889afed76e7d2d8e8b0c70919011dba8d32
bigcode/the-stack
train
2f752b5b0cac8420927ebf1b
train
function
@service.csv @service.rss @service.xml def browse_prob_admin(): export_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) prob = SQLFORM.grid(db.Problems, showbuttontext=False,user_sign...
@service.csv @service.rss @service.xml def browse_prob_admin():
export_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) prob = SQLFORM.grid(db.Problems, showbuttontext=False,user_signature=False) return dict(prob=prob)
redirect(URL(r=request,f='superadmin')) elif form1.errors: response.flash='Please Check The Form Again' else: response.flash='Add New College Here' return dict(form1=form1) @service.csv @service.rss @service.xml def browse_prob_admin():
64
64
79
18
46
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
browse_prob_admin
browse_prob_admin
193
201
193
196
c64bf4b95060fd0082be992deabe2a842313a95b
bigcode/the-stack
train
7122e944952b62396e346629
train
function
def console(): return locals()
def console():
return locals()
by department heads. After approval by department heads solutions of problems assigned to faculty and student teams are submitted. Problem solvers can get engage with the problem givers. Courses recommended after analysis of archived data') def Contact_us(): return dict(message='I am working') def collaboration(...
64
64
7
3
61
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
console
console
221
222
221
221
d4c4ebe65db042c0653c62447331833f0bc7e747
bigcode/the-stack
train
bb3602a3f7a479952ab862ff
train
function
def collaboration(): return locals()
def collaboration():
return locals()
reported to nearby institutes and are taken by department heads. After approval by department heads solutions of problems assigned to faculty and student teams are submitted. Problem solvers can get engage with the problem givers. Courses recommended after analysis of archived data') def Contact_us(): return dict...
64
64
7
3
61
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
collaboration
collaboration
219
220
219
219
771f088eea918ccda696e5d44b4ef4d25eba09c7
bigcode/the-stack
train
81b92e255ebe8739be91b9ca
train
function
@auth.requires_login() def index(): if db.auth_user.email!=None: mail = db(db.auth_user.id == auth.user_id).select(db.auth_user.email).first() if mail.email=='knitishnitj@gmail.com' or mail.email=='setiadeepanshu@gmail.com': redirect(URL(r=request,f='browse_prob_admin')) else: ...
@auth.requires_login() def index():
if db.auth_user.email!=None: mail = db(db.auth_user.id == auth.user_id).select(db.auth_user.email).first() if mail.email=='knitishnitj@gmail.com' or mail.email=='setiadeepanshu@gmail.com': redirect(URL(r=request,f='browse_prob_admin')) else: redirect(URL(r=request,f='...
ToCollege(pp) #redirect(URL(r=request,f='index')) elif form.errors: ids.destroy_pid(request) response.flash=form.errors else: ids.destroy_pid(request) response.flash='Upload Your Problem' return locals() #def cat(): @auth.requires_login() def index():
64
64
103
8
56
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
index
index
130
139
130
131
ba2288cad1d86d07703151aa11753bac65d1186a
bigcode/the-stack
train
cb80a34e7533a9c49666aad0
train
function
def Browse_problem(): if auth.user_id!=None: locs = db(db.auth_user.id == auth.user_id).select(db.auth_user.Loc).first() export_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False...
def Browse_problem():
if auth.user_id!=None: locs = db(db.auth_user.id == auth.user_id).select(db.auth_user.Loc).first() export_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) prob=db(db.Probl...
chk.check_mail(emailid): return else: form.errors.contact = 'Invalid Email Address,please check your email address' @auth.requires_login() def upload_sol(): form=SQLFORM(db.Solutions) if form.process().accepted: #onvalidation=validate response.flash='Thank You, Your Solution Has ...
147
147
490
4
142
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
Browse_problem
Browse_problem
62
96
62
62
28c9846a8f55867327d57d533a3c3df04c2a723f
bigcode/the-stack
train
36a848093b2c405086263dda
train
function
def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://.....
def user():
""" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/def...
redirect(URL(r=request,f='browse_prob_admin')) else: redirect(URL(r=request,f='Browse_problem')) form=SQLFORM(db.Locate) return dict(form=form) def relatedsolution(): pp=db(request.args[0]==db.Problems.id).select() return locals() def user():
64
64
169
3
61
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
user
user
143
159
143
143
557e78d04b8135b172036dc9c4a06fb5a4ebf0f5
bigcode/the-stack
train
ab1f2d109bf66a87b9d2e2c6
train
function
@cache.action() def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db)
@cache.action() def download():
""" allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db)
name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users """ return dict(form=auth()) @cache.action() def download():
64
64
39
7
57
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
download
download
162
168
162
163
1be0bb95814ad34951bf542ae8e70323d1bd784e
bigcode/the-stack
train
facb219abab089a1885bad89
train
function
def Contact_us(): return dict(message='I am working')
def Contact_us():
return dict(message='I am working')
izing them in various domains i.e., departments etc. Problems reported to nearby institutes and are taken by department heads. After approval by department heads solutions of problems assigned to faculty and student teams are submitted. Problem solvers can get engage with the problem givers. Courses recommended after a...
64
64
13
4
60
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
Contact_us
Contact_us
216
217
216
216
f0d61ab389045dc9e3d777f2b2cbcebd9b10c049
bigcode/the-stack
train