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
6ea4014f5b2632b23302a7fa
train
class
class Chord(object): template_url = "https://shahinrostami.com/assets/chord/chord.tmpl" template = urllib.request.urlopen(template_url).read() def __init__( self, matrix, names, colors="d3.schemeSet1", opacity=0.8, padding=0.01, label_color="#454545",...
class Chord(object):
template_url = "https://shahinrostami.com/assets/chord/chord.tmpl" template = urllib.request.urlopen(template_url).read() def __init__( self, matrix, names, colors="d3.schemeSet1", opacity=0.8, padding=0.01, label_color="#454545", wrap_labels=...
can be saved directly to HTML files or displayed in a Jupyter Notebook output cell. Copyright 2020, Dr. Shahin Rostami http://shahinrostami.com https://github.com/shahinrostami/chord https://pypi.org/project/chord/ """ from mako.template import Template import mako.runtime import urllib.request import uuid # undef...
101
102
342
5
96
philippeitis/chord
chord/__init__.py
Python
Chord
Chord
21
76
21
21
18ef710ff18d1e2f89ec5624a7f27bad50d232e2
bigcode/the-stack
train
236d2fe8e9decedf5a32bd3e
train
function
@skip_if_no_pyarrow def test_setitem_invalid_indexer_raises(): import pyarrow as pa arr = ArrowStringArray(pa.array(list("abcde"))) with pytest.raises(IndexError, match=None): arr[5] = "foo" with pytest.raises(IndexError, match=None): arr[-6] = "foo" with pytest.raises(IndexError...
@skip_if_no_pyarrow def test_setitem_invalid_indexer_raises():
import pyarrow as pa arr = ArrowStringArray(pa.array(list("abcde"))) with pytest.raises(IndexError, match=None): arr[5] = "foo" with pytest.raises(IndexError, match=None): arr[-6] = "foo" with pytest.raises(IndexError, match=None): arr[[0, 5]] = "foo" with pytest.rai...
:]]) result = ArrowStringArray(result) expected = ArrowStringArray(expected) result[key] = value tm.assert_equal(result, expected) assert result._data.num_chunks == expected._data.num_chunks @skip_if_no_pyarrow def test_setitem_invalid_indexer_raises():
64
64
171
17
46
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_setitem_invalid_indexer_raises
test_setitem_invalid_indexer_raises
177
199
177
178
c07372fcc200f33a6aff942b0fbf4706bede1b53
bigcode/the-stack
train
0d77945c66d9ba00eaac7dfe
train
function
@skip_if_no_pyarrow def test_eq_all_na(): a = pd.array([pd.NA, pd.NA], dtype=StringDtype("pyarrow")) result = a == a expected = pd.array([pd.NA, pd.NA], dtype="boolean") tm.assert_extension_array_equal(result, expected)
@skip_if_no_pyarrow def test_eq_all_na():
a = pd.array([pd.NA, pd.NA], dtype=StringDtype("pyarrow")) result = a == a expected = pd.array([pd.NA, pd.NA], dtype="boolean") tm.assert_extension_array_equal(result, expected)
pandas.core.arrays.string_arrow import ArrowStringArray skip_if_no_pyarrow = pytest.mark.skipif( pa_version_under1p01, reason="pyarrow>=1.0.0 is required for PyArrow backed StringArray", ) @skip_if_no_pyarrow def test_eq_all_na():
64
64
71
13
51
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_eq_all_na
test_eq_all_na
22
27
22
23
0d31d00013401d832e3f9f13e31a3f0f77dfa48b
bigcode/the-stack
train
d4981d62886f2e6b027fd888
train
function
@skip_if_no_pyarrow def test_from_sequence_wrong_dtype_raises(): with pd.option_context("string_storage", "python"): ArrowStringArray._from_sequence(["a", None, "c"], dtype="string") with pd.option_context("string_storage", "pyarrow"): ArrowStringArray._from_sequence(["a", None, "c"], dtype="st...
@skip_if_no_pyarrow def test_from_sequence_wrong_dtype_raises():
with pd.option_context("string_storage", "python"): ArrowStringArray._from_sequence(["a", None, "c"], dtype="string") with pd.option_context("string_storage", "pyarrow"): ArrowStringArray._from_sequence(["a", None, "c"], dtype="string") with pytest.raises(AssertionError, match=None): ...
ed): import pyarrow as pa array = pa if array == "pyarrow" else np arr = array.array([1, 2, 3]) if chunked: if array is np: pytest.skip("chunked not applicable to numpy array") arr = pa.chunked_array(arr) if array is np: msg = "Unsupported type '<class 'numpy.nd...
155
155
518
16
139
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_from_sequence_wrong_dtype_raises
test_from_sequence_wrong_dtype_raises
71
117
71
72
cb0a2456add961fa52d02e08657b9ab09c5e6060
bigcode/the-stack
train
eb547e7615b3df5493c20e50
train
function
@pytest.mark.skipif( not pa_version_under1p01, reason="pyarrow is installed", ) def test_pyarrow_not_installed_raises(): msg = re.escape("pyarrow>=1.0.0 is required for PyArrow backed StringArray") with pytest.raises(ImportError, match=msg): StringDtype(storage="pyarrow") with pytest.raise...
@pytest.mark.skipif( not pa_version_under1p01, reason="pyarrow is installed", ) def test_pyarrow_not_installed_raises():
msg = re.escape("pyarrow>=1.0.0 is required for PyArrow backed StringArray") with pytest.raises(ImportError, match=msg): StringDtype(storage="pyarrow") with pytest.raises(ImportError, match=msg): ArrowStringArray([]) with pytest.raises(ImportError, match=msg): ArrowStringArray...
(AssertionError, match=None): StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("pyarrow")) @pytest.mark.skipif( not pa_version_under1p01, reason="pyarrow is installed", ) def test_pyarrow_not_installed_raises():
63
64
122
33
30
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_pyarrow_not_installed_raises
test_pyarrow_not_installed_raises
120
134
120
124
f0555a72fb32268088a82dc52bb8101b6084d677
bigcode/the-stack
train
9b2ab2db0d90b7fb3cff3fa0
train
function
def test_config_bad_storage_raises(): msg = re.escape("Value must be one of python|pyarrow") with pytest.raises(ValueError, match=msg): pd.options.mode.string_storage = "foo"
def test_config_bad_storage_raises():
msg = re.escape("Value must be one of python|pyarrow") with pytest.raises(ValueError, match=msg): pd.options.mode.string_storage = "foo"
_storage result = pd.array(["a", "b"]) assert result.dtype.storage == string_storage expected = ( StringDtype(string_storage).construct_array_type()._from_sequence(["a", "b"]) ) tm.assert_equal(result, expected) def test_config_bad_storage_raises():
64
64
45
8
56
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_config_bad_storage_raises
test_config_bad_storage_raises
42
45
42
42
ed19a1edb24a55016aa8667358b4f5c14a4fc1e7
bigcode/the-stack
train
2edaf573879d8608228c924c
train
function
@skip_if_no_pyarrow @pytest.mark.parametrize("multiple_chunks", [False, True]) @pytest.mark.parametrize( "key, value, expected", [ (-1, "XX", ["a", "b", "c", "d", "XX"]), (1, "XX", ["a", "XX", "c", "d", "e"]), (1, None, ["a", None, "c", "d", "e"]), (1, pd.NA, ["a", None, "c", "d"...
@skip_if_no_pyarrow @pytest.mark.parametrize("multiple_chunks", [False, True]) @pytest.mark.parametrize( "key, value, expected", [ (-1, "XX", ["a", "b", "c", "d", "XX"]), (1, "XX", ["a", "XX", "c", "d", "e"]), (1, None, ["a", None, "c", "d", "e"]), (1, pd.NA, ["a", None, "c", "d"...
import pyarrow as pa result = pa.array(list("abcde")) expected = pa.array(expected) if multiple_chunks: result = pa.chunked_array([result[:3], result[3:]]) expected = pa.chunked_array([expected[:3], expected[3:]]) result = ArrowStringArray(result) expected = ArrowStringArray(e...
@skip_if_no_pyarrow @pytest.mark.parametrize("multiple_chunks", [False, True]) @pytest.mark.parametrize( "key, value, expected", [ (-1, "XX", ["a", "b", "c", "d", "XX"]), (1, "XX", ["a", "XX", "c", "d", "e"]), (1, None, ["a", None, "c", "d", "e"]), (1, pd.NA, ["a", None, "c", "d"...
445
165
553
445
0
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_setitem
test_setitem
137
174
137
159
ce1a8450603ee35ca3647a0a9935548feb165991
bigcode/the-stack
train
de0a97bdc471a59f71a5463b
train
function
def test_config(string_storage): with pd.option_context("string_storage", string_storage): assert StringDtype().storage == string_storage result = pd.array(["a", "b"]) assert result.dtype.storage == string_storage expected = ( StringDtype(string_storage).construct_array_type()._...
def test_config(string_storage):
with pd.option_context("string_storage", string_storage): assert StringDtype().storage == string_storage result = pd.array(["a", "b"]) assert result.dtype.storage == string_storage expected = ( StringDtype(string_storage).construct_array_type()._from_sequence(["a", "b"]) ) ...
a = pd.array([pd.NA, pd.NA], dtype=StringDtype("pyarrow")) result = a == a expected = pd.array([pd.NA, pd.NA], dtype="boolean") tm.assert_extension_array_equal(result, expected) def test_config(string_storage):
64
64
83
6
58
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_config
test_config
30
39
30
30
1260c1bdec82ee071ddfa981bb5135d60910f8d3
bigcode/the-stack
train
225c9a06e7226224bde46627
train
function
@skip_if_no_pyarrow @pytest.mark.parametrize("chunked", [True, False]) @pytest.mark.parametrize("array", ["numpy", "pyarrow"]) def test_constructor_not_string_type_raises(array, chunked): import pyarrow as pa array = pa if array == "pyarrow" else np arr = array.array([1, 2, 3]) if chunked: if ...
@skip_if_no_pyarrow @pytest.mark.parametrize("chunked", [True, False]) @pytest.mark.parametrize("array", ["numpy", "pyarrow"]) def test_constructor_not_string_type_raises(array, chunked):
import pyarrow as pa array = pa if array == "pyarrow" else np arr = array.array([1, 2, 3]) if chunked: if array is np: pytest.skip("chunked not applicable to numpy array") arr = pa.chunked_array(arr) if array is np: msg = "Unsupported type '<class 'numpy.ndarray...
pytest.raises(ValueError, match=msg): pd.options.mode.string_storage = "foo" @skip_if_no_pyarrow @pytest.mark.parametrize("chunked", [True, False]) @pytest.mark.parametrize("array", ["numpy", "pyarrow"]) def test_constructor_not_string_type_raises(array, chunked):
64
64
182
45
19
luftwurzel/pandas
pandas/tests/arrays/string_/test_string_arrow.py
Python
test_constructor_not_string_type_raises
test_constructor_not_string_type_raises
48
68
48
51
b224080a31f8501d98c9819c1ebae10003e1c263
bigcode/the-stack
train
71cdb64e552b542524822a0e
train
function
def directory_in_list(directory, filenames): """Checks if any entries in the filenames list starts with the given directory.""" return any(name.startswith(directory + os.sep) or fnmatch.fnmatch(directory, name) for name in filenames)
def directory_in_list(directory, filenames):
"""Checks if any entries in the filenames list starts with the given directory.""" return any(name.startswith(directory + os.sep) or fnmatch.fnmatch(directory, name) for name in filenames)
', '['] def create_project_temp_dir(): temp_dir = tempfile.gettempdir() project_temp_dir = os.path.join(temp_dir, 'elyra') if not os.path.exists(project_temp_dir): os.mkdir(project_temp_dir) return project_temp_dir def directory_in_list(directory, filenames):
64
64
48
8
55
mudspringhiker/elyra
elyra/util/archive.py
Python
directory_in_list
directory_in_list
34
36
34
34
e5c00e921a5d38b98c051871978f619f0e3b5520
bigcode/the-stack
train
d65b0aa83d3d367bd434c70b
train
function
def create_temp_archive(archive_name, source_dir, filenames=None, recursive=False, require_complete=False): """ Create archive file with specified list of files :param archive_name: the name of the archive to be created :param source_dir: the root folder containing source files :param filenames: the...
def create_temp_archive(archive_name, source_dir, filenames=None, recursive=False, require_complete=False):
""" Create archive file with specified list of files :param archive_name: the name of the archive to be created :param source_dir: the root folder containing source files :param filenames: the list of filenames, each of which can contain wildcards and/or specify subdirectories :param recursive: ...
WILDCARDS = ['*', '?', '['] def create_project_temp_dir(): temp_dir = tempfile.gettempdir() project_temp_dir = os.path.join(temp_dir, 'elyra') if not os.path.exists(project_temp_dir): os.mkdir(project_temp_dir) return project_temp_dir def directory_in_list(directory, filenames): """Ch...
231
231
772
21
210
mudspringhiker/elyra
elyra/util/archive.py
Python
create_temp_archive
create_temp_archive
49
126
49
49
ce45df41f6bc4c7c003d5ddfe0c9e861089e45c1
bigcode/the-stack
train
89f2842e2a9786f081527c69
train
function
def create_project_temp_dir(): temp_dir = tempfile.gettempdir() project_temp_dir = os.path.join(temp_dir, 'elyra') if not os.path.exists(project_temp_dir): os.mkdir(project_temp_dir) return project_temp_dir
def create_project_temp_dir():
temp_dir = tempfile.gettempdir() project_temp_dir = os.path.join(temp_dir, 'elyra') if not os.path.exists(project_temp_dir): os.mkdir(project_temp_dir) return project_temp_dir
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import tarfile import tempfile import fnmatch WILDCARDS = ['*', '?', '['] def create_project_temp_dir():
64
64
53
6
58
mudspringhiker/elyra
elyra/util/archive.py
Python
create_project_temp_dir
create_project_temp_dir
26
31
26
26
e65b930a1c1d18c0254ddaee09c0a0c6f8a071ee
bigcode/the-stack
train
60080e832b906b0fa2cd32c8
train
function
def has_wildcards(filename): """Returns True if the filename contains wildcard characters per https://docs.python.org/3/library/fnmatch.html """ return len(set(WILDCARDS) & set(list(filename))) > 0
def has_wildcards(filename):
"""Returns True if the filename contains wildcard characters per https://docs.python.org/3/library/fnmatch.html """ return len(set(WILDCARDS) & set(list(filename))) > 0
_temp_dir) return project_temp_dir def directory_in_list(directory, filenames): """Checks if any entries in the filenames list starts with the given directory.""" return any(name.startswith(directory + os.sep) or fnmatch.fnmatch(directory, name) for name in filenames) def has_wildcards(filename):
64
64
49
7
57
mudspringhiker/elyra
elyra/util/archive.py
Python
has_wildcards
has_wildcards
39
41
39
39
e790b5e19346a3e850aff347afdb73e29c9e31b3
bigcode/the-stack
train
d0612f526c9fc79f87524b4a
train
function
def directory_prefixed(filename): """Returns True if filename is prefixed by a directory (i.e., in a sub-directory.""" return os.sep in filename and not filename.startswith(os.sep) and not filename.endswith(os.sep)
def directory_prefixed(filename):
"""Returns True if filename is prefixed by a directory (i.e., in a sub-directory.""" return os.sep in filename and not filename.startswith(os.sep) and not filename.endswith(os.sep)
(directory, name) for name in filenames) def has_wildcards(filename): """Returns True if the filename contains wildcard characters per https://docs.python.org/3/library/fnmatch.html """ return len(set(WILDCARDS) & set(list(filename))) > 0 def directory_prefixed(filename):
64
64
47
6
57
mudspringhiker/elyra
elyra/util/archive.py
Python
directory_prefixed
directory_prefixed
44
46
44
44
e8c4dd4cff7aebda48ab04a50831b4cadf1d051b
bigcode/the-stack
train
ac53dc61ab310f541bbad570
train
class
class ProcessTestCase(ResolweAPITestCase): fixtures = ['users.yaml', 'permissions.yaml', 'processes.yaml', 'collections.yaml'] def setUp(self): self.process1 = Process.objects.get(pk=1) self.post_data = { 'slug': 'new-process', 'name': 'New process', 'type':...
class ProcessTestCase(ResolweAPITestCase):
fixtures = ['users.yaml', 'permissions.yaml', 'processes.yaml', 'collections.yaml'] def setUp(self): self.process1 = Process.objects.get(pk=1) self.post_data = { 'slug': 'new-process', 'name': 'New process', 'type': 'data:test:process:', 'input_s...
# pylint: disable=missing-docstring from __future__ import absolute_import, division, print_function, unicode_literals from rest_framework import status from ..utils.test import ResolweAPITestCase from resolwe.flow.models import Collection, Process from resolwe.flow.views import ProcessViewSet class ProcessTestCase(R...
73
212
707
11
61
jkokosar/resolwe
resolwe/permissions/tests/test_tool.py
Python
ProcessTestCase
ProcessTestCase
11
85
11
11
b48f0f5ede7fce619b4a97cb8eac5d3eb76a1be1
bigcode/the-stack
train
5653cfe71192565eb6efae0b
train
class
class StatsFrameworkLogTest(test_case.TestCase, stats_framework_mock.MockMixIn): def setUp(self): super(StatsFrameworkLogTest, self).setUp() stats_framework_mock.configure(self) self.h = stats_framework.StatisticsFramework( 'test_framework', Snapshot, generate_snapshot) # pylint: disable=E021...
class StatsFrameworkLogTest(test_case.TestCase, stats_framework_mock.MockMixIn):
def setUp(self): super(StatsFrameworkLogTest, self).setUp() stats_framework_mock.configure(self) self.h = stats_framework.StatisticsFramework( 'test_framework', Snapshot, generate_snapshot) # pylint: disable=E0213 class GenerateHandler(webapp2.RequestHandler): def get(self2): ...
datetime.datetime(2010, 1, 2) self.assertEqual( ndb.Key('StatsRoot', 'test_framework', 'StatsDay', '2010-01-02'), handler.day_key(date.date())) self.assertEqual( ndb.Key( 'StatsRoot', 'test_framework', 'StatsDay', '2010-01-02', 'StatsHour', '00'), ...
256
256
2,338
17
238
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
StatsFrameworkLogTest
StatsFrameworkLogTest
317
595
317
317
dc1e271f301c8089a03416037ead2c5b92012bc3
bigcode/the-stack
train
b2c055b188bce6471627aef5
train
class
class StatsFrameworkTest(test_case.TestCase, stats_framework_mock.MockMixIn): def test_empty(self): handler = stats_framework.StatisticsFramework( 'test_framework', Snapshot, self.fail) self.assertEqual(0, stats_framework.StatsRoot.query().count()) self.assertEqual(0, handler.stats_day_cls.query(...
class StatsFrameworkTest(test_case.TestCase, stats_framework_mock.MockMixIn):
def test_empty(self): handler = stats_framework.StatisticsFramework( 'test_framework', Snapshot, self.fail) self.assertEqual(0, stats_framework.StatsRoot.query().count()) self.assertEqual(0, handler.stats_day_cls.query().count()) self.assertEqual(0, handler.stats_hour_cls.query().count()) ...
.LocalStructuredProperty(InnerSnapshot) d = ndb.StringProperty(repeated=True) def __init__(self, **kwargs): # This is the recommended way to use ndb.LocalStructuredProperty inside a # snapshot. # # Warning: The only reason it works is because Snapshot is itself inside a # ndb.LocalStructuredPro...
256
256
1,907
16
240
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
StatsFrameworkTest
StatsFrameworkTest
70
305
70
70
0960e46b1ee5df08131ad42f4d6f692e817e6ee9
bigcode/the-stack
train
8b3febc6235a711d43b546c9
train
function
def generate_snapshot(start_time, end_time): values = Snapshot() for entry in stats_framework.yield_entries(start_time, end_time): values.requests += 1 for l in entry.entries: values.inner.c += l return values
def generate_snapshot(start_time, end_time):
values = Snapshot() for entry in stats_framework.yield_entries(start_time, end_time): values.requests += 1 for l in entry.entries: values.inner.c += l return values
', '00', 'StatsMinute', '00'), handler.minute_key(date)) def test_yield_empty(self): self.testbed.init_modules_stub() self.assertEqual( 0, len(list(stats_framework.yield_entries(None, None)))) def generate_snapshot(start_time, end_time):
63
64
54
9
54
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
generate_snapshot
generate_snapshot
308
314
308
308
d01e4e70ad73fdaa7a8a87d52283e55fc343e424
bigcode/the-stack
train
4e9c3cd1729cc43a699a31d2
train
function
def get_now(): """Returns an hard coded 'utcnow'. It is important because the timestamp near the hour or day limit could induce the creation of additional 'hours' stats, which would make the test flaky. """ return datetime.datetime(2010, 1, 2, 3, 4, 5, 6)
def get_now():
"""Returns an hard coded 'utcnow'. It is important because the timestamp near the hour or day limit could induce the creation of additional 'hours' stats, which would make the test flaky. """ return datetime.datetime(2010, 1, 2, 3, 4, 5, 6)
.LocalStructuredProperty. kwargs.setdefault('inner', InnerSnapshot()) super(Snapshot, self).__init__(**kwargs) def accumulate(self, rhs): # accumulate() specifically handles where default value is a class instance. return stats_framework.accumulate(self, rhs, ['d']) def get_now():
63
64
75
4
59
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
get_now
get_now
56
62
56
56
97bd5f7433c7a4eb3eff42f5305e0da54eec0a9a
bigcode/the-stack
train
4a49efcdb76daf31264ff109
train
class
class Snapshot(ndb.Model): """Fake statistics.""" requests = ndb.IntegerProperty(default=0, indexed=False) b = ndb.FloatProperty(default=0, indexed=False) inner = ndb.LocalStructuredProperty(InnerSnapshot) d = ndb.StringProperty(repeated=True) def __init__(self, **kwargs): # This is the recommended way...
class Snapshot(ndb.Model):
"""Fake statistics.""" requests = ndb.IntegerProperty(default=0, indexed=False) b = ndb.FloatProperty(default=0, indexed=False) inner = ndb.LocalStructuredProperty(InnerSnapshot) d = ndb.StringProperty(repeated=True) def __init__(self, **kwargs): # This is the recommended way to use ndb.LocalStructured...
import stats_framework_mock from test_support import test_case # pylint: disable=W0212 class InnerSnapshot(ndb.Model): c = ndb.StringProperty(default='', indexed=False) def accumulate(self, rhs): return stats_framework.accumulate(self, rhs, []) class Snapshot(ndb.Model):
63
64
175
6
57
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
Snapshot
Snapshot
35
53
35
35
526b203092ace7ab6ff2575c142625c1a4512cde
bigcode/the-stack
train
31612150bc20de3590a523d1
train
class
class InnerSnapshot(ndb.Model): c = ndb.StringProperty(default='', indexed=False) def accumulate(self, rhs): return stats_framework.accumulate(self, rhs, [])
class InnerSnapshot(ndb.Model):
c = ndb.StringProperty(default='', indexed=False) def accumulate(self, rhs): return stats_framework.accumulate(self, rhs, [])
_env.setup_test_env() from google.appengine.ext import ndb import webapp2 import webtest from components import stats_framework from components import utils from test_support import stats_framework_mock from test_support import test_case # pylint: disable=W0212 class InnerSnapshot(ndb.Model):
64
64
37
7
56
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
InnerSnapshot
InnerSnapshot
28
32
28
28
591a8bcdc42ef2e07361af97bf1ecf64567bfe61
bigcode/the-stack
train
afd1be9c52c3cdf0d0ebb07d
train
function
def strip_seconds(timestamp): """Returns timestamp with seconds and microseconds stripped.""" return datetime.datetime(*timestamp.timetuple()[:5], second=0)
def strip_seconds(timestamp):
"""Returns timestamp with seconds and microseconds stripped.""" return datetime.datetime(*timestamp.timetuple()[:5], second=0)
is important because the timestamp near the hour or day limit could induce the creation of additional 'hours' stats, which would make the test flaky. """ return datetime.datetime(2010, 1, 2, 3, 4, 5, 6) def strip_seconds(timestamp):
64
64
33
5
59
stefb965/luci-py
appengine/components/components/stats_framework_test.py
Python
strip_seconds
strip_seconds
65
67
65
65
0b459be489a23f3593215b2fd7f516f0a46910df
bigcode/the-stack
train
4c246e7a55b9d5174a9d184b
train
class
class Augmentator(): def __init__(self, ratio_val, invratio_val, cross_val): self.ratio_val = ratio_val self.invratio_val = invratio_val self.cross_val = cross_val self.min_inv_len = 3 self.dict_list_val = ['./dataset/Panlex/dict/es2.txt'] idx_dict = util.convert.Com...
class Augmentator():
def __init__(self, ratio_val, invratio_val, cross_val): self.ratio_val = ratio_val self.invratio_val = invratio_val self.cross_val = cross_val self.min_inv_len = 3 self.dict_list_val = ['./dataset/Panlex/dict/es2.txt'] idx_dict = util.convert.Common.to_args({"src2tgt...
import yaml import re import random import pandas as pd import numpy as np import util.tool import util.data import util.convert from svo_extraction.subject_verb_object_extract import findSVOs, get_spacy_nlp_sm_model, invertSentence class Augmentator():
62
144
483
5
56
kelvinchanwh/fyp-CoSDA-ML
augmentator_covid.py
Python
Augmentator
Augmentator
11
64
11
11
cc965d0ed1ed9472ae469658ca067a05a60867a4
bigcode/the-stack
train
7e89f2f1b7594d22fdce29bc
train
class
class SequentialAlgorithm(Algorithm): def __init__(self, initial: Result, algorithms_cls: Sequence[Tuple[Type[Algorithm], Dict[str, Any]]] = None, seed: int = 56, *args, **kwargs): super().__init__(*args, **kwargs) if algorithms_cls is None: from .iterative import Iter...
class SequentialAlgorithm(Algorithm):
def __init__(self, initial: Result, algorithms_cls: Sequence[Tuple[Type[Algorithm], Dict[str, Any]]] = None, seed: int = 56, *args, **kwargs): super().__init__(*args, **kwargs) if algorithms_cls is None: from .iterative import IterativeAlgorithm from ..heuri...
import annotations import logging from random import Random from typing import TYPE_CHECKING from ...models import ( Planning, MAX_INT, ) from ..abc import ( Algorithm, ) if TYPE_CHECKING: from ...models import ( Result, ) from typing import ( Dict, Any, Seque...
92
92
308
6
86
PhilippeGalvan/jinete
jinete/algorithms/metaheuristics/sequential.py
Python
SequentialAlgorithm
SequentialAlgorithm
30
67
30
31
5f836e6ea9b4b83cbf64be2cff7b03d0a72c2c90
bigcode/the-stack
train
fcfa3e99fcae090334db005e
train
function
def load(annotation_type, fixed_positions=None): # Define cropped positions CROPPED_IMAGE_HEIGHT = 80 CROPPED_IMAGE_WIDTH = CROPPED_IMAGE_HEIGHT * 4 // 5 cropped_image_size = (CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH) cropped_positions = legacy_default_cropping(cropped_image_size, annotation_type)...
def load(annotation_type, fixed_positions=None): # Define cropped positions
CROPPED_IMAGE_HEIGHT = 80 CROPPED_IMAGE_WIDTH = CROPPED_IMAGE_HEIGHT * 4 // 5 cropped_image_size = (CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH) cropped_positions = legacy_default_cropping(cropped_image_size, annotation_type) # Cropping face_cropper, transform_extra_arguments = make_cropper( ...
import wrap import tempfile from bob.bio.base.transformers import AlgorithmTransformer from bob.pipelines.transformers import SampleLinearize import os import logging logger = logging.getLogger(__name__) #### SOLVING IF THERE'S ANY DATABASE INFORMATION annotation_type, fixed_positions, memory_demanding = lookup_con...
105
105
352
15
90
bioidiap/bob.bio.face
bob/bio/face/config/baseline/lda.py
Python
load
load
31
79
31
33
7c2c69937e4768507a21765803f42d830914cb91
bigcode/the-stack
train
e5f0c4d557432332da8338cc
train
function
def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, is_plot=True, lambd=0, keep_prob=1): """ 实现一个三层的神经网络:LINEAR ->RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID 参数: X - 输入的数据,维度为(2, 要训练/测试的数量) Y - 标签,【0(蓝色) | 1(红色)】,维度为(1,对应的是输入的数据的标签) learning_rate - 学习速率 ...
def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, is_plot=True, lambd=0, keep_prob=1):
""" 实现一个三层的神经网络:LINEAR ->RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID 参数: X - 输入的数据,维度为(2, 要训练/测试的数量) Y - 标签,【0(蓝色) | 1(红色)】,维度为(1,对应的是输入的数据的标签) learning_rate - 学习速率 num_iterations - 迭代的次数 print_cost - 是否打印成本值,每迭代10000次打印一次,但是每1000次记录一个成本值 is_polt - 是否绘制梯度下降的曲...
_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig # 获取准确性评估,将A转为Y_hat并与Y进行比较,返回准确率 # input: # A : np.array(1,m) # Y : np.array(1,m) # output: # accuracy (float) def getAccuracy(A, Y): # 获取总样本数 A_dummy = A.copy() ...
249
249
830
37
211
TimVan1596/datasetX
test/test_datasetx.py
Python
model
model
46
130
46
46
10d6b52d500322634d10310ac7f7f1e2786e8c7a
bigcode/the-stack
train
11b595739ddba72dbc4a9c1f
train
function
def compute_cost_with_regularization(A3, Y, parameters, lambd): """ 实现公式2的L2正则化计算成本 参数: A3 - 正向传播的输出结果,维度为(输出节点数量,训练/测试的数量) Y - 标签向量,与数据一一对应,维度为(输出节点数量,训练/测试的数量) parameters - 包含模型学习后的参数的字典 返回: cost - 使用公式2计算出来的正则化损失的值 """ m = Y.shape[1] W1 = parameters["W1"]...
def compute_cost_with_regularization(A3, Y, parameters, lambd):
""" 实现公式2的L2正则化计算成本 参数: A3 - 正向传播的输出结果,维度为(输出节点数量,训练/测试的数量) Y - 标签向量,与数据一一对应,维度为(输出节点数量,训练/测试的数量) parameters - 包含模型学习后的参数的字典 返回: cost - 使用公式2计算出来的正则化损失的值 """ m = Y.shape[1] W1 = parameters["W1"] W2 = parameters["W2"] W3 = parameters["W3"] cross_...
: plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (x1,000)') plt.title("Learning rate =" + str(learning_rate)) plt.show() # 返回学习后的参数 return parameters def compute_cost_with_regularization(A3, Y, parameters, lambd):
68
68
228
16
51
TimVan1596/datasetX
test/test_datasetx.py
Python
compute_cost_with_regularization
compute_cost_with_regularization
133
157
133
133
6048fe06f08ed74a86f6af492baa055e762ec117
bigcode/the-stack
train
0554152210ba78592f6ac99d
train
function
def getAccuracy(A, Y): # 获取总样本数 A_dummy = A.copy() m = A_dummy.shape[1] for i in range(0, A_dummy.shape[1]): if A_dummy[0, i] > 0.5: A_dummy[0, i] = 1 else: A_dummy[0, i] = 0 a = float(np.sum((A_dummy == Y))) accuracy = float(np.sum((A_dummy == Y))) * 100 ...
def getAccuracy(A, Y): # 获取总样本数
A_dummy = A.copy() m = A_dummy.shape[1] for i in range(0, A_dummy.shape[1]): if A_dummy[0, i] > 0.5: A_dummy[0, i] = 1 else: A_dummy[0, i] = 0 a = float(np.sum((A_dummy == Y))) accuracy = float(np.sum((A_dummy == Y))) * 100 / m return accuracy
准确性评估,将A转为Y_hat并与Y进行比较,返回准确率 # input: # A : np.array(1,m) # Y : np.array(1,m) # output: # accuracy (float) def getAccuracy(A, Y): # 获取总样本数
64
64
121
15
49
TimVan1596/datasetX
test/test_datasetx.py
Python
getAccuracy
getAccuracy
32
43
32
33
cf790a54c1e34a93c6ef4071872cf3670baafa62
bigcode/the-stack
train
e0207107b5bfc7650751660e
train
function
def load_dataset(path): train_dataset = h5py.File(path + '/train.h5', "r") train_set_x_orig = np.array(train_dataset["x"][:]) # your train set features train_set_y_orig = np.array(train_dataset["y"][:]) # your train set labels test_dataset = h5py.File(path + '/test.h5', "r") test_set_x_orig = np....
def load_dataset(path):
train_dataset = h5py.File(path + '/train.h5', "r") train_set_x_orig = np.array(train_dataset["x"][:]) # your train set features train_set_y_orig = np.array(train_dataset["y"][:]) # your train set labels test_dataset = h5py.File(path + '/test.h5', "r") test_set_x_orig = np.array(test_dataset["x"][...
import h5py import numpy as np import init_utils # 第一部分,初始化 import reg_utils # 第二部分,正则化 import gc_utils # 第三部分,梯度校验 import matplotlib.pyplot as plt def load_dataset(path):
57
64
216
5
51
TimVan1596/datasetX
test/test_datasetx.py
Python
load_dataset
load_dataset
9
23
9
9
6d5ee7a6eb77bc1821951841f75846cb48ae40d6
bigcode/the-stack
train
6ecd3b8c53f4a749bfc2bbb9
train
function
def backward_propagation_with_regularization(X, Y, cache, lambd): """ 实现我们添加了L2正则化的模型的后向传播。 参数: X - 输入数据集,维度为(输入节点数量,数据集里面的数量) Y - 标签,维度为(输出节点数量,数据集里面的数量) cache - 来自forward_propagation()的cache输出 lambda - regularization超参数,实数 返回: gradients - 一个包含了每个参数、激活值和预激活值变量的...
def backward_propagation_with_regularization(X, Y, cache, lambd):
""" 实现我们添加了L2正则化的模型的后向传播。 参数: X - 输入数据集,维度为(输入节点数量,数据集里面的数量) Y - 标签,维度为(输出节点数量,数据集里面的数量) cache - 来自forward_propagation()的cache输出 lambda - regularization超参数,实数 返回: gradients - 一个包含了每个参数、激活值和预激活值变量的梯度的字典 """ m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2...
值 """ m = Y.shape[1] W1 = parameters["W1"] W2 = parameters["W2"] W3 = parameters["W3"] cross_entropy_cost = reg_utils.compute_cost(A3, Y) L2_regularization_cost = lambd * (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3))) / (2 * m...
161
161
537
17
144
TimVan1596/datasetX
test/test_datasetx.py
Python
backward_propagation_with_regularization
backward_propagation_with_regularization
162
199
162
162
965744cde72832bcdde2af31a4f4adfe3cfdf14f
bigcode/the-stack
train
3e17f9ffd1a911802a9b4f98
train
function
def backward_propagation_with_dropout(X, Y, cache, keep_prob): """ 实现我们随机删除的模型的后向传播。 参数: X - 输入数据集,维度为(2,示例数) Y - 标签,维度为(输出节点数量,示例数量) cache - 来自forward_propagation_with_dropout()的cache输出 keep_prob - 随机删除的概率,实数 返回: gradients - 一个关于每个参数、激活值和预激活变量的梯度值的字典 """ ...
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
""" 实现我们随机删除的模型的后向传播。 参数: X - 输入数据集,维度为(2,示例数) Y - 标签,维度为(输出节点数量,示例数量) cache - 来自forward_propagation_with_dropout()的cache输出 keep_prob - 随机删除的概率,实数 返回: gradients - 一个关于每个参数、激活值和预激活变量的梯度值的字典 """ m = X.shape[1] (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2,...
...) D2 = D2 < keep_prob # 步骤2:将D2的值转换为0或1(使​​用keep_prob作为阈值) A2 = A2 * D2 # 步骤3:舍弃A1的一些节点(将它的值变为0或False) A2 = A2 / keep_prob # 步骤4:缩放未舍弃的节点(不为0)的值 Z3 = np.dot(W3, A2) + b3 A3 = reg_utils.sigmoid(Z3) cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) return A3, cache def...
199
199
666
16
182
TimVan1596/datasetX
test/test_datasetx.py
Python
backward_propagation_with_dropout
backward_propagation_with_dropout
277
317
277
277
85169986b76380a4db2fdc5ff2d6a839de56b81d
bigcode/the-stack
train
9dffb7a13273dd03382c0bd9
train
function
def forward_propagation(x, theta): """ 实现图中呈现的线性前向传播(计算J)(J(theta)= theta * x) 参数: x - 一个实值输入 theta - 参数,也是一个实数 返回: J - 函数J的值,用公式J(theta)= theta * x计算 """ J = np.dot(theta, x) return J
def forward_propagation(x, theta):
""" 实现图中呈现的线性前向传播(计算J)(J(theta)= theta * x) 参数: x - 一个实值输入 theta - 参数,也是一个实数 返回: J - 函数J的值,用公式J(theta)= theta * x计算 """ J = np.dot(theta, x) return J
"dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients def forward_propagation(x, theta):
64
64
99
9
54
TimVan1596/datasetX
test/test_datasetx.py
Python
forward_propagation
forward_propagation
320
334
320
320
1fad7b1082a7a9c895b5ce828b120925de9a07ba
bigcode/the-stack
train
1aed805ce6c8f033e2b9af1b
train
function
def backward_propagation(x, theta): """ 计算J相对于θ的导数。 参数: x - 一个实值输入 theta - 参数,也是一个实数 返回: dtheta - 相对于θ的成本梯度 """ dtheta = x return dtheta
def backward_propagation(x, theta):
""" 计算J相对于θ的导数。 参数: x - 一个实值输入 theta - 参数,也是一个实数 返回: dtheta - 相对于θ的成本梯度 """ dtheta = x return dtheta
一个实值输入 theta - 参数,也是一个实数 返回: J - 函数J的值,用公式J(theta)= theta * x计算 """ J = np.dot(theta, x) return J def backward_propagation(x, theta):
64
64
73
9
54
TimVan1596/datasetX
test/test_datasetx.py
Python
backward_propagation
backward_propagation
337
350
337
337
38fde4dc918b54d305e7b0567c587d0f79c91743
bigcode/the-stack
train
1ca397a122f5ffa96ee467ba
train
function
def forward_propagation_with_dropout(X, parameters, keep_prob=0.5): """ 实现具有随机舍弃节点的前向传播。 LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID. 参数: X - 输入数据集,维度为(2,示例数) parameters - 包含参数“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典: W1 - 权重矩阵,维度为(20,2) ...
def forward_propagation_with_dropout(X, parameters, keep_prob=0.5):
""" 实现具有随机舍弃节点的前向传播。 LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID. 参数: X - 输入数据集,维度为(2,示例数) parameters - 包含参数“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典: W1 - 权重矩阵,维度为(20,2) b1 - 偏向量,维度为(20,1) W2 - 权重矩阵,维度为(3,20) ...
, A1.T) + ((lambd * W2) / m) db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = (1 / m) * np.dot(dZ1, X.T) + ((lambd * W1) / m) db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True) gradients = {"dZ3": dZ3, "dW3": dW3, "db3": ...
256
256
952
18
237
TimVan1596/datasetX
test/test_datasetx.py
Python
forward_propagation_with_dropout
forward_propagation_with_dropout
203
274
203
203
1deb20e4f19eadac9a83a8359506a4599fa3926a
bigcode/the-stack
train
ed0626aa3cf73f0580221341
train
class
class FirmwareAnalysisForm(forms.ModelForm): class Meta: model = models.FirmwareAnalysis fields = ('firmware', 'version', 'vendor', 'device', 'notes', 'firmware_Architecture', 'cwe_checker', 'dev_mode', 'deep_extraction', 'log_path', 'grep_able_log', 'relative_paths', 'ANSI...
class FirmwareAnalysisForm(forms.ModelForm):
class Meta: model = models.FirmwareAnalysis fields = ('firmware', 'version', 'vendor', 'device', 'notes', 'firmware_Architecture', 'cwe_checker', 'dev_mode', 'deep_extraction', 'log_path', 'grep_able_log', 'relative_paths', 'ANSI_color', 'web_reporter', 'emu...
# pylint: disable=E1101 import logging import django from django import forms from uploader import models logger = logging.getLogger('web') class FirmwareAnalysisForm(forms.ModelForm):
41
105
350
8
33
BenediktMKuehne/embark
embark/uploader/forms.py
Python
FirmwareAnalysisForm
FirmwareAnalysisForm
11
49
11
12
bc2b95fecfc3c15347a458efd65b9ff453c913cc
bigcode/the-stack
train
9dbdba0794643e7b2bfc413a
train
class
class DeleteFirmwareForm(forms.Form): firmware = forms.ModelChoiceField(queryset=models.FirmwareFile.objects, empty_label='Select firmware-file to delete')
class DeleteFirmwareForm(forms.Form):
firmware = forms.ModelChoiceField(queryset=models.FirmwareFile.objects, empty_label='Select firmware-file to delete')
= field.field.expert_mode except Exception as error: logger.info("Exception passed: %s", error) # pass self.base_fields['firmware'] = forms.ModelChoiceField(queryset=models.FirmwareFile.objects, empty_label='Select firmware') class DeleteFirmwareForm(forms.Form...
63
64
31
7
56
BenediktMKuehne/embark
embark/uploader/forms.py
Python
DeleteFirmwareForm
DeleteFirmwareForm
52
53
52
52
e4b22708ded4de7e084b13956066a62c9192c65e
bigcode/the-stack
train
01b3563b0ced7529e24a404d
train
class
class LoadCase: """ A unique Load case defines a set of simulation analysis conditions and a set of boundary conditions to apply to the domain. The default and initial timestep provide an estimate for the solver should be specified along with the total duration of the load case using :meth:`setTimeStep...
class LoadCase:
""" A unique Load case defines a set of simulation analysis conditions and a set of boundary conditions to apply to the domain. The default and initial timestep provide an estimate for the solver should be specified along with the total duration of the load case using :meth:`setTimeStep`. The analysis ...
import numpy as np import abc import os from enum import Enum, auto from typing import List, Tuple, Type from ..bc import BoundaryCondition, BoundaryConditionType from ..results import Result class LoadCaseType(Enum): """ Enum Class specifies the Load Case Type """ STATIC = auto() """Linear Sta...
163
256
1,946
4
159
drlukeparry/pyccx
pyccx/loadcase/loadcase.py
Python
LoadCase
LoadCase
31
248
31
31
b4b7fc04f2f4ae45781e6e38a7f9f3f7deb141ae
bigcode/the-stack
train
31d0d46a42c3e9dedfb0b758
train
class
class LoadCaseType(Enum): """ Enum Class specifies the Load Case Type """ STATIC = auto() """Linear Static structural analysis""" THERMAL = auto() """Thermal analysis for performing heat transfer studies""" UNCOUPLEDTHERMOMECHANICAL = auto() """Coupled thermo-mechanical analysis""" ...
class LoadCaseType(Enum):
""" Enum Class specifies the Load Case Type """ STATIC = auto() """Linear Static structural analysis""" THERMAL = auto() """Thermal analysis for performing heat transfer studies""" UNCOUPLEDTHERMOMECHANICAL = auto() """Coupled thermo-mechanical analysis""" BUCKLE = auto() ""...
import numpy as np import abc import os from enum import Enum, auto from typing import List, Tuple, Type from ..bc import BoundaryCondition, BoundaryConditionType from ..results import Result class LoadCaseType(Enum):
50
64
115
6
43
drlukeparry/pyccx
pyccx/loadcase/loadcase.py
Python
LoadCaseType
LoadCaseType
12
28
12
12
fa87df164a2ac795614bc7881f07a86be0b25788
bigcode/the-stack
train
ab45941917d26f996991a922
train
class
class RS_Simulator(TS_Simulator): def __init__(self, user_input): TS_Simulator.__init__(self,user_input) def load_stellar_spectra(self): selection = self.user_input["Star"]["Spectra"]["selection"] filename = self.user_input["Star"]["Spectra"]["filename"] ...
class RS_Simulator(TS_Simulator):
def __init__(self, user_input): TS_Simulator.__init__(self,user_input) def load_stellar_spectra(self): selection = self.user_input["Star"]["Spectra"]["selection"] filename = self.user_input["Star"]["Spectra"]["filename"] orbit = utils.to_float(self.us...
MultipleLocator(10) import SEAS_Main.atmosphere_geometry import SEAS_Main.atmosphere_property from SEAS_Main.atmosphere_effects.biosig_molecule import load_NIST_spectra, biosig_interpolate from transmission_spectra_simulator import TS_Simulator from SEAS_Aux.calculation.interpolation import interpolate1d import SEAS...
215
215
719
10
204
zhuchangzhan/SEAS
deprecated/simulation/reflection_spectra_simulator.py
Python
RS_Simulator
RS_Simulator
65
152
65
66
e836f8bf5e62e555fe04d1e1dcebf112a0a1accf
bigcode/the-stack
train
6976ee13456f8438a3d6ecbb
train
function
def _run(command, error_message): runner = utils.LocalCommandRunner(logger=ctx.logger) try: runner.run(command) except exceptions.CommandExecutionException as e: raise exceptions.NonRecoverableError('{0}: {1}'.format(error_message, e))
def _run(command, error_message):
runner = utils.LocalCommandRunner(logger=ctx.logger) try: runner.run(command) except exceptions.CommandExecutionException as e: raise exceptions.NonRecoverableError('{0}: {1}'.format(error_message, e))
: raise def start(): _service('start') def stop(): _service('stop') def _service(state): _run('sudo service haproxy {0}'.format(state), error_message='Failed setting state to {0}'.format(state)) def _run(command, error_message):
64
64
56
8
56
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
_run
_run
110
115
110
110
96845bbc284ea4fbed8dba1bbd50a72921b676c8
bigcode/the-stack
train
da1de5c983c5a9480509c2f8
train
function
@contextmanager def _backends_update(): backends = ctx.target.instance.runtime_properties.get('backends', {}) yield backends ctx.target.instance.runtime_properties['backends'] = backends # being explict because errors in unlink are ignored and # not retried without being explicit. # also, this w...
@contextmanager def _backends_update():
backends = ctx.target.instance.runtime_properties.get('backends', {}) yield backends ctx.target.instance.runtime_properties['backends'] = backends # being explict because errors in unlink are ignored and # not retried without being explicit. # also, this way, we make sure that configure/reload ...
'address': backend_address or ctx.source.instance.host_ip, 'port': port, 'maxconn': maxconn } def remove_backend(): with _backends_update() as backends: backends.pop(ctx.source.instance.id, None) @contextmanager def _backends_update():
64
64
174
10
54
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
_backends_update
_backends_update
74
94
74
75
53af6b8af45c69a75f69e7957a68dfeb87ce654d
bigcode/the-stack
train
a67fc564ab45dd9a3f4cd5c8
train
function
def start(): _service('start')
def start():
_service('start')
') except rest_exceptions.CloudifyClientError as e: if 'conflict' in str(e): # cannot 'return' in contextmanager ctx.operation.retry( message='Backends updated concurrently, retrying.', retry_after=1) else: raise def start():
64
64
9
3
60
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
start
start
97
98
97
97
01795cb574138e9c5da14f653a4c5f80b81d9022
bigcode/the-stack
train
e9977206d9c4a109421ac2df
train
function
def remove_backend(): with _backends_update() as backends: backends.pop(ctx.source.instance.id, None)
def remove_backend():
with _backends_update() as backends: backends.pop(ctx.source.instance.id, None)
(port, maxconn, backend_address=None): with _backends_update() as backends: backends[ctx.source.instance.id] = { 'address': backend_address or ctx.source.instance.host_ip, 'port': port, 'maxconn': maxconn } def remove_backend():
64
64
26
4
60
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
remove_backend
remove_backend
69
71
69
69
6bad54e2afaf6fbdcde60d5d481d52eb27ae4c64
bigcode/the-stack
train
7f40167d413da62012462fc0
train
function
def stop(): _service('stop')
def stop():
_service('stop')
Error as e: if 'conflict' in str(e): # cannot 'return' in contextmanager ctx.operation.retry( message='Backends updated concurrently, retrying.', retry_after=1) else: raise def start(): _service('start') def stop():
64
64
9
3
61
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
stop
stop
101
102
101
101
6a275ce8b6765f53722fbd4f0404deafafac7f17
bigcode/the-stack
train
3342160325317a709ed030a5
train
function
def add_backend(port, maxconn, backend_address=None): with _backends_update() as backends: backends[ctx.source.instance.id] = { 'address': backend_address or ctx.source.instance.host_ip, 'port': port, 'maxconn': maxconn }
def add_backend(port, maxconn, backend_address=None):
with _backends_update() as backends: backends[ctx.source.instance.id] = { 'address': backend_address or ctx.source.instance.host_ip, 'port': port, 'maxconn': maxconn }
-c'.format(temp_config.name), error_message='Failed to Configure') _run('sudo mv {0} {1}'.format(temp_config.name, CONFIG_PATH), error_message='Failed to write to {0}.'.format(CONFIG_PATH)) def add_backend(port, maxconn, backend_address=None):
64
64
63
12
52
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
add_backend
add_backend
60
66
60
60
960e0800a4944896da795af98fba8337b6ba8fb2
bigcode/the-stack
train
2a126a4f8956d075113c4426
train
function
def _service(state): _run('sudo service haproxy {0}'.format(state), error_message='Failed setting state to {0}'.format(state))
def _service(state):
_run('sudo service haproxy {0}'.format(state), error_message='Failed setting state to {0}'.format(state))
str(e): # cannot 'return' in contextmanager ctx.operation.retry( message='Backends updated concurrently, retrying.', retry_after=1) else: raise def start(): _service('start') def stop(): _service('stop') def _service(state):
64
64
34
5
59
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
_service
_service
105
107
105
105
a45ef005d032407ca43770e27a2bf90e23dafdaf
bigcode/the-stack
train
5f41047126fc37c5cced4e66
train
function
def _main(): invocation = inputs['invocation'] function = invocation['function'] args = invocation.get('args', []) kwargs = invocation.get('kwargs', {}) globals()[function](*args, **kwargs)
def _main():
invocation = inputs['invocation'] function = invocation['function'] args = invocation.get('args', []) kwargs = invocation.get('kwargs', {}) globals()[function](*args, **kwargs)
}'.format(state)) def _run(command, error_message): runner = utils.LocalCommandRunner(logger=ctx.logger) try: runner.run(command) except exceptions.CommandExecutionException as e: raise exceptions.NonRecoverableError('{0}: {1}'.format(error_message, e)) def _main():
64
64
48
4
60
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
_main
_main
118
123
118
118
20a04d5921a66bb069d3852aa73e89549ec43507
bigcode/the-stack
train
b09d6bb863425841ef663d78
train
function
def configure(subject=None): subject = subject or ctx ctx.logger.info('Configuring HAProxy.') template = Template(ctx.get_resource(TEMPLATE_RESOURCE_NAME)) ctx.logger.debug('Building a dict object that will contain variables ' 'to write to the Jinja2 template.') config = subj...
def configure(subject=None):
subject = subject or ctx ctx.logger.info('Configuring HAProxy.') template = Template(ctx.get_resource(TEMPLATE_RESOURCE_NAME)) ctx.logger.debug('Building a dict object that will contain variables ' 'to write to the Jinja2 template.') config = subject.node.properties.copy() ...
rest_exceptions from cloudify import ctx from cloudify.state import ctx_parameters as inputs from cloudify import exceptions from cloudify import utils CONFIG_PATH = '/etc/haproxy/haproxy.cfg' TEMPLATE_RESOURCE_NAME = 'resources/haproxy/haproxy.cfg.template' def configure(subject=None):
66
66
221
5
61
screwgoth/nodecellar-auto-scale-auto-heal-blueprint
scripts/haproxy/haproxy.py
Python
configure
configure
33
57
33
33
6ece8a6d0d6ee69225d43d8b09092c3f4de63f22
bigcode/the-stack
train
a8baed2bfdb62a620902c815
train
class
class ModelSummaryMode(LightningEnum): # TODO: remove in v1.6 (as `mode` would be deprecated for `max_depth`) """Define the Model Summary mode to be used. Can be one of - `top`: only the top-level modules will be recorded (the children of the root module) - `full`: summarizes all layers and...
class ModelSummaryMode(LightningEnum): # TODO: remove in v1.6 (as `mode` would be deprecated for `max_depth`)
"""Define the Model Summary mode to be used. Can be one of - `top`: only the top-level modules will be recorded (the children of the root module) - `full`: summarizes all layers and their submodules in the root module >>> # you can match the type with string >>> ModelSummaryMode.TOP ==...
ClipAlgorithmType] class AutoRestartBatchKeys(LightningEnum): """Defines special dictionary keys used to track captured dataset state with multiple workers.""" PL_RESTART_META = "__pl_restart_meta" class ModelSummaryMode(LightningEnum): # TODO: remove in v1.6 (as `mode` would be deprecated for `max_depth...
73
73
244
32
41
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
ModelSummaryMode
ModelSummaryMode
202
231
202
203
416780e7282579df30dad9896355ac2503313331
bigcode/the-stack
train
0c0f86622100fba3ac4a6a62
train
class
class GradClipAlgorithmType(LightningEnum): """Define gradient_clip_algorithm types - training-tricks. NORM type means "clipping gradients by norm". This computed over all model parameters together. VALUE type means "clipping gradients by value". This will clip the gradient value for each parameter. Re...
class GradClipAlgorithmType(LightningEnum):
"""Define gradient_clip_algorithm types - training-tricks. NORM type means "clipping gradients by norm". This computed over all model parameters together. VALUE type means "clipping gradients by value". This will clip the gradient value for each parameter. References: clip_by_norm: https://pyto...
precate(self) -> None: rank_zero_deprecation( "`DeviceType` Enum has been deprecated in v1.6 and will be removed in v1.8." f" Use the string value `{self.value!r}` instead." ) class GradClipAlgorithmType(LightningEnum):
64
64
185
10
54
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
GradClipAlgorithmType
GradClipAlgorithmType
174
193
174
174
94abfd328dbb41d8066e25b09fd32a9501a333ee
bigcode/the-stack
train
9e32bb060c823908f7430b4b
train
class
class AutoRestartBatchKeys(LightningEnum): """Defines special dictionary keys used to track captured dataset state with multiple workers.""" PL_RESTART_META = "__pl_restart_meta"
class AutoRestartBatchKeys(LightningEnum):
"""Defines special dictionary keys used to track captured dataset state with multiple workers.""" PL_RESTART_META = "__pl_restart_meta"
staticmethod def supported_type(val: str) -> bool: return any(x.value == val for x in GradClipAlgorithmType) @staticmethod def supported_types() -> list[str]: return [x.value for x in GradClipAlgorithmType] class AutoRestartBatchKeys(LightningEnum):
64
64
37
10
54
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
AutoRestartBatchKeys
AutoRestartBatchKeys
196
199
196
196
4220efac61a9b8d20ebc0d160c0985ca1ce868ec
bigcode/the-stack
train
33ae599422757a9686a955f0
train
class
class _AcceleratorType(LightningEnum): """Define Accelerator type by its nature. >>> _AcceleratorType.CPU == _AcceleratorType.from_str('cpu') True >>> # you can match the type with string >>> _AcceleratorType.GPU == 'GPU' True >>> # which is case invariant >>> _AcceleratorType.TPU in ('...
class _AcceleratorType(LightningEnum):
"""Define Accelerator type by its nature. >>> _AcceleratorType.CPU == _AcceleratorType.from_str('cpu') True >>> # you can match the type with string >>> _AcceleratorType.GPU == 'GPU' True >>> # which is case invariant >>> _AcceleratorType.TPU in ('tpu', 'CPU') True """ CPU ...
[ _StrategyType.DP, _StrategyType.TPU_SPAWN, ] def is_interactive_compatible(self) -> bool: """Returns whether self is interactive compatible.""" return self in _StrategyType.interactive_compatible_types() class _AcceleratorType(LightningEnum):
64
64
130
10
54
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
_AcceleratorType
_AcceleratorType
271
288
271
271
89ceb651f697cdd0e56647b0ecfaebe0d18eb2d5
bigcode/the-stack
train
078bf91c9ea967a649add95b
train
class
class PrecisionType(LightningEnum): """Type of precision used. >>> PrecisionType.HALF == 16 True >>> PrecisionType.HALF in (16, "16") True """ HALF = "16" FLOAT = "32" FULL = "64" BFLOAT = "bf16" MIXED = "mixed" @staticmethod def supported_type(precision: str | int...
class PrecisionType(LightningEnum):
"""Type of precision used. >>> PrecisionType.HALF == 16 True >>> PrecisionType.HALF in (16, "16") True """ HALF = "16" FLOAT = "32" FULL = "64" BFLOAT = "bf16" MIXED = "mixed" @staticmethod def supported_type(precision: str | int) -> bool: return any(x == p...
Enum): """Type of Automatic Mixed Precission used for training. >>> # you can match the type with string >>> AMPType.APEX == 'apex' True """ APEX = "apex" NATIVE = "native" class PrecisionType(LightningEnum):
64
64
135
8
56
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
PrecisionType
PrecisionType
89
110
89
89
5a75e6319c499a8be2b77869b5ab2737c9cecbf2
bigcode/the-stack
train
2f30ba258da0ee494d8fb2cc
train
class
class LightningEnum(str, Enum): """Type of any enumerator with allowed comparison to string invariant to cases.""" @classmethod def from_str(cls, value: str) -> LightningEnum | None: statuses = cls.__members__.keys() for st in statuses: if st.lower() == value.lower(): ...
class LightningEnum(str, Enum):
"""Type of any enumerator with allowed comparison to string invariant to cases.""" @classmethod def from_str(cls, value: str) -> LightningEnum | None: statuses = cls.__members__.keys() for st in statuses: if st.lower() == value.lower(): return cls[st] ret...
the License. """Enumerated utilities.""" from __future__ import annotations import os from enum import Enum, EnumMeta from typing import Any from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.warnings import rank_zero_deprecation class LightningEnum(str, Enu...
64
64
163
7
56
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
LightningEnum
LightningEnum
25
43
25
25
86428a7056566997438e1b71b45175bd84dd0184
bigcode/the-stack
train
4d700a56ac669c34530e6c45
train
class
class AMPType(LightningEnum): """Type of Automatic Mixed Precission used for training. >>> # you can match the type with string >>> AMPType.APEX == 'apex' True """ APEX = "apex" NATIVE = "native"
class AMPType(LightningEnum):
"""Type of Automatic Mixed Precission used for training. >>> # you can match the type with string >>> AMPType.APEX == 'apex' True """ APEX = "apex" NATIVE = "native"
) if isinstance(obj, Enum): obj.deprecate() return obj class _DeprecatedEnum(LightningEnum, metaclass=_DeprecatedEnumMeta): """_DeprecatedEnum calls an enum's `deprecate()` method on member access.""" pass class AMPType(LightningEnum):
64
64
62
8
55
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
AMPType
AMPType
77
86
77
77
0666830d09f21c9c5214154685374181cf3b41cf
bigcode/the-stack
train
985ad789c0d56549215cc167
train
class
class _DeprecatedEnumMeta(EnumMeta): """Enum that calls `deprecate()` whenever a member is accessed. Adapted from: https://stackoverflow.com/a/62309159/208880 """ def __getattribute__(cls, name: str) -> Any: obj = super().__getattribute__(name) # ignore __dunder__ names -- prevents pot...
class _DeprecatedEnumMeta(EnumMeta):
"""Enum that calls `deprecate()` whenever a member is accessed. Adapted from: https://stackoverflow.com/a/62309159/208880 """ def __getattribute__(cls, name: str) -> Any: obj = super().__getattribute__(name) # ignore __dunder__ names -- prevents potential recursion errors if no...
return self.value.lower() == other.lower() def __hash__(self) -> int: # re-enable hashtable so it can be used as a dict key or in a set # example: set(LightningEnum) return hash(self.value.lower()) class _DeprecatedEnumMeta(EnumMeta):
64
64
199
8
56
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
_DeprecatedEnumMeta
_DeprecatedEnumMeta
46
68
46
46
9d2d93b42470326fcaa3e4d7b4dedf45907278e5
bigcode/the-stack
train
4ba32f65fbfb3c7953a638e8
train
class
class DeviceType(_DeprecatedEnum): """Define Device type by its nature - accelerators. Deprecated since v1.6.0 and will be removed in v1.8.0. Use `_AcceleratorType` instead. """ CPU = "CPU" GPU = "GPU" IPU = "IPU" TPU = "TPU" def deprecate(self) -> None: rank_zero_depreca...
class DeviceType(_DeprecatedEnum):
"""Define Device type by its nature - accelerators. Deprecated since v1.6.0 and will be removed in v1.8.0. Use `_AcceleratorType` instead. """ CPU = "CPU" GPU = "GPU" IPU = "IPU" TPU = "TPU" def deprecate(self) -> None: rank_zero_deprecation( "`DeviceType` Enu...
def deprecate(self) -> None: rank_zero_deprecation( "`DistributedType` Enum has been deprecated in v1.6 and will be removed in v1.8." f" Use the string value `{self.value!r}` instead." ) class DeviceType(_DeprecatedEnum):
64
64
135
7
57
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
DeviceType
DeviceType
154
171
154
154
4058b7a6d59e0ccdaecaf3a5260e87982ad3e290
bigcode/the-stack
train
2d6770e84be01199770c8f81
train
class
class _DeprecatedEnum(LightningEnum, metaclass=_DeprecatedEnumMeta): """_DeprecatedEnum calls an enum's `deprecate()` method on member access.""" pass
class _DeprecatedEnum(LightningEnum, metaclass=_DeprecatedEnumMeta):
"""_DeprecatedEnum calls an enum's `deprecate()` method on member access.""" pass
def __call__(cls, *args: Any, **kwargs: Any) -> Any: obj = super().__call__(*args, **kwargs) if isinstance(obj, Enum): obj.deprecate() return obj class _DeprecatedEnum(LightningEnum, metaclass=_DeprecatedEnumMeta):
64
64
38
16
47
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
_DeprecatedEnum
_DeprecatedEnum
71
74
71
71
f06bfd20bea0292d7f14c2b0dddd6593f7f583d5
bigcode/the-stack
train
f291b3eb2d13682f4559dc09
train
class
class _FaultTolerantMode(LightningEnum): DISABLED = "disabled" AUTOMATIC = "automatic" MANUAL = "manual" @property def is_enabled(self) -> bool: return self is not _FaultTolerantMode.DISABLED @property def is_automatic(self) -> bool: return self is _FaultTolerantMode.AUTOM...
class _FaultTolerantMode(LightningEnum):
DISABLED = "disabled" AUTOMATIC = "automatic" MANUAL = "manual" @property def is_enabled(self) -> bool: return self is not _FaultTolerantMode.DISABLED @property def is_automatic(self) -> bool: return self is _FaultTolerantMode.AUTOMATIC @property def is_manual(self...
with string >>> _AcceleratorType.GPU == 'GPU' True >>> # which is case invariant >>> _AcceleratorType.TPU in ('tpu', 'CPU') True """ CPU = "CPU" GPU = "GPU" IPU = "IPU" TPU = "TPU" HPU = "HPU" class _FaultTolerantMode(LightningEnum):
94
94
316
12
82
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
_FaultTolerantMode
_FaultTolerantMode
291
322
291
292
cc8aedf60ab9f875506fd3d2746544c4c44914e1
bigcode/the-stack
train
4958c6a9c3214a3aa91db6db
train
class
class DistributedType(_DeprecatedEnum): """Define type of training strategy. Deprecated since v1.6.0 and will be removed in v1.8.0. Use `_StrategyType` instead. """ DP = "dp" DDP = "ddp" DDP2 = "ddp2" DDP_SPAWN = "ddp_spawn" TPU_SPAWN = "tpu_spawn" DEEPSPEED = "deepspeed" ...
class DistributedType(_DeprecatedEnum):
"""Define type of training strategy. Deprecated since v1.6.0 and will be removed in v1.8.0. Use `_StrategyType` instead. """ DP = "dp" DDP = "ddp" DDP2 = "ddp2" DDP_SPAWN = "ddp_spawn" TPU_SPAWN = "tpu_spawn" DEEPSPEED = "deepspeed" HOROVOD = "horovod" DDP_SHARDED = "d...
True """ HALF = "16" FLOAT = "32" FULL = "64" BFLOAT = "bf16" MIXED = "mixed" @staticmethod def supported_type(precision: str | int) -> bool: return any(x == precision for x in PrecisionType) @staticmethod def supported_types() -> list[str]: return [x.value...
99
99
332
7
92
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
DistributedType
DistributedType
113
151
113
113
8104348a792b158d80cd833b21b0e89655ed5c49
bigcode/the-stack
train
6b09725679c34c17d261b55d
train
class
class _StrategyType(LightningEnum): """Define type of training strategy. >>> # you can match the type with string >>> _StrategyType.DDP == 'ddp' True >>> # which is case invariant >>> _StrategyType.DDP2 in ('ddp2', ) True """ DP = "dp" DDP = "ddp" DDP2 = "ddp2" DDP_SPAW...
class _StrategyType(LightningEnum):
"""Define type of training strategy. >>> # you can match the type with string >>> _StrategyType.DDP == 'ddp' True >>> # which is case invariant >>> _StrategyType.DDP2 in ('ddp2', ) True """ DP = "dp" DDP = "ddp" DDP2 = "ddp2" DDP_SPAWN = "ddp_spawn" TPU_SPAWN = "tpu...
if mode == ModelSummaryMode.TOP: return 1 if mode == ModelSummaryMode.FULL: return -1 raise ValueError(f"`mode` can be {', '.join(list(ModelSummaryMode))}, got {mode}.") @staticmethod def supported_types() -> list[str]: return [x.value for x in ModelSummaryMode]...
87
87
290
9
78
mathemusician/pytorch-lightning
pytorch_lightning/utilities/enums.py
Python
_StrategyType
_StrategyType
234
268
234
234
d067dbb25635058ff2d9add5960c2082cf0913b8
bigcode/the-stack
train
e8db99bd929fdd7ca0f0ece2
train
function
def get_all_columns(df): if df is None: return [] elif isinstance(df, pd.DataFrame): return df.columns.tolist() elif isinstance(df, pd.core.groupby.groupby.DataFrameGroupBy): # TODO: We need to exclude key columns which are used for gropuing return df.obj.columns.tolist() ...
def get_all_columns(df):
if df is None: return [] elif isinstance(df, pd.DataFrame): return df.columns.tolist() elif isinstance(df, pd.core.groupby.groupby.DataFrameGroupBy): # TODO: We need to exclude key columns which are used for gropuing return df.obj.columns.tolist() else: return Non...
.__getattr__(col) col_exists = True except: pass if col_exists: out.append(col) else: log.warning("Column '{0}' cannot be found. Skip column.".format(str(col))) return out return result def get_all_columns(...
64
64
76
6
57
asavinov/lambdo
lambdo/utils.py
Python
get_all_columns
get_all_columns
185
194
185
185
0b6715fcdffb807614349750f93a5590758460aa
bigcode/the-stack
train
7191ee86c6c8fbb1697f5147
train
function
def read_value_from_file(link): """Read Python object from the specified URI treated as a local file.""" is_json = link.lower().endswith('json') is_pkl = link.lower().endswith('pkl') pathname = get_filename_from_uri(link) ret = None if is_pkl: if not os.path.exists(pathname): ...
def read_value_from_file(link):
"""Read Python object from the specified URI treated as a local file.""" is_json = link.lower().endswith('json') is_pkl = link.lower().endswith('pkl') pathname = get_filename_from_uri(link) ret = None if is_pkl: if not os.path.exists(pathname): # Having no file means that a ...
*result[1:]).geturl() except: return None elif uri.startswith('file:/'): return uri[len('file:/'):] elif uri.startswith('file:'): return uri[len('file:'):] else: return uri def read_value_from_file(link):
64
64
205
7
56
asavinov/lambdo
lambdo/utils.py
Python
read_value_from_file
read_value_from_file
61
87
61
61
2581b09e3902644ec90493c51bfaa8b349c1a645
bigcode/the-stack
train
bd982f51ec4f8c8835df791e
train
function
def apply_row_filter(data, row_filter): """Select rows from the specified data frame which satisfy the provided row filter and return the result.""" # # Column(s) with NaN as a predicate # drop_cols = row_filter.get("dropna") if isinstance(drop_cols, bool) and drop_cols is True: data.dr...
def apply_row_filter(data, row_filter):
"""Select rows from the specified data frame which satisfy the provided row filter and return the result.""" # # Column(s) with NaN as a predicate # drop_cols = row_filter.get("dropna") if isinstance(drop_cols, bool) and drop_cols is True: data.dropna(inplace=True) elif isinstance(d...
.""" if not isinstance(ref, str): return if not ref.startswith('$'): return # Now we know that the location is a reference link = ref[1:] # Check if it is URL or workflow variable if is_valid_uri(link): is_file = link.lower().startswith('file:') if is_file: ...
133
133
446
9
123
asavinov/lambdo
lambdo/utils.py
Python
apply_row_filter
apply_row_filter
266
320
266
266
3d07f7912d5bdf4dfd1106415fa3b3e709d269f3
bigcode/the-stack
train
a4385a43d3c670757d338a10
train
function
def get_filename_from_uri(uri): """Get local file name given URI.""" if uri.startswith('file://'): try: result = urllib.parse.urlparse(uri) return urllib.parse.ParseResult('', *result[1:]).geturl() except: return None elif uri.startswith('file:/'): ...
def get_filename_from_uri(uri):
"""Get local file name given URI.""" if uri.startswith('file://'): try: result = urllib.parse.urlparse(uri) return urllib.parse.ParseResult('', *result[1:]).geturl() except: return None elif uri.startswith('file:/'): return uri[len('file:/'):] ...
_uri(uri): """Determine if the string is a valid URL. We use it to distringuish links from workflow variables.""" try: result = urllib.parse.urlparse(uri) return result.scheme and result.path except Exception as e: return False def get_filename_from_uri(uri):
64
64
100
7
56
asavinov/lambdo
lambdo/utils.py
Python
get_filename_from_uri
get_filename_from_uri
46
59
46
46
c31805150576288f667a64a20cf9753990a80813
bigcode/the-stack
train
05fad1acdb1c150a205f2699
train
function
def set_value(ref, value): """If the value is a reference then write it to the referenced location.""" if not isinstance(ref, str): return if not ref.startswith('$'): return # Now we know that the location is a reference link = ref[1:] # Check if it is URL or workflow variab...
def set_value(ref, value):
"""If the value is a reference then write it to the referenced location.""" if not isinstance(ref, str): return if not ref.startswith('$'): return # Now we know that the location is a reference link = ref[1:] # Check if it is URL or workflow variable if is_valid_uri(link...
if is_file: value = read_value_from_file(link) else: log.error("Reading values from URI is not implemented.") return None else: log.error("Reading values from workflow variables is not implemented.") return None return value def set_value(ref...
64
64
146
7
56
asavinov/lambdo
lambdo/utils.py
Python
set_value
set_value
239
264
239
239
d269f1852f952ce7f74698fd244c3d4c6cec14df
bigcode/the-stack
train
1df584ee3defca626769f7bc
train
function
def build_json_extensions(definition_json): """ Produce all concrete definitions by imposing extensions onto the base definition. Extensions produced are copies. :return: List of concrete definitions. In the case of no extensions, only the base definition is returned. """ base = definition_json....
def build_json_extensions(definition_json):
""" Produce all concrete definitions by imposing extensions onto the base definition. Extensions produced are copies. :return: List of concrete definitions. In the case of no extensions, only the base definition is returned. """ base = definition_json.copy() exts = definition_json.get('exten...
__author__="Alexandr Savinov" import os import pickle import urllib.parse import pandas as pd import logging log = logging.getLogger('lambdo.utils') def build_json_extensions(definition_json):
47
64
174
8
39
asavinov/lambdo
lambdo/utils.py
Python
build_json_extensions
build_json_extensions
13
36
13
13
7f3721e62a42c4c50026f80ecdc8f398006f4845
bigcode/the-stack
train
7c5a4ecdb35d00fa23611474
train
function
def is_valid_uri(uri): """Determine if the string is a valid URL. We use it to distringuish links from workflow variables.""" try: result = urllib.parse.urlparse(uri) return result.scheme and result.path except Exception as e: return False
def is_valid_uri(uri):
"""Determine if the string is a valid URL. We use it to distringuish links from workflow variables.""" try: result = urllib.parse.urlparse(uri) return result.scheme and result.path except Exception as e: return False
# Make copy del e['extensions'] # Remove extensions # Generate id if not explicitly specified if not ext.get('id'): e['id'] = e['id'] + "_" + str(i) result.append(e) return result def is_valid_uri(uri):
64
64
60
6
57
asavinov/lambdo
lambdo/utils.py
Python
is_valid_uri
is_valid_uri
38
44
38
38
24f5a182893742966d19f7722a8aec128364e102
bigcode/the-stack
train
323331ec6239a2a68358a3be
train
function
def get_columns(names, df=None): """Produce a list of column names by also validating them against the data frame.""" result = [] if isinstance(names, str): # A single column name result.append(names) elif isinstance(names, int) and df is not None: # A single column number result.app...
def get_columns(names, df=None):
"""Produce a list of column names by also validating them against the data frame.""" result = [] if isinstance(names, str): # A single column name result.append(names) elif isinstance(names, int) and df is not None: # A single column number result.append(df.columns[names]) elif ...
treated as a local file.""" is_json = link.lower().endswith('json') is_pkl = link.lower().endswith('pkl') pathname = get_filename_from_uri(link) if is_pkl: try: with open(pathname, 'wb') as file: try: pickle.dump(value, file) exce...
156
156
520
8
147
asavinov/lambdo
lambdo/utils.py
Python
get_columns
get_columns
111
183
111
111
561ff0ee51868a0cc407c83d395cb3d217421e7d
bigcode/the-stack
train
7b15a3cab87f0354e421deb1
train
function
def all_columns_exist(names, df): all_columns_available = True for col in names: if col not in df.columns: all_columns_available = False log.warning("Column '{0}' is not available.".format(col)) break if not all_columns_available: return False return T...
def all_columns_exist(names, df):
all_columns_available = True for col in names: if col not in df.columns: all_columns_available = False log.warning("Column '{0}' is not available.".format(col)) break if not all_columns_available: return False return True
pd.DataFrame): return df.columns.tolist() elif isinstance(df, pd.core.groupby.groupby.DataFrameGroupBy): # TODO: We need to exclude key columns which are used for gropuing return df.obj.columns.tolist() else: return None def all_columns_exist(names, df):
64
64
69
8
55
asavinov/lambdo
lambdo/utils.py
Python
all_columns_exist
all_columns_exist
196
205
196
196
bb24650efaf393123313c62f026eddc7c5fd9d96
bigcode/the-stack
train
c90a5e45a3629b1b499d2910
train
function
def get_value(ref): """If the value is a reference then de-reference it and return. Otherwise, return this input value.""" if not isinstance(ref, str): return ref if not ref.startswith('$'): return ref # Now we know that the value is a reference link = ref[1:] # De-reference...
def get_value(ref):
"""If the value is a reference then de-reference it and return. Otherwise, return this input value.""" if not isinstance(ref, str): return ref if not ref.startswith('$'): return ref # Now we know that the value is a reference link = ref[1:] # De-reference depending on the li...
_columns_available = True for col in names: if col not in df.columns: all_columns_available = False log.warning("Column '{0}' is not available.".format(col)) break if not all_columns_available: return False return True def get_value(ref):
64
64
171
5
58
asavinov/lambdo
lambdo/utils.py
Python
get_value
get_value
207
237
207
207
6374733e5bd94a1bbd18a613fc29553e62a94a2e
bigcode/the-stack
train
21375f103fda5c9c472ce4a1
train
function
def write_value_to_file(link, value): """Write Python object to the specified URI treated as a local file.""" is_json = link.lower().endswith('json') is_pkl = link.lower().endswith('pkl') pathname = get_filename_from_uri(link) if is_pkl: try: with open(pathname, 'wb') as file: ...
def write_value_to_file(link, value):
"""Write Python object to the specified URI treated as a local file.""" is_json = link.lower().endswith('json') is_pkl = link.lower().endswith('pkl') pathname = get_filename_from_uri(link) if is_pkl: try: with open(pathname, 'wb') as file: try: ...
return None except IOError as e: log.warning("Error reading from file {0}. Exception: {1}".format(pathname, e)) return None elif is_json: return None else: return None return ret def write_value_to_file(link, value):
64
64
166
9
54
asavinov/lambdo
lambdo/utils.py
Python
write_value_to_file
write_value_to_file
89
109
89
89
ba0773a954150ac172c5612a15cb6c21de3a38e1
bigcode/the-stack
train
0c08ab798fcb8f54b480453b
train
class
class UNet(nn.Module): def __init__(self, labelclassMap, in_channels=3, depth=5, numFeaturesExponent=6, batch_norm=False, upsamplingMode='upconv'): super(UNet, self).__init__() self.labelclassMap = labelclassMap self.in_channels = in_channels self.depth = depth self.numFeatur...
class UNet(nn.Module):
def __init__(self, labelclassMap, in_channels=3, depth=5, numFeaturesExponent=6, batch_norm=False, upsamplingMode='upconv'): super(UNet, self).__init__() self.labelclassMap = labelclassMap self.in_channels = in_channels self.depth = depth self.numFeaturesExponent = numFeature...
''' U-Net implementation in PyTorch (Ronneberger et al., 2015). Adapted from 2019 Joris van Vugt (source: https://raw.githubusercontent.com/jvanvugt/pytorch-unet/master/unet.py). 2020 Benjamin Kellenberger ''' import torch import torch.nn as nn import torch.nn.functional as F class UNet(nn.Module):
85
256
1,585
6
78
bkellenb/aerial_wildlife_detection_mee_2020
ai/models/pytorch/functional/segmentationMasks/unet.py
Python
UNet
UNet
14
179
14
14
806604e321c8cea07067577ea049624d9a456f8a
bigcode/the-stack
train
049287ef6e9cd955fdbbd4cd
train
class
class UNetConvBlock(nn.Module): def __init__(self, in_size, out_size, padding, batch_norm): super(UNetConvBlock, self).__init__() block = [] block.append(nn.Conv2d(in_size, out_size, kernel_size=3, padding=int(padding))) block.append(nn.ReLU()) if batch_norm: bl...
class UNetConvBlock(nn.Module):
def __init__(self, in_size, out_size, padding, batch_norm): super(UNetConvBlock, self).__init__() block = [] block.append(nn.Conv2d(in_size, out_size, kernel_size=3, padding=int(padding))) block.append(nn.ReLU()) if batch_norm: block.append(nn.BatchNorm2d(out_siz...
(self.down_path) - 1: blocks.append(x) x = F.max_pool2d(x, 2) for i, up in enumerate(self.up_path): x = up(x, blocks[-i - 1]) return self.last(x) class UNetConvBlock(nn.Module):
64
64
161
8
56
bkellenb/aerial_wildlife_detection_mee_2020
ai/models/pytorch/functional/segmentationMasks/unet.py
Python
UNetConvBlock
UNetConvBlock
183
204
183
184
a5b39ec2100162ff9227764d833d91de8e1ac944
bigcode/the-stack
train
eb8e2f20f3bbc77cf71718f4
train
class
class UNetUpBlock(nn.Module): def __init__(self, in_size, out_size, up_mode, padding, batch_norm): super(UNetUpBlock, self).__init__() if up_mode == 'upconv': self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=2, stride=2) elif up_mode == 'upsample': self.up...
class UNetUpBlock(nn.Module):
def __init__(self, in_size, out_size, up_mode, padding, batch_norm): super(UNetUpBlock, self).__init__() if up_mode == 'upconv': self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=2, stride=2) elif up_mode == 'upsample': self.up = nn.Sequential( ...
Norm2d(out_size)) block.append(nn.Conv2d(out_size, out_size, kernel_size=3, padding=int(padding))) block.append(nn.ReLU()) if batch_norm: block.append(nn.BatchNorm2d(out_size)) self.block = nn.Sequential(*block) def forward(self, x): out = self.block(x) ...
87
87
290
8
78
bkellenb/aerial_wildlife_detection_mee_2020
ai/models/pytorch/functional/segmentationMasks/unet.py
Python
UNetUpBlock
UNetUpBlock
208
238
208
209
8b5d9d371807708cb6179a8f52c1c3684e8ae2a7
bigcode/the-stack
train
f7814a71585228c59e0cb9bd
train
function
def swipe(adb_path: str, x1: int, y1: int, x2: int, y2: int, duration: int) -> None: subprocess.call(f'{adb_path} shell input swipe {x1} {y1} {x2} {y2} {duration}', shell=True)
def swipe(adb_path: str, x1: int, y1: int, x2: int, y2: int, duration: int) -> None:
subprocess.call(f'{adb_path} shell input swipe {x1} {y1} {x2} {y2} {duration}', shell=True)
np_arr = numpy.frombuffer(image_bytes, numpy.uint8) return cv2.imdecode(np_arr, cv2.IMREAD_COLOR) def swipe(adb_path: str, x1: int, y1: int, x2: int, y2: int, duration: int) -> None:
64
64
68
35
29
legnaleurc/libpcrd
pcrd/adb.py
Python
swipe
swipe
15
16
15
15
8e726cf11256aebbd82473a545add80c50e77247
bigcode/the-stack
train
b67b44794e151a7b7b706097
train
function
def grab_screenshot(adb_path: str) -> numpy.ndarray: with subprocess.Popen(f'{adb_path} shell screencap -p', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) as pipe: image_bytes = pipe.stdout.read().replace(b'\r\n', b'\n') np_arr = numpy.frombuffer(image_bytes, numpy.uint8) return cv2.imd...
def grab_screenshot(adb_path: str) -> numpy.ndarray:
with subprocess.Popen(f'{adb_path} shell screencap -p', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) as pipe: image_bytes = pipe.stdout.read().replace(b'\r\n', b'\n') np_arr = numpy.frombuffer(image_bytes, numpy.uint8) return cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
import subprocess import time import cv2 import numpy def grab_screenshot(adb_path: str) -> numpy.ndarray:
27
64
91
14
12
legnaleurc/libpcrd
pcrd/adb.py
Python
grab_screenshot
grab_screenshot
8
12
8
8
0bad9bab42b7d3ba3f6dff42323b347085fa5dbf
bigcode/the-stack
train
ee46f3822bd198ceeb38bc56
train
function
def scrolled_to_bottom(scroll_bar_color: tuple[int, int, int]) -> bool: SCROLL_BAR_COLOR = (191, 123, 88) return get_color_diff(scroll_bar_color, SCROLL_BAR_COLOR) < 200
def scrolled_to_bottom(scroll_bar_color: tuple[int, int, int]) -> bool:
SCROLL_BAR_COLOR = (191, 123, 88) return get_color_diff(scroll_bar_color, SCROLL_BAR_COLOR) < 200
0 power = [2, 4, 3] for i in range(3): ret += power[i] * (a[i] - b[i]) ** 2 return ret def scrolled_to_bottom(scroll_bar_color: tuple[int, int, int]) -> bool:
64
64
52
19
44
legnaleurc/libpcrd
pcrd/adb.py
Python
scrolled_to_bottom
scrolled_to_bottom
35
37
35
35
16588be833ec32f9980f7c7dac9582d5bcdea064
bigcode/the-stack
train
ce28c1d5fdc820433c1e4a24
train
function
def grab_input(input_folder: str, adb_path: str) -> None: coordinates = None scroll_bar_bottom_point = None idx = 0 while True: img = grab_screenshot(adb_path) if not coordinates: h, w, _ = img.shape coordinates = get_coordinates(h, w) scroll_bar_botto...
def grab_input(input_folder: str, adb_path: str) -> None:
coordinates = None scroll_bar_bottom_point = None idx = 0 while True: img = grab_screenshot(adb_path) if not coordinates: h, w, _ = img.shape coordinates = get_coordinates(h, w) scroll_bar_bottom_point = get_bottom_point(h, w) cv2.imwrite(f'{in...
_bottom(scroll_bar_color: tuple[int, int, int]) -> bool: SCROLL_BAR_COLOR = (191, 123, 88) return get_color_diff(scroll_bar_color, SCROLL_BAR_COLOR) < 200 def grab_input(input_folder: str, adb_path: str) -> None:
64
64
143
16
47
legnaleurc/libpcrd
pcrd/adb.py
Python
grab_input
grab_input
40
55
40
40
17f600fdcc888ef6ace36912adf683908f386225
bigcode/the-stack
train
2f6773bfee7d8e0b6620c667
train
function
def get_coordinates(h: int, w: int) -> tuple[int, int, int, int]: return w // 2, 3 * h // 4, w // 2, int(h // 3.5)
def get_coordinates(h: int, w: int) -> tuple[int, int, int, int]:
return w // 2, 3 * h // 4, w // 2, int(h // 3.5)
: int, duration: int) -> None: subprocess.call(f'{adb_path} shell input swipe {x1} {y1} {x2} {y2} {duration}', shell=True) def get_coordinates(h: int, w: int) -> tuple[int, int, int, int]:
64
64
49
21
43
legnaleurc/libpcrd
pcrd/adb.py
Python
get_coordinates
get_coordinates
19
20
19
19
0c0b75e025867ed2b99269d64095cdf31e6ffc5c
bigcode/the-stack
train
ac2743356cdc74d3c2c4aeee
train
function
def get_bottom_point(h: int, w: int) -> tuple[int, int]: return 749 * h // 900, 977 * w // 1600
def get_bottom_point(h: int, w: int) -> tuple[int, int]:
return 749 * h // 900, 977 * w // 1600
(h: int, w: int) -> tuple[int, int, int, int]: return w // 2, 3 * h // 4, w // 2, int(h // 3.5) def get_bottom_point(h: int, w: int) -> tuple[int, int]:
64
64
37
18
46
legnaleurc/libpcrd
pcrd/adb.py
Python
get_bottom_point
get_bottom_point
23
24
23
23
c15064c97836379227d1596e889753a88520920a
bigcode/the-stack
train
dbbc1cc267d8c8e8d43e6991
train
function
def get_color_diff(a: tuple[int, int, int], b: tuple[int, int, int]) -> int: ret = 0 power = [2, 4, 3] for i in range(3): ret += power[i] * (a[i] - b[i]) ** 2 return ret
def get_color_diff(a: tuple[int, int, int], b: tuple[int, int, int]) -> int:
ret = 0 power = [2, 4, 3] for i in range(3): ret += power[i] * (a[i] - b[i]) ** 2 return ret
5) def get_bottom_point(h: int, w: int) -> tuple[int, int]: return 749 * h // 900, 977 * w // 1600 def get_color_diff(a: tuple[int, int, int], b: tuple[int, int, int]) -> int:
64
64
74
25
38
legnaleurc/libpcrd
pcrd/adb.py
Python
get_color_diff
get_color_diff
27
32
27
27
7ecee534bbbb2db116d53357738f75d9a65729cc
bigcode/the-stack
train
2c5ecac2a53a3d829ca23d6f
train
function
def my_grep(line, term): if line.startswith(term): yield line
def my_grep(line, term):
if line.startswith(term): yield line
in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import apache_beam as beam def my_grep(line, term):
64
64
18
8
55
memeyankm/training-data-analyst
courses/data_analysis/lab2/python/grepc.py
Python
my_grep
my_grep
18
20
18
18
1569590731a4956f1ab55fd868df110174e5922a
bigcode/the-stack
train
d99c88036880102bc1d86479
train
function
def run(): argv = [ '--project={0}'.format(PROJECT), '--job_name=examplejob2', '--save_main_session', '--staging_location=gs://{0}/staging/'.format(BUCKET), '--temp_location=gs://{0}/staging/'.format(BUCKET), '--region=us-central1', '--runner=DataflowRunner' ] p = bea...
def run():
argv = [ '--project={0}'.format(PROJECT), '--job_name=examplejob2', '--save_main_session', '--staging_location=gs://{0}/staging/'.format(BUCKET), '--temp_location=gs://{0}/staging/'.format(BUCKET), '--region=us-central1', '--runner=DataflowRunner' ] p = beam.Pipeline(...
express or implied. See the License for the specific language governing permissions and limitations under the License. """ import apache_beam as beam def my_grep(line, term): if line.startswith(term): yield line PROJECT='cloud-training-demos' BUCKET='cloud-training-demos' def run():
64
64
213
3
61
memeyankm/training-data-analyst
courses/data_analysis/lab2/python/grepc.py
Python
run
run
25
48
25
25
1ca9ac83fbc75d92fac258110fe455cc43406544
bigcode/the-stack
train
db96d2ae4cb889c6ccc60a48
train
class
class InstallRequirement: """ Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. """ def __init__( self, req, # type: Optional[Requirement]...
class InstallRequirement:
""" Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. """ def __init__( self, req, # type: Optional[Requirement] comes_from, # ty...
, Union from pip._vendor.packaging.markers import Marker from pip._vendor.packaging.specifiers import SpecifierSet from pip._vendor.pkg_resources import Distribution from pip._internal.build_env import BuildEnvironment logger = logging.getLogger(__name__) def _get_dist(metadata_directo...
255
256
5,761
4
251
JE-Chen/je_old_repo
Python_OCR_JE/venv/Lib/site-packages/pip/_internal/req/req_install.py
Python
InstallRequirement
InstallRequirement
95
847
95
95
bebdff791bf5ec07544a3a29f6b862575c2a4763
bigcode/the-stack
train
2c715f29624d9ef9e0169100
train
function
def check_invalid_constraint_type(req): # type: (InstallRequirement) -> str # Check for unsupported forms problem = "" if not req.name: problem = "Unnamed requirements are not allowed as constraints" elif req.link: problem = "Links are not allowed as constraints" elif r...
def check_invalid_constraint_type(req): # type: (InstallRequirement) -> str # Check for unsupported forms
problem = "" if not req.name: problem = "Unnamed requirements are not allowed as constraints" elif req.link: problem = "Links are not allowed as constraints" elif req.extras: problem = "Constraints cannot have extras" if problem: deprecated( rea...
be built for it.". format(self.name) ), replacement="to fix the wheel build issue reported above", gone_in=None, issue=8368, ) def check_invalid_constraint_type(req): # type: (InstallRequirement) -> str # ...
63
64
200
25
38
JE-Chen/je_old_repo
Python_OCR_JE/venv/Lib/site-packages/pip/_internal/req/req_install.py
Python
check_invalid_constraint_type
check_invalid_constraint_type
850
879
850
853
9ef35e52034303a064d2ba182347ad2f28637c6d
bigcode/the-stack
train
87017aa7806801a94701224d
train
function
def _get_dist(metadata_directory): # type: (str) -> Distribution """Return a pkg_resources.Distribution for the provided metadata directory. """ dist_dir = metadata_directory.rstrip(os.sep) # Build a PathMetadata object, from path to metadata. :wink: base_dir, dist_dir_name = os.pat...
def _get_dist(metadata_directory): # type: (str) -> Distribution
"""Return a pkg_resources.Distribution for the provided metadata directory. """ dist_dir = metadata_directory.rstrip(os.sep) # Build a PathMetadata object, from path to metadata. :wink: base_dir, dist_dir_name = os.path.split(dist_dir) metadata = pkg_resources.PathMetadata(base_dir, ...
import Marker from pip._vendor.packaging.specifiers import SpecifierSet from pip._vendor.pkg_resources import Distribution from pip._internal.build_env import BuildEnvironment logger = logging.getLogger(__name__) def _get_dist(metadata_directory): # type: (str) -> Distribution
63
64
192
17
46
JE-Chen/je_old_repo
Python_OCR_JE/venv/Lib/site-packages/pip/_internal/req/req_install.py
Python
_get_dist
_get_dist
68
92
68
69
207498b2fefa4072c4e4f3541dc788a17fa16d7b
bigcode/the-stack
train
8279c24c7c929a3198ad8928
train
class
class Structure(with_metaclass(ABCMeta, object)): '''Structure plugin interface. A structure plugin should compute appropriate paths for data. ''' def __init__(self, prefix=''): '''Initialise structure.''' self.prefix = prefix self.path_separator = '/' super(Structure,...
class Structure(with_metaclass(ABCMeta, object)):
'''Structure plugin interface. A structure plugin should compute appropriate paths for data. ''' def __init__(self, prefix=''): '''Initialise structure.''' self.prefix = prefix self.path_separator = '/' super(Structure, self).__init__() @abstractmethod def get...
# :coding: utf-8 # :copyright: Copyright (c) 2014 ftrack from builtins import object from abc import ABCMeta, abstractmethod from future.utils import with_metaclass class Structure(with_metaclass(ABCMeta, object)):
56
64
173
11
44
tokejepsen/pype-setup
vendor/python/ftrack-python-api/ftrack_api/structure/base.py
Python
Structure
Structure
9
38
9
9
a41c009be856192d36bd3740b9fc066bcd1a8b4f
bigcode/the-stack
train
34f0739d2895bf3ea500cbd1
train
class
class PlanSerializer(ModelSerializer): product = BaseProductSerializer() class Meta: model = Plan fields = ("id", "nickname", "amount", "metadata", "product")
class PlanSerializer(ModelSerializer):
product = BaseProductSerializer() class Meta: model = Plan fields = ("id", "nickname", "amount", "metadata", "product")
_ext.models import OrganizationUserRole from .rest_framework.serializers import ( SubscriptionSerializer as BaseSubscriptionSerializer, ) class BaseProductSerializer(ModelSerializer): class Meta: model = Product fields = ("id", "name", "description", "type", "metadata") class PlanSerializer(Mo...
64
64
40
6
58
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
PlanSerializer
PlanSerializer
17
22
17
17
4f2ea403fe5bdc1271c4d9e0a0b17855533f7912
bigcode/the-stack
train
75c82f0535d09d3af85b0930
train
class
class OrganizationPrimaryKeySerializer(serializers.PrimaryKeyRelatedField): def get_queryset(self): user = self.context["request"].user return user.organizations_ext_organization.filter( organization_users__role=OrganizationUserRole.OWNER )
class OrganizationPrimaryKeySerializer(serializers.PrimaryKeyRelatedField):
def get_queryset(self): user = self.context["request"].user return user.organizations_ext_organization.filter( organization_users__role=OrganizationUserRole.OWNER )
any=True, source="plan_set") class Meta(BaseProductSerializer.Meta): fields = ("id", "name", "description", "type", "plans", "metadata") class SubscriptionSerializer(BaseSubscriptionSerializer): plan = PlanSerializer(read_only=True) class OrganizationPrimaryKeySerializer(serializers.PrimaryKeyRelated...
64
64
51
11
53
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
OrganizationPrimaryKeySerializer
OrganizationPrimaryKeySerializer
36
41
36
36
b66d8ef82201072007ff705761f98c14f2e971fc
bigcode/the-stack
train
564a0a54b988ee41e820e053
train
class
class PlanForOrganizationSerializer(OrganizationSelectSerializer): plan = serializers.SlugRelatedField(queryset=Plan.objects.all(), slug_field="id")
class PlanForOrganizationSerializer(OrganizationSelectSerializer):
plan = serializers.SlugRelatedField(queryset=Plan.objects.all(), slug_field="id")
["request"].user return user.organizations_ext_organization.filter( organization_users__role=OrganizationUserRole.OWNER ) class OrganizationSelectSerializer(serializers.Serializer): """ Organization in which user is owner of """ organization = OrganizationPrimaryKeySerializer() cl...
64
64
30
10
54
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
PlanForOrganizationSerializer
PlanForOrganizationSerializer
50
51
50
50
88f0a01815f856ef9cb9a21d0d58b19213dbd9ef
bigcode/the-stack
train
1351a7f2e30abbd60f84d866
train
class
class SubscriptionSerializer(BaseSubscriptionSerializer): plan = PlanSerializer(read_only=True)
class SubscriptionSerializer(BaseSubscriptionSerializer):
plan = PlanSerializer(read_only=True)
", "metadata", "product") class ProductSerializer(BaseProductSerializer): plans = PlanSerializer(many=True, source="plan_set") class Meta(BaseProductSerializer.Meta): fields = ("id", "name", "description", "type", "plans", "metadata") class SubscriptionSerializer(BaseSubscriptionSerializer):
64
64
16
7
57
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
SubscriptionSerializer
SubscriptionSerializer
32
33
32
32
dfc283c09f2aa907aa46f5ae597f1ad9c157f930
bigcode/the-stack
train
15c9f0d3910281c03eab17f0
train
class
class BaseProductSerializer(ModelSerializer): class Meta: model = Product fields = ("id", "name", "description", "type", "metadata")
class BaseProductSerializer(ModelSerializer):
class Meta: model = Product fields = ("id", "name", "description", "type", "metadata")
import SuspiciousOperation from rest_framework import serializers from rest_framework.serializers import ModelSerializer from djstripe.models import Plan, Customer, Product from organizations_ext.models import OrganizationUserRole from .rest_framework.serializers import ( SubscriptionSerializer as BaseSubscription...
64
64
34
7
57
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
BaseProductSerializer
BaseProductSerializer
11
14
11
11
6481774cba5d668792847e4866bef7533173e637
bigcode/the-stack
train
e71575c54cace979eb2bc050
train
class
class OrganizationSelectSerializer(serializers.Serializer): """ Organization in which user is owner of """ organization = OrganizationPrimaryKeySerializer()
class OrganizationSelectSerializer(serializers.Serializer):
""" Organization in which user is owner of """ organization = OrganizationPrimaryKeySerializer()
PlanSerializer(read_only=True) class OrganizationPrimaryKeySerializer(serializers.PrimaryKeyRelatedField): def get_queryset(self): user = self.context["request"].user return user.organizations_ext_organization.filter( organization_users__role=OrganizationUserRole.OWNER ) class...
64
64
25
7
57
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
OrganizationSelectSerializer
OrganizationSelectSerializer
44
47
44
44
2d260c64fca75178364dea257478e286eceabbf3
bigcode/the-stack
train
b52c875a3255fa6e9cb68037
train
class
class CreateSubscriptionSerializer(PlanForOrganizationSerializer): """A serializer used to create a Subscription. Only works with free plans. """ subscription = SubscriptionSerializer(read_only=True) def create(self, data): organization = data["organization"] plan = data["plan"] if...
class CreateSubscriptionSerializer(PlanForOrganizationSerializer):
"""A serializer used to create a Subscription. Only works with free plans. """ subscription = SubscriptionSerializer(read_only=True) def create(self, data): organization = data["organization"] plan = data["plan"] if plan.amount != 0.0: raise SuspiciousOperation( ...
OrganizationSelectSerializer(serializers.Serializer): """ Organization in which user is owner of """ organization = OrganizationPrimaryKeySerializer() class PlanForOrganizationSerializer(OrganizationSelectSerializer): plan = serializers.SlugRelatedField(queryset=Plan.objects.all(), slug_field="id") clas...
64
64
136
10
54
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
CreateSubscriptionSerializer
CreateSubscriptionSerializer
54
72
54
54
e26b7d4d86522ba3f45a044c414139af16521feb
bigcode/the-stack
train
079513cd5464c62d837ad922
train
class
class ProductSerializer(BaseProductSerializer): plans = PlanSerializer(many=True, source="plan_set") class Meta(BaseProductSerializer.Meta): fields = ("id", "name", "description", "type", "plans", "metadata")
class ProductSerializer(BaseProductSerializer):
plans = PlanSerializer(many=True, source="plan_set") class Meta(BaseProductSerializer.Meta): fields = ("id", "name", "description", "type", "plans", "metadata")
fields = ("id", "name", "description", "type", "metadata") class PlanSerializer(ModelSerializer): product = BaseProductSerializer() class Meta: model = Plan fields = ("id", "nickname", "amount", "metadata", "product") class ProductSerializer(BaseProductSerializer):
64
64
50
7
57
rh-cssre/glitchtip-backend
djstripe_ext/serializers.py
Python
ProductSerializer
ProductSerializer
25
29
25
25
53bfeaa9fadc2a9b1a1c1597e2b0ddc914708f0d
bigcode/the-stack
train
1248b10c101f9f8ff02e2600
train
class
class ParameterException(Exception): def __init__(self,value): self.value=value def __str__(self): return "Parameter Exception: %s"%(repr(self.value))
class ParameterException(Exception):
def __init__(self,value): self.value=value def __str__(self): return "Parameter Exception: %s"%(repr(self.value))
class ParameterException(Exception):
5
64
38
5
0
Srheft/desispec
py/desispec/quicklook/qlexceptions.py
Python
ParameterException
ParameterException
2
6
2
2
5d8eb5cabf5cbb9dd358ab306877c4dfc3e82022
bigcode/the-stack
train
8a886d9c4e8bdc16ab48d2f8
train
class
class Migration(migrations.Migration): dependencies = [("sites", "0002_alter_domain_unique")] operations = [migrations.RunPython(update_site_forward, update_site_backward)]
class Migration(migrations.Migration):
dependencies = [("sites", "0002_alter_domain_unique")] operations = [migrations.RunPython(update_site_forward, update_site_backward)]
schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} ) class Migration(migrations.Migration):
64
64
39
7
57
Khan6452/testwed
testwed/contrib/sites/migrations/0003_set_site_domain_and_name.py
Python
Migration
Migration
30
34
30
31
0600620ced2e96fc01e6539dab743ca087596038
bigcode/the-stack
train
23abe3c0eea078b78260ad58
train
function
def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "testwed.com", "name": "testwed", }, )
def update_site_forward(apps, schema_editor):
"""Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "testwed.com", "name": "testwed", }, )
here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor):
64
64
68
10
53
Khan6452/testwed
testwed/contrib/sites/migrations/0003_set_site_domain_and_name.py
Python
update_site_forward
update_site_forward
10
19
10
10
3ab32128af143ee634f9b0f54af7acb89ba4107a
bigcode/the-stack
train
322e3df681201dcffb2a2068
train
function
def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} )
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} )
domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "testwed.com", "name": "testwed", }, ) def update_site_backward(apps, schema_editor):
64
64
64
10
54
Khan6452/testwed
testwed/contrib/sites/migrations/0003_set_site_domain_and_name.py
Python
update_site_backward
update_site_backward
22
27
22
22
e292061d5d6d1511fd8dfc5c59842b5c241752af
bigcode/the-stack
train