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
d734ab0de41757d30b8b6e6c
train
function
@pytest.fixture def freeze_datetime_utcnow(monkeypatch): """Fixture to return a static time for utcnow().""" class _Datetime: @classmethod def utcnow(cls): return FROZEN_DATETIME monkeypatch.setattr(datetime, 'datetime', _Datetime)
@pytest.fixture def freeze_datetime_utcnow(monkeypatch):
"""Fixture to return a static time for utcnow().""" class _Datetime: @classmethod def utcnow(cls): return FROZEN_DATETIME monkeypatch.setattr(datetime, 'datetime', _Datetime)
pytest raises builtin. Assures that an exception is NOT thrown. """ try: yield except exception: raise pytest.fail(f'DID RAISE {exception}') # fixture to freeze utcnow to a fixed date-time @pytest.fixture def freeze_datetime_utcnow(monkeypatch):
64
64
62
13
50
rstens/lear
queue_services/entity-pay/tests/conftest.py
Python
freeze_datetime_utcnow
freeze_datetime_utcnow
47
55
47
48
adb59e665f35835b227b5d47cdac74beb1e5c507
bigcode/the-stack
train
9137a934701729b3f22ba9b4
train
function
@pytest.fixture('function') def client_id(): """Return a unique client_id that can be used in tests.""" _id = random.SystemRandom().getrandbits(0x58) # _id = (base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', '') return f'client-{_id}'
@pytest.fixture('function') def client_id():
"""Return a unique client_id that can be used in tests.""" _id = random.SystemRandom().getrandbits(0x58) # _id = (base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', '') return f'client-{_id}'
-wide jwt manager.""" return _jwt @pytest.fixture(scope='session') def client_ctx(app): # pylint: disable=redefined-outer-name """Return session-wide Flask test client.""" with app.test_client() as _client: yield _client @pytest.fixture('function') def client_id():
64
64
72
9
54
rstens/lear
queue_services/entity-pay/tests/conftest.py
Python
client_id
client_id
94
100
94
95
a8cd3b7ca1b76a5175b6af33b16ad9d971527bf4
bigcode/the-stack
train
52024aae10f37e2d9148eb06
train
function
@pytest.fixture(scope='function') def session(app): # pylint: disable=redefined-outer-name, invalid-name """Return a function-scoped session.""" with app.app_context(): conn = db.engine.connect() txn = conn.begin() options = dict(bind=conn, binds={}) sess = db.create_scoped_ses...
@pytest.fixture(scope='function') def session(app): # pylint: disable=redefined-outer-name, invalid-name
"""Return a function-scoped session.""" with app.app_context(): conn = db.engine.connect() txn = conn.begin() options = dict(bind=conn, binds={}) sess = db.create_scoped_session(options=options) # establish a SAVEPOINT just before beginning the test # (http://d...
used in tests.""" _id = random.SystemRandom().getrandbits(0x58) # _id = (base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', '') return f'client-{_id}' @pytest.fixture(scope='function') def session(app): # pylint: disable=redefined-outer-name, invalid-name
77
78
261
24
53
rstens/lear
queue_services/entity-pay/tests/conftest.py
Python
session
session
103
136
103
104
923d56c65e479c3b033488c3f011bfc6e365a70e
bigcode/the-stack
train
17574a77d3ac38072254f78a
train
function
@pytest.fixture def config(app): """Return the application config.""" return app.config
@pytest.fixture def config(app):
"""Return the application config.""" return app.config
def app(): """Return a session-wide application configured in TEST mode.""" # _app = create_app('testing') _app = Flask(__name__) _app.config.from_object(get_named_config('testing')) db.init_app(_app) return _app @pytest.fixture def config(app):
64
64
19
7
56
rstens/lear
queue_services/entity-pay/tests/conftest.py
Python
config
config
69
72
69
70
5d0bb661d2aee47f625c63e01917407c450828d3
bigcode/the-stack
train
131d89b1ea8cc19e7699cf20
train
function
@contextmanager def not_raises(exception): """Corallary to the pytest raises builtin. Assures that an exception is NOT thrown. """ try: yield except exception: raise pytest.fail(f'DID RAISE {exception}')
@contextmanager def not_raises(exception):
"""Corallary to the pytest raises builtin. Assures that an exception is NOT thrown. """ try: yield except exception: raise pytest.fail(f'DID RAISE {exception}')
_api import jwt as _jwt from nats.aio.client import Client as Nats from sqlalchemy import event, text from stan.aio.client import Client as Stan from entity_pay.config import get_named_config from . import FROZEN_DATETIME @contextmanager def not_raises(exception):
64
64
56
10
53
rstens/lear
queue_services/entity-pay/tests/conftest.py
Python
not_raises
not_raises
35
44
35
36
258ac9122db35bf036a199fabbb279a7bd7bc2db
bigcode/the-stack
train
ff2a66746aa9ec3fb7b3b5da
train
function
@pytest.fixture(scope='session') def stan_server(docker_services): """Create the nats / stan services that the integration tests will use.""" if os.getenv('TEST_NATS_DOCKER'): docker_services.start('nats') time.sleep(2)
@pytest.fixture(scope='session') def stan_server(docker_services):
"""Create the nats / stan services that the integration tests will use.""" if os.getenv('TEST_NATS_DOCKER'): docker_services.start('nats') time.sleep(2)
sess sql = text('select 1') sess.execute(sql) yield sess # Cleanup sess.remove() # This instruction rollsback any commit that were executed in the tests. txn.rollback() conn.close() @pytest.fixture(scope='session') def stan_server(docker_services):
64
64
55
13
51
rstens/lear
queue_services/entity-pay/tests/conftest.py
Python
stan_server
stan_server
139
144
139
140
f4f1994fe2bd1f970f8b88cbbf01480f3bef8147
bigcode/the-stack
train
957394d9ce02f481ac3f8b0e
train
class
class TokenSerializer(serializers.ModelSerializer): class Meta: model = Token fields = ('key',)
class TokenSerializer(serializers.ModelSerializer):
class Meta: model = Token fields = ('key',)
request = self.context.get('request') self.form = self.form_class(data=self.initial_data, request=request) if not self.form.is_valid(): raise serializers.ValidationError(self.form.errors) return self.form.cleaned_data def save(self): self.form.save() class TokenSeria...
64
64
23
7
57
TabsterApp/django-nopassword
nopassword/rest/serializers.py
Python
TokenSerializer
TokenSerializer
46
50
46
47
613a6d25ff249623c88d24c2b6c54678451ff147
bigcode/the-stack
train
c926459089bfe8b6d24dbf34
train
class
class LoginCodeSerializer(serializers.Serializer): code = serializers.CharField() form_class = forms.LoginCodeForm def validate(self, data): request = self.context.get('request') self.form = self.form_class(data=self.initial_data, request=request) if not self.form.is_valid(): ...
class LoginCodeSerializer(serializers.Serializer):
code = serializers.CharField() form_class = forms.LoginCodeForm def validate(self, data): request = self.context.get('request') self.form = self.form_class(data=self.initial_data, request=request) if not self.form.is_valid(): raise serializers.ValidationError(self.for...
self.form = self.form_class(data=self.initial_data) if not self.form.is_valid(): raise serializers.ValidationError(self.form.errors) return self.form.cleaned_data def save(self): request = self.context.get('request') return self.form.save(request=request) class LoginC...
64
64
88
7
57
TabsterApp/django-nopassword
nopassword/rest/serializers.py
Python
LoginCodeSerializer
LoginCodeSerializer
27
43
27
27
d3e4dd3e925314c9802392928bde75a57190695f
bigcode/the-stack
train
03f6d6f2664bf979a98f57cc
train
class
class LoginSerializer(serializers.Serializer): username = serializers.CharField() next = serializers.CharField(required=False, allow_null=True) form_class = forms.LoginForm def validate(self, data): self.form = self.form_class(data=self.initial_data) if not self.form.is_valid(): ...
class LoginSerializer(serializers.Serializer):
username = serializers.CharField() next = serializers.CharField(required=False, allow_null=True) form_class = forms.LoginForm def validate(self, data): self.form = self.form_class(data=self.initial_data) if not self.form.is_valid(): raise serializers.ValidationError(self.f...
# -*- coding: utf-8 -*- from rest_framework import serializers from rest_framework.authtoken.models import Token from nopassword import forms class LoginSerializer(serializers.Serializer):
36
64
99
6
29
TabsterApp/django-nopassword
nopassword/rest/serializers.py
Python
LoginSerializer
LoginSerializer
8
24
8
8
75ae725e8af12f60a4d718b39670fb899921daac
bigcode/the-stack
train
2a8a3d2ed1b1453272a4d57a
train
function
@impl def flaskshop_load_blueprints(app): bp = Blueprint("api", __name__) csrf_protect.exempt(bp) bp.session_interface = CustomSessionInterface() ALLOWED_PATHS = frozenset( ["/api/v1/user/login", "/api/v1/", "/api/v1/swagger.json", "/api/v1/products/"] ) @bp.after_request def verif...
@impl def flaskshop_load_blueprints(app):
bp = Blueprint("api", __name__) csrf_protect.exempt(bp) bp.session_interface = CustomSessionInterface() ALLOWED_PATHS = frozenset( ["/api/v1/user/login", "/api/v1/", "/api/v1/swagger.json", "/api/v1/products/"] ) @bp.after_request def verify_user(response): from .auth impor...
from pluggy import HookimplMarker from flaskshop.extensions import csrf_protect from .product import api as product_api from .checkout import api as checkout_api from .auth import api as auth_api from .auth import CustomSessionInterface impl = HookimplMarker("flaskshop") @impl def flaskshop_load_blueprints(app):
74
74
247
11
63
maquinuz/flask-shop
flaskshop/api/api.py
Python
flaskshop_load_blueprints
flaskshop_load_blueprints
15
48
15
16
22f457d0897e4696899d3ed295cb3c4c5bf9fc22
bigcode/the-stack
train
bce9b5804a58ba53ad1d03c6
train
class
class V1alpha1Command(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). Th...
class V1alpha1Command(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a c...
""" Consolidate Services Description of all APIs # noqa: E501 The version of the OpenAPI document: version not set Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from argocd_python_client.model_utils import ( # noqa: F401 ApiTypeError, Mo...
167
256
1,981
9
157
RyanSiu1995/argocd-python-client
argocd_python_client/model/v1alpha1_command.py
Python
V1alpha1Command
V1alpha1Command
33
259
33
33
c48ad541657be6a849e3b1b3ddde4c823fcb76df
bigcode/the-stack
train
70a6766c6dd7ccfa60dcc9f3
train
class
class ProxyTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 def setup_nodes(self): self.have_ipv6 = test_ipv6_local() # Create two proxies on different ports # ... one unauthenticated self.conf1 = Socks5Configuration() self.conf1.addr = (...
class ProxyTest(BitcoinTestFramework):
def set_test_params(self): self.num_nodes = 4 def setup_nodes(self): self.have_ipv6 = test_ipv6_local() # Create two proxies on different ports # ... one unauthenticated self.conf1 = Socks5Configuration() self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid()...
, and the right connection command is given - Proxy configurations to test on QUISHd side: - `-proxy` (proxy everything) - `-onion` (proxy just onions) - `-proxyrandomize` Circuit randomization - Proxy configurations to test on proxy side, - support no authentication (other proxy) - support no authe...
256
256
1,748
8
247
quishtv/QUISH
test/functional/feature_proxy.py
Python
ProxyTest
ProxyTest
44
197
44
44
9ecfbb73178175c8487ab18162f18f822b71252c
bigcode/the-stack
train
c4f0ee32744f75d300d3a78f
train
class
class TestMetadata(TestCase): def test_usds_all_tokens_view(self): usds = pytezos.using('mainnet').contract('KT1REEb5VxWRjcHm5GzDMwErMmNFftsE5Gpf') res = usds.metadata.allTokens().storage_view() self.assertEqual([0], res) def test_domains(self): td = pytezos.using('mainnet').co...
class TestMetadata(TestCase):
def test_usds_all_tokens_view(self): usds = pytezos.using('mainnet').contract('KT1REEb5VxWRjcHm5GzDMwErMmNFftsE5Gpf') res = usds.metadata.allTokens().storage_view() self.assertEqual([0], res) def test_domains(self): td = pytezos.using('mainnet').contract('KT1GBZmSxmnKJXGMdMLbugP...
from unittest import TestCase, skip from pytezos import pytezos class TestMetadata(TestCase):
23
64
180
6
16
m-kus/pytezos
tests/integration_tests/test_metadata.py
Python
TestMetadata
TestMetadata
6
16
6
7
46e5e099299cb7bbfbb18f2304df3ddd191d0d93
bigcode/the-stack
train
4304c3b41be70f421a56976e
train
class
class Ensemble(object): def __init__( self, X_train, y_train, data_normalizer_class, n_classifiers=None, classifiers=None, base_classifier=None, n_features=None, features=None, activated=None, voting_weights=None, ): """ Builds an ensem...
class Ensemble(object):
def __init__( self, X_train, y_train, data_normalizer_class, n_classifiers=None, classifiers=None, base_classifier=None, n_features=None, features=None, activated=None, voting_weights=None, ): """ Builds an ensemble of classifiers. ...
from collections import Counter import numpy as np import pandas as pd from sklearn.ensemble import AdaBoostClassifier from data_normalization import DataNormalizer from sklearn.linear_model import LogisticRegression class Ensemble(object):
44
256
2,771
4
39
viniCerutti/eel
eda/__init__.py
Python
Ensemble
Ensemble
9
338
9
9
3637f39c65aa999e3eb132501c9f20fd510ac97c
bigcode/the-stack
train
b174890546cbd380134ce4cd
train
class
class DummyClassifier(object): """ Implements a DummyClassifier for compliance with the Ensemble class, when the base classifiers are not given to the constructor. """ def fit(self, X_train, y_train): """ Will not fit data. :param X_train: Predictive attributes of the traini...
class DummyClassifier(object):
""" Implements a DummyClassifier for compliance with the Ensemble class, when the base classifiers are not given to the constructor. """ def fit(self, X_train, y_train): """ Will not fit data. :param X_train: Predictive attributes of the training instances. :param y_...
): for j in range(1, n_classifiers + 1): dfd += (float(n_classifiers - j) / float(n_classifiers - 1)) * \ (float(distinct_failures[j]) / distinct_failures_count) return dfd class DummyClassifier(object):
64
64
168
5
58
viniCerutti/eel
eda/__init__.py
Python
DummyClassifier
DummyClassifier
341
362
341
341
ed7ed8f2c372fd17f944fbcba464d39a6b44f627
bigcode/the-stack
train
dacd5a38689cc07ec81b1d63
train
class
class FileInfo(object): def __init__(self, file_type, extension, mime, offset, signature): self.type = file_type self.extension = extension self.mime_type = mime self.signatures = signature
class FileInfo(object):
def __init__(self, file_type, extension, mime, offset, signature): self.type = file_type self.extension = extension self.mime_type = mime self.signatures = signature
class FileInfo(object):
5
64
50
5
0
jmg292/r2remote
plugins/_file_type_resolver.py
Python
FileInfo
FileInfo
1
7
1
2
3edb2fca1d456e43ce1c29e3a173ea31ea3ee215
bigcode/the-stack
train
85194b737d5d344a92b36cd6
train
function
def initialize_third_party(): flatbuffers()
def initialize_third_party():
flatbuffers()
osure//closure:defs.bzl", "filegroup_external") load( "//tensorflow/tools/def_file_filter:def_file_filter_configure.bzl", "def_file_filter_configure", ) load("//third_party/flatbuffers:workspace.bzl", flatbuffers = "repo") def initialize_third_party():
64
64
10
6
58
chibby0ne/tensorflow
tensorflow/workspace.bzl
Python
initialize_third_party
initialize_third_party
24
25
24
24
c68ca2d224a724fe2de69b39140c8669d9c471d5
bigcode/the-stack
train
78e5d7bf90203622e328d27d
train
function
def clean_dep(dep): return str(Label(dep))
def clean_dep(dep):
return str(Label(dep))
"def_file_filter_configure", ) load("//third_party/flatbuffers:workspace.bzl", flatbuffers = "repo") def initialize_third_party(): flatbuffers() # Sanitize a dependency so that it works correctly from code that includes # TensorFlow as a submodule. def clean_dep(dep):
64
64
11
5
59
chibby0ne/tensorflow
tensorflow/workspace.bzl
Python
clean_dep
clean_dep
29
30
29
29
1b34dbb57fab07168b570ed36c37c6bb230d7f8a
bigcode/the-stack
train
23f2f6cf8ac29bded7b74d26
train
function
def tf_workspace(path_prefix = "", tf_repo_name = ""): # Note that we check the minimum bazel version in WORKSPACE. clang6_configure(name = "local_config_clang6") cc_download_clang_toolchain(name = "local_config_download_clang") cuda_configure(name = "local_config_cuda") tensorrt_configure(name = "l...
def tf_workspace(path_prefix = "", tf_repo_name = ""): # Note that we check the minimum bazel version in WORKSPACE.
clang6_configure(name = "local_config_clang6") cc_download_clang_toolchain(name = "local_config_download_clang") cuda_configure(name = "local_config_cuda") tensorrt_configure(name = "local_config_tensorrt") nccl_configure(name = "local_config_nccl") git_configure(name = "local_config_git") s...
") load("//third_party/toolchains/cpus/arm:arm_compiler_configure.bzl", "arm_compiler_configure") load("//third_party:repo.bzl", "tf_http_archive") load("//third_party/clang_toolchain:cc_configure_clang.bzl", "cc_download_clang_toolchain") load("@io_bazel_rules_closure//closure/private:java_import_external.bzl", "java_...
256
256
12,938
28
228
chibby0ne/tensorflow
tensorflow/workspace.bzl
Python
tf_workspace
tf_workspace
35
947
35
36
d29663a7ce8562418d1c874df1b09b9c52d6f109
bigcode/the-stack
train
c261c1a89c6a9e365ffdb3d2
train
function
@user_passes_test(is_instructor) def formula_column_add(request): # TODO: Encapsulate operations in a function so that is available for the # API # Data to send as JSON response, in principle, assume form is not valid data = {'form_is_valid': False} # Get the workflow element workflow = get_wo...
@user_passes_test(is_instructor) def formula_column_add(request): # TODO: Encapsulate operations in a function so that is available for the # API # Data to send as JSON response, in principle, assume form is not valid
data = {'form_is_valid': False} # Get the workflow element workflow = get_workflow(request) if not workflow: data['form_is_valid'] = True data['html_redirect'] = reverse('workflow:index') return JsonResponse(data) if workflow.nrows == 0: data['form_is_valid'] = True...
. df = pandas_db.load_from_db(workflow.id) # Add the column with the initial value df = ops.data_frame_add_column(df, column, column_initial_value) # Update the column type with the value extracted from the data frame column.data_type = \ pandas_db.pandas_datatype_names[df[column.name].dty...
256
256
949
56
200
Lukahm/ontask
src/workflow/column_views.py
Python
formula_column_add
formula_column_add
128
254
128
132
4926d5c26cb4dd67a4fc808be7fef41e2e9d9502
bigcode/the-stack
train
718543e3a6347684e4a4c71b
train
function
@user_passes_test(is_instructor) def column_move_bottom(request, pk): """ :param request: HTTP request to move a column to end of the list :param pk: Column ID :return: """ # Get the workflow element workflow = get_workflow(request) if not workflow: return JsonResponse({'html_r...
@user_passes_test(is_instructor) def column_move_bottom(request, pk):
""" :param request: HTTP request to move a column to end of the list :param pk: Column ID :return: """ # Get the workflow element workflow = get_workflow(request) if not workflow: return JsonResponse({'html_redirect': reverse('workflow:index')}) # Get the column try: ...
pk': workflow.id}) }) # The workflow and column objects have been correctly obtained if column.position > 1: reposition_column_and_update_df(workflow, column, 1) return JsonResponse({}) @user_passes_test(is_instructor) def column_move_bottom(request, pk):
63
64
181
17
47
Lukahm/ontask
src/workflow/column_views.py
Python
column_move_bottom
column_move_bottom
606
633
606
607
c2b000002b02519eb89da8dc3604eddb5ae56f6a
bigcode/the-stack
train
21b557f8192e13a58aa09c0d
train
function
@user_passes_test(is_instructor) def column_add(request): # TODO: Encapsulate operations in a function so that is available for the # API # Data to send as JSON response data = {} # Get the workflow element workflow = get_workflow(request) if not workflow: data['form_is_valid'] = T...
@user_passes_test(is_instructor) def column_add(request): # TODO: Encapsulate operations in a function so that is available for the # API # Data to send as JSON response
data = {} # Get the workflow element workflow = get_workflow(request) if not workflow: data['form_is_valid'] = True data['html_redirect'] = reverse('workflow:index') return JsonResponse(data) if workflow.nrows == 0: data['form_is_valid'] = True data['html_re...
: Minimum of the selected columns', ['integer', 'double']), ('mean', 'mean: Mean of the selected columns', ['integer', 'double']), ('median', 'median: Median of the selected columns', ['integer', 'double']), ('std', 'std: Standard deviation over the selected columns', ['integer', 'double']), ('all'...
161
161
537
46
115
Lukahm/ontask
src/workflow/column_views.py
Python
column_add
column_add
49
125
49
53
2d873acb97ed6f1e24fab984294cbcc6f0885b7c
bigcode/the-stack
train
b7970a1f388feaaa458d9029
train
function
@user_passes_test(is_instructor) def column_edit(request, pk): # TODO: Encapsulate operations in a function so that is available for the # API # Data to send as JSON response data = {} # Get the workflow element workflow = get_workflow(request) if not workflow: data['form_is_valid'...
@user_passes_test(is_instructor) def column_edit(request, pk): # TODO: Encapsulate operations in a function so that is available for the # API # Data to send as JSON response
data = {} # Get the workflow element workflow = get_workflow(request) if not workflow: data['form_is_valid'] = True data['html_redirect'] = reverse('workflow:index') return JsonResponse(data) # Get the column object and make sure it belongs to the workflow try: ...
dtype.name] # Update the positions of the appropriate columns reposition_columns(workflow, workflow.ncols + 1, column.position) column.save() # Store the df to DB ops.store_dataframe_in_db(df, workflow.id) # Log the event logs.ops.put(request.user, 'column_add', ...
191
191
637
48
143
Lukahm/ontask
src/workflow/column_views.py
Python
column_edit
column_edit
257
352
257
261
366eccc64da049473126a7cdd72d389f4fe0c173
bigcode/the-stack
train
48aa99bf58974cf88914f493
train
function
@user_passes_test(is_instructor) def column_move_prev(request, pk): """ :param request: HTTP request to move a column to its previous position :param pk: Column ID :return: """ # JSON response, context and default values data = dict() # JSON response # Get the workflow element wo...
@user_passes_test(is_instructor) def column_move_prev(request, pk):
""" :param request: HTTP request to move a column to its previous position :param pk: Column ID :return: """ # JSON response, context and default values data = dict() # JSON response # Get the workflow element workflow = get_workflow(request) if not workflow: return J...
name': workflow.name, 'old_column_name': old_name, 'new_column_name': column.name}) data['form_is_valid'] = True data['html_redirect'] = '' return JsonResponse(data) @user_passes_test(is_instructor) def column_move_prev(request, pk):
64
64
201
17
47
Lukahm/ontask
src/workflow/column_views.py
Python
column_move_prev
column_move_prev
513
543
513
514
36f62badf657db83a89f6110b936894b7cfa4eee
bigcode/the-stack
train
df3d208ae46403db7a12feb8
train
function
@user_passes_test(is_instructor) def column_delete(request, pk): """ Delete a column in the table attached to a workflow :param request: HTTP request :param pk: ID of the column to delete. The workflow element is taken from the session. :return: Render the delete column form """ # JSON...
@user_passes_test(is_instructor) def column_delete(request, pk):
""" Delete a column in the table attached to a workflow :param request: HTTP request :param pk: ID of the column to delete. The workflow element is taken from the session. :return: Render the delete column form """ # JSON response, context and default values data = dict() # JSON r...
if 'position' in form.changed_data: # Update the positions of the appropriate columns reposition_columns(workflow, old_position, column.position) # Save the column information form.save() # Changes in column require rebuilding the query_builder_ops workf...
194
194
649
16
178
Lukahm/ontask
src/workflow/column_views.py
Python
column_delete
column_delete
355
439
355
356
50bd53aa65d5ef88f8f7f2637a30143851edf17f
bigcode/the-stack
train
dbb54011e2e05bb45eef8ac8
train
function
@user_passes_test(is_instructor) def column_move_next(request, pk): """ :param request: HTTP request to move a column to its next position :param pk: Column ID :return: """ # Get the workflow element workflow = get_workflow(request) if not workflow: return JsonResponse({'html_r...
@user_passes_test(is_instructor) def column_move_next(request, pk):
""" :param request: HTTP request to move a column to its next position :param pk: Column ID :return: """ # Get the workflow element workflow = get_workflow(request) if not workflow: return JsonResponse({'html_redirect': reverse('workflow:index')}) # Get the column try:...
.id}) }) # The workflow and column objects have been correctly obtained if column.position > 1: reposition_column_and_update_df(workflow, column, column.position - 1) return JsonResponse({}) @user_passes_test(is_instructor) def column_move_next(request, pk):
63
64
182
17
47
Lukahm/ontask
src/workflow/column_views.py
Python
column_move_next
column_move_next
546
573
546
547
da0c97412c890e296066d2977cba54c8dfe00d47
bigcode/the-stack
train
5e126dcaa8b29b5c4af30e17
train
function
@user_passes_test(is_instructor) def column_move_top(request, pk): """ :param request: HTTP request to move a column to the top of the list :param pk: Column ID :return: """ # Get the workflow element workflow = get_workflow(request) if not workflow: return JsonResponse({'html_...
@user_passes_test(is_instructor) def column_move_top(request, pk):
""" :param request: HTTP request to move a column to the top of the list :param pk: Column ID :return: """ # Get the workflow element workflow = get_workflow(request) if not workflow: return JsonResponse({'html_redirect': reverse('workflow:index')}) # Get the column tr...
}) }) # The workflow and column objects have been correctly obtained if column.position < workflow.ncols: reposition_column_and_update_df(workflow, column, column.position + 1) return JsonResponse({}) @user_passes_test(is_instructor) def column_move_top(request, pk):
63
64
180
17
47
Lukahm/ontask
src/workflow/column_views.py
Python
column_move_top
column_move_top
576
603
576
577
fe2020c411aaad09a4cadb284e36ce717db9c0d9
bigcode/the-stack
train
cc7c03c94b510d8eff2c3add
train
function
@user_passes_test(is_instructor) def column_clone(request, pk): """ Clone a column in the table attached to a workflow :param request: HTTP request :param pk: ID of the column to clone. The workflow element is taken from the session. :return: Render the clone column form """ # JSON res...
@user_passes_test(is_instructor) def column_clone(request, pk):
""" Clone a column in the table attached to a workflow :param request: HTTP request :param pk: ID of the column to clone. The workflow element is taken from the session. :return: Render the clone column form """ # JSON response, context and default values data = dict() # JSON resp...
'column_name': column.name}) data['form_is_valid'] = True # There are various points of return from_url = request.META['HTTP_REFERER'] if from_url.endswith(reverse('table:display')): data['html_redirect'] = reverse('table:display') else: data['html_redi...
142
142
475
16
126
Lukahm/ontask
src/workflow/column_views.py
Python
column_clone
column_clone
442
510
442
443
82bf1f59441a90336ed8fe0a90670491e7dba3b8
bigcode/the-stack
train
8cce066e8a5f10db8df924af
train
function
def create_meeting(dog_name, place, time, owner_email, client_email): path = os.path.dirname(__file__) credentials = pickle.load(open(f"{path}/token.pkl", "rb")) service = build("calendar", "v3", credentials=credentials) event = { 'summary': 'Meeting with ' + dog_name, 'location'...
def create_meeting(dog_name, place, time, owner_email, client_email):
path = os.path.dirname(__file__) credentials = pickle.load(open(f"{path}/token.pkl", "rb")) service = build("calendar", "v3", credentials=credentials) event = { 'summary': 'Meeting with ' + dog_name, 'location': place, 'description': 'meeting with the dog and the owners',...
from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow import pickle import sys import os # pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib def create_meeting(dog_name, place, time, owner_email, client_email):
69
82
274
18
50
hadaran/DogsTinder
meeting/create_meeting.py
Python
create_meeting
create_meeting
8
39
8
8
43f5b5ff215d08b8dde2b6fab580c31db64aa5b5
bigcode/the-stack
train
a5c0ed2968cccc16cc4afde5
train
function
def main(): # python lc_readcminfo_forradiomics_onefolder.py -sp I:\\Project_Lyph\\Grouped_ROI_venous\\Origin\\ROI_1 -gs True -op I:\\Project_Lyph\\Grouped_ROI_venous\\Origin\\ROI_1 # input import argparse parser = argparse.ArgumentParser() parser.add_argument('-sp', '--subjpath', type=str, help='所有被试根目...
def main(): # python lc_readcminfo_forradiomics_onefolder.py -sp I:\\Project_Lyph\\Grouped_ROI_venous\\Origin\\ROI_1 -gs True -op I:\\Project_Lyph\\Grouped_ROI_venous\\Origin\\ROI_1 # input
import argparse parser = argparse.ArgumentParser() parser.add_argument('-sp', '--subjpath', type=str, help='所有被试根目录') parser.add_argument('-gs', '--get_seriesinfo', type=str, help='是否提取dcm series信息') parser.add_argument('-op', '--outpath', type=str, help='保存结果的路径') args = parser.parse_args() ...
seriesname.append(seriespath) return spacing, machine, seriesname, shape, errorseries def main(): # python lc_readcminfo_forradiomics_onefolder.py -sp I:\\Project_Lyph\\Grouped_ROI_venous\\Origin\\ROI_1 -gs True -op I:\\Project_Lyph\\Grouped_ROI_venous\\Origin\\ROI_1 # input
88
88
296
68
19
dongmengshi/easylearn
eslearn/utils/lc_read_dicominfo_subjlevel.py
Python
main
main
42
63
42
44
a3754591bdcd10999e77ec3791274c95ff6c68c2
bigcode/the-stack
train
6ca4bd460cac6ba4ba71dceb
train
function
def run(subjpath, get_seriesinfo): """ For several series folder of one subject Input: subjpath: one subject's folder path (containing several seriers subfolders) Returns: spacing, machine, seriesname, shape, errorseries """ allsubj = os.listdir(subjpath) allseriespath =...
def run(subjpath, get_seriesinfo):
""" For several series folder of one subject Input: subjpath: one subject's folder path (containing several seriers subfolders) Returns: spacing, machine, seriesname, shape, errorseries """ allsubj = os.listdir(subjpath) allseriespath = [os.path.join(subjpath, subj) for ...
@author: lenovo """ import sys import os import numpy homedir = os.path.dirname(os.getcwd()) sys.path.append(homedir) from concurrent.futures import ThreadPoolExecutor from Utils.lc_read_dicominfo_base import readdcmseries def run(subjpath, get_seriesinfo):
66
66
222
10
55
dongmengshi/easylearn
eslearn/utils/lc_read_dicominfo_subjlevel.py
Python
run
run
18
40
18
18
5df9e69b8b4c1bb9b927ca146864a064ad0ec90b
bigcode/the-stack
train
f4012758d89b304d7d42a340
train
class
class TestUINotificationHooksFactory(unittest.TestCase): def setUp(self): self.plugin = UINotificationPlugin() self.factory = self.plugin.ui_hooks_factories[0] def test_initialization(self): self.assertEqual(self.factory.plugin_id, self.plugin.id) self.assertEqual(self.factory.p...
class TestUINotificationHooksFactory(unittest.TestCase):
def setUp(self): self.plugin = UINotificationPlugin() self.factory = self.plugin.ui_hooks_factories[0] def test_initialization(self): self.assertEqual(self.factory.plugin_id, self.plugin.id) self.assertEqual(self.factory.plugin_name, self.plugin.name) def test_create_ui_hoo...
, TX # All rights reserved. import unittest from force_wfmanager.notifications.ui_notification_hooks_manager \ import \ UINotificationHooksManager from force_wfmanager.notifications.ui_notification_plugin import \ UINotificationPlugin class TestUINotificationHooksFactory(unittest.TestCase):
64
64
105
12
51
force-h2020/force-wfmanager
force_wfmanager/notifications/tests/test_ui_notification_hooks_factory.py
Python
TestUINotificationHooksFactory
TestUINotificationHooksFactory
13
25
13
13
9503372193f10bda10429649522fc8345711b0be
bigcode/the-stack
train
b7de1e14a54393dd61d518b9
train
class
class MNIST_HANDLER(object): def __init__(self, data): self.num_training_example = data.train.num_examples self.num_test_example = data.test.num_examples self.training_data , self.training_labels = data.train.next_batch(self.num_training_example) self.test_data , self.test_labels = data....
class MNIST_HANDLER(object):
def __init__(self, data): self.num_training_example = data.train.num_examples self.num_test_example = data.test.num_examples self.training_data , self.training_labels = data.train.next_batch(self.num_training_example) self.test_data , self.test_labels = data.test.next_batch(self.num_test_ex...
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import mnist from tensorflow.examples.tutorials.mnist import input_data import cdbn_backup as cdbn """ -------------------------------------------- ------------------- DATA ------------------- ---------------------------------...
64
204
682
7
57
arthurmeyer/Convolutional_Deep_Belief_Network
demo_cdbn_mnist.py
Python
MNIST_HANDLER
MNIST_HANDLER
12
76
12
13
9b7b3d97aa509396cdee0ad8e276c5885d33d084
bigcode/the-stack
train
790251a8bceaab366583cfc0
train
function
def check_pos_is_safe (pos_to_check, minion_dict, level): pos_is_safe = True if not isinstance (level.get_cell_pos (pos_to_check.x, pos_to_check.y), Room): return False for _key, minion in minion_dict.items(): if minion.is_on_cell (pos_to_check): if minion.state != 0: ...
def check_pos_is_safe (pos_to_check, minion_dict, level):
pos_is_safe = True if not isinstance (level.get_cell_pos (pos_to_check.x, pos_to_check.y), Room): return False for _key, minion in minion_dict.items(): if minion.is_on_cell (pos_to_check): if minion.state != 0: pos_is_safe = False if minion.is_on...
_time = 0 self.recall_time = param_0 self.target = param_2 def is_on_map(self): return self.recall_time > 0 class Wanderer(Minion): pass class Slasher(Minion): pass def check_pos_is_safe (pos_to_check, minion_dict, level):
75
75
252
16
58
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
check_pos_is_safe
check_pos_is_safe
363
386
363
363
c8fd5a1ee4429f2ebc543b5c59db4cfceed00ed0
bigcode/the-stack
train
910b48b5807568620e2d89cf
train
class
class Slasher(Minion): pass
class Slasher(Minion):
pass
else: self.invoc_time = 0 self.recall_time = param_0 self.target = param_2 def is_on_map(self): return self.recall_time > 0 class Wanderer(Minion): pass class Slasher(Minion):
64
64
9
6
57
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Slasher
Slasher
359
360
359
359
14b8e8ff61c43a67d75df900245afa42a90f0d89
bigcode/the-stack
train
0c5f3716aec7ae3124b1ea89
train
class
class Cell (): def __init__ (self, x , y): self.position = Position (x, y) def wall_hack_distance (self, other): return abs(self.position.x - other.position.x) + abs(self.position.y - other.position.y) def is_adjacent (self, other): return self.wall_hack_distance (other) ==...
class Cell ():
def __init__ (self, x , y): self.position = Position (x, y) def wall_hack_distance (self, other): return abs(self.position.x - other.position.x) + abs(self.position.y - other.position.y) def is_adjacent (self, other): return self.wall_hack_distance (other) == 1
current_room.wall_hack_distance (end_cell) path_searched_count += 1 next_path_data = Path (estimated_cost = next_cost, tie_breaker = path_searched_count, path = next_path) heappush (pending_paths_heap, next_path_data) class Cell ():
63
64
84
4
59
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Cell
Cell
96
104
96
96
f7a2f407be844162fd1ec2a2fd881f4ba61a0c30
bigcode/the-stack
train
ebaf9af018927169251ff12e
train
class
class Room (Cell): def __init__ (self, x, y): super().__init__ (x, y) self.adjacent_rooms = [] def add_adjacent_room (self, room): self.adjacent_rooms.append (room) def get_adjacent_rooms (self): return self.adjacent_rooms + [self]
class Room (Cell):
def __init__ (self, x, y): super().__init__ (x, y) self.adjacent_rooms = [] def add_adjacent_room (self, room): self.adjacent_rooms.append (room) def get_adjacent_rooms (self): return self.adjacent_rooms + [self]
) def wall_hack_distance (self, other): return abs(self.position.x - other.position.x) + abs(self.position.y - other.position.y) def is_adjacent (self, other): return self.wall_hack_distance (other) == 1 class Room (Cell):
64
64
78
5
58
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Room
Room
106
115
106
106
f4bbd301d59e29f382622ef6ad19fbb16f4d82e9
bigcode/the-stack
train
fc9ee7373b9039c0c4267090
train
function
def debug (text): print (text, file=sys.stderr)
def debug (text):
print (text, file=sys.stderr)
numpy from collections import namedtuple from heapq import * import timeit # Survive the wrath of Kutulu # Coded fearlessly by JohnnyYuge & nmahoude (ok we might have been a bit scared by the old god...but don't say anything) def debug (text):
64
64
14
5
59
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
debug
debug
16
17
16
16
feddbc91e92a5ff52ebaef30b8ef8335081af5c5
bigcode/the-stack
train
9b711f0047c9f8c58f86041e
train
class
class Minion(Entity): def __init__(self): Entity.__init__(self) self.kind = "Minions" self.invoc_time = 0 self.recall_time = 0 self.state = 0 self.target = 0 def is_spawning (self): return self.state == 0 def update (self, ident,...
class Minion(Entity):
def __init__(self): Entity.__init__(self) self.kind = "Minions" self.invoc_time = 0 self.recall_time = 0 self.state = 0 self.target = 0 def is_spawning (self): return self.state == 0 def update (self, ident, x, y, param_0, param_1, pa...
target = Position (other.pos.x, other.pos.y - 1) else: debug ("cannot reach...") return target def wall_hack_distance (self, other, maze): return maze.get_wall_hack_distance (self, other) class Minion(Entity):
62
64
201
6
56
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Minion
Minion
328
354
328
329
68e80197cda7f7cd48adfe8dc2d471df11370d0d
bigcode/the-stack
train
ce9d2790510886ca7bfa73e5
train
class
class Shelter(Effect): pass
class Shelter(Effect):
pass
_end = param_0 self.launcher = param_1 def __str__(self): return "Effect pos : {}".format (self.pos) class Light(Effect): pass class Map(Effect): pass class Yell(Effect): pass class Shelter(Effect):
64
64
8
5
58
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Shelter
Shelter
232
233
232
232
11a746804b4f50cde7ce18bf37439c61c1eef6a4
bigcode/the-stack
train
1e83b7fe3b17cc5b7e5a74ce
train
class
class Wanderer(Minion): pass
class Wanderer(Minion):
pass
self.recall_time = 0 else: self.invoc_time = 0 self.recall_time = param_0 self.target = param_2 def is_on_map(self): return self.recall_time > 0 class Wanderer(Minion):
64
64
9
6
57
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Wanderer
Wanderer
356
357
356
356
c15805757513aceada138fb34ccee145e16d7d9a
bigcode/the-stack
train
9f1c367afc9857f5be9a9530
train
class
class Entity: def __init__(self): self.kind = "" self.ident = 0 self.pos = Position() def update(self, kind, ident, x, y): self.kind = kind self.ident = ident self.pos.update (x, y) def get_nearest(self, others): """ Wrong wa...
class Entity:
def __init__(self): self.kind = "" self.ident = 0 self.pos = Position() def update(self, kind, ident, x, y): self.kind = kind self.ident = ident self.pos.update (x, y) def get_nearest(self, others): """ Wrong way to find nearest e...
""" if other != None: return self.x == other.x and self.y == other.y return False def __str__ (self): """ Define str() function for class """ return "{} {}".format(int (self.x), int (self.y)) class Entity:
64
64
186
4
60
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Entity
Entity
175
201
175
176
ea05d2922bf00eab1b8219344e6ea94fdf5435c1
bigcode/the-stack
train
18d66b8ea5c8883222a27af5
train
class
class Maze(): def __init__ (self, width, heght): self.cells = [[Cell (x,y) for y in range(height)] for x in range(width)] # aliased collection for quick access to a specific type of room self.rooms = [] self.spawners = [] def set_row (self, row_number, serialized_row_str...
class Maze():
def __init__ (self, width, heght): self.cells = [[Cell (x,y) for y in range(height)] for x in range(width)] # aliased collection for quick access to a specific type of room self.rooms = [] self.spawners = [] def set_row (self, row_number, serialized_row_string): ...
import sys import math import copy import itertools import numpy from collections import namedtuple from heapq import * import timeit # Survive the wrath of Kutulu # Coded fearlessly by JohnnyYuge & nmahoude (ok we might have been a bit scared by the old god...but don't say anything) def debug (text): print (t...
127
239
798
3
124
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Maze
Maze
24
94
24
24
c3b8ae92235f57034b4f27a256d0dff8e2341223
bigcode/the-stack
train
1d953e253ce049668788d4c7
train
class
class Yell(Effect): pass
class Yell(Effect):
pass
x, y) self.time_to_end = param_0 self.launcher = param_1 def __str__(self): return "Effect pos : {}".format (self.pos) class Light(Effect): pass class Map(Effect): pass class Yell(Effect):
64
64
9
6
57
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Yell
Yell
229
230
229
229
5426a2b0d85892607a8170d5b162b33975d359e7
bigcode/the-stack
train
4287d640e183e0da5ece228b
train
class
class Position: def __init__(self, x = 0, y = 0): self.x = x self.y = y def update (self, x, y): """ Udpate value for Position """ self.x = x self.y = y def __sub__ (self, other): """ Define "-" operator for class ...
class Position:
def __init__(self, x = 0, y = 0): self.x = x self.y = y def update (self, x, y): """ Udpate value for Position """ self.x = x self.y = y def __sub__ (self, other): """ Define "-" operator for class """ return P...
self.adjacent_rooms = [] def add_adjacent_room (self, room): self.adjacent_rooms.append (room) def get_adjacent_rooms (self): return self.adjacent_rooms + [self] class Spawner (Room): def __init__ (self, x, y): super().__init__ (x, y) ########### end maze class Positi...
87
87
293
4
82
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Position
Position
123
172
123
124
18af51ea4a8706f5c3398a8b97ed2e3d0caba944
bigcode/the-stack
train
697fc89fb8b684cdb976e4ab
train
class
class Effect(Entity): def __init__(self): Entity.__init__(self) self.kind = "Effect" self.time_to_end = 0 self.launcher = 0 def update (self, x, y, param_0, param_1, param_2): self.ident = -1 self.pos.update (x, y) self.time_to_end = param_0 ...
class Effect(Entity):
def __init__(self): Entity.__init__(self) self.kind = "Effect" self.time_to_end = 0 self.launcher = 0 def update (self, x, y, param_0, param_1, param_2): self.ident = -1 self.pos.update (x, y) self.time_to_end = param_0 self.launcher = param_1...
= entity.pos nearest = entity return nearest def is_on_cell (self, cell): return self.pos == cell #def get_nearest(self, maze, other_entity): # return maze.get_shortest_path (self, other_entity) class Effect(Entity):
64
64
119
5
59
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Effect
Effect
206
221
206
207
b6c507bbaac1f4866c205e7e7d6e45f34eb4aaa3
bigcode/the-stack
train
acf6cdc01572d3aeed97e147
train
class
class Light(Effect): pass
class Light(Effect):
pass
, param_2): self.ident = -1 self.pos.update (x, y) self.time_to_end = param_0 self.launcher = param_1 def __str__(self): return "Effect pos : {}".format (self.pos) class Light(Effect):
64
64
8
5
59
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Light
Light
223
224
223
223
384476cd9d8c56ac0a1201360a58c29e1e277abf
bigcode/the-stack
train
540f2b945fd826a9b0745ebc
train
class
class Explorer(Entity): def __init__(self): Entity.__init__(self) self.kind = "Explorer" self.mental_health = 250 self.plan_use = 2 self.torch_use = 3 def update (self, x, y, param_0, param_1, param_2): self.pos.update (x, y) se...
class Explorer(Entity):
def __init__(self): Entity.__init__(self) self.kind = "Explorer" self.mental_health = 250 self.plan_use = 2 self.torch_use = 3 def update (self, x, y, param_0, param_1, param_2): self.pos.update (x, y) self.mental_health = param_0 ...
{}, is at {}".format(entity.ident, entity.pos)) if abs(entity.pos - self.pos) <= abs(current_val - self.pos): current_val = entity.pos nearest = entity return nearest def is_on_cell (self, cell): return self.pos == cell #def get_near...
247
247
825
5
241
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Explorer
Explorer
235
324
235
236
4eea1a98dc8972073a5273e314d732bf119f118d
bigcode/the-stack
train
7d43080148ada83d6ed2e757
train
class
class Map(Effect): pass
class Map(Effect):
pass
= -1 self.pos.update (x, y) self.time_to_end = param_0 self.launcher = param_1 def __str__(self): return "Effect pos : {}".format (self.pos) class Light(Effect): pass class Map(Effect):
64
64
8
5
58
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Map
Map
226
227
226
226
a7b44166b6c54338cdec1f3e5839fcd17414ac42
bigcode/the-stack
train
273bf66554077165df1cb10c
train
class
class Spawner (Room): def __init__ (self, x, y): super().__init__ (x, y)
class Spawner (Room):
def __init__ (self, x, y): super().__init__ (x, y)
init__ (x, y) self.adjacent_rooms = [] def add_adjacent_room (self, room): self.adjacent_rooms.append (room) def get_adjacent_rooms (self): return self.adjacent_rooms + [self] class Spawner (Room):
64
64
28
6
58
OkynC/codingame_challenge
code_of_kutulu/code.py
Python
Spawner
Spawner
117
119
117
117
70c4939452096f046084d225576813037f4b45d2
bigcode/the-stack
train
be63633b81663a6e7a86b7a1
train
class
class DeleteInternetGateway(EC2Request): DESCRIPTION = 'Delete a VPC Internet gateway' ARGS = [Arg('InternetGatewayId', metavar='IGATEWAY', help='ID of the Internet gateway to delete (required)')]
class DeleteInternetGateway(EC2Request):
DESCRIPTION = 'Delete a VPC Internet gateway' ARGS = [Arg('InternetGatewayId', metavar='IGATEWAY', help='ID of the Internet gateway to delete (required)')]
LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from requestbuilder import Arg from euca2ools.commands.ec2 import EC2Request class DeleteInternetGateway(EC2Request):
64
64
51
9
54
salewski/euca2ools
euca2ools/commands/ec2/deleteinternetgateway.py
Python
DeleteInternetGateway
DeleteInternetGateway
31
34
31
31
bc1c6095c0bc0c362c84ff7ea121e10eeeee6476
bigcode/the-stack
train
2fec652e787347bcc7497f67
train
function
@launchable.subset def subset(client): # read lines as test file names for t in client.stdin(): client.test_path(t.rstrip("\n")) client.separator = ',' client.run()
@launchable.subset def subset(client): # read lines as test file names
for t in client.stdin(): client.test_path(t.rstrip("\n")) client.separator = ',' client.run()
("file") if filepath is not None: for suite in suites: suite.attrib.update({"filepath": filepath}) return tree client._junitxml_parse_func = parse_func client.run() @launchable.subset def subset(client): # read lines as test file names
64
64
45
19
45
tchia04/cli
launchable/test_runners/cypress.py
Python
subset
subset
29
36
29
31
44fae3204ede9cfaa6998752ef8742aa878894d7
bigcode/the-stack
train
09d2a848d1e5556fe456f687
train
function
@click.argument('reports', required=True, nargs=-1) @launchable.record.tests def record_tests(client, reports): for r in reports: client.report(r) def parse_func(p: str) -> ET.ElementTree: tree = ET.parse(p) for suites in tree.iter("testsuites"): if len(suites)==0: ...
@click.argument('reports', required=True, nargs=-1) @launchable.record.tests def record_tests(client, reports):
for r in reports: client.report(r) def parse_func(p: str) -> ET.ElementTree: tree = ET.parse(p) for suites in tree.iter("testsuites"): if len(suites)==0: continue root_suite = suites.find('./testsuite[@name="Root Suite"]') if root_suit...
import click from . import launchable from xml.etree import ElementTree as ET @click.argument('reports', required=True, nargs=-1) @launchable.record.tests def record_tests(client, reports):
44
64
152
25
18
tchia04/cli
launchable/test_runners/cypress.py
Python
record_tests
record_tests
6
26
6
8
5460ed75e3bea48d81e9eaa5d3468a25ff4e93fe
bigcode/the-stack
train
87070ddbc5de26d193316d49
train
class
class FirewallPolicyRuleCollectionGroupsOperations(object): """FirewallPolicyRuleCollectionGroupsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to mode...
class FirewallPolicyRuleCollectionGroupsOperations(object):
"""FirewallPolicyRuleCollectionGroupsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~a...
. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ---------------------------------------------------------...
256
256
4,594
9
247
rsdoherty/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_08_01/operations/_firewall_policy_rule_collection_groups_operations.py
Python
FirewallPolicyRuleCollectionGroupsOperations
FirewallPolicyRuleCollectionGroupsOperations
28
441
28
28
a576869c4806e9a7d75a0e326136fe361f170e8e
bigcode/the-stack
train
9cb82cc2f1af2c23fe35e754
train
class
class Migration(migrations.Migration): dependencies = [ ('main', '0023_auto_20170702_2002'), ] operations = [ migrations.AddField( model_name='senatemembership', name='year', field=models.CharField(choices=[('1', 'First Year'), ('2', 'Second Year'), ('3'...
class Migration(migrations.Migration):
dependencies = [ ('main', '0023_auto_20170702_2002'), ] operations = [ migrations.AddField( model_name='senatemembership', name='year', field=models.CharField(choices=[('1', 'First Year'), ('2', 'Second Year'), ('3', 'Third Year'), ('4', 'Fourth Year')], ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-02 14:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
54
64
156
7
46
shashankmohabia/gymkhana-master
src/main/migrations/0024_auto_20170702_2026.py
Python
Migration
Migration
8
26
8
9
f4687817a571bea9cea765967ed65a66975b7c1e
bigcode/the-stack
train
e704c73249976cc8f3df947d
train
function
def formula(): # pivot factor P = 0 # scale factor A = 1 # joint number J = 6 # name move = 'formula' # element part = 'universe' # left or right helicity = 'left' start = 0 end = start+360 formula = Formula(P, A, J, move, part, helicity, start, end)
def formula(): # pivot factor
P = 0 # scale factor A = 1 # joint number J = 6 # name move = 'formula' # element part = 'universe' # left or right helicity = 'left' start = 0 end = start+360 formula = Formula(P, A, J, move, part, helicity, start, end)
.make_single_user(type='SELECTED_OBJECTS', object=True, obdata=True, material=True, animation=True) bpy.context.scene.cursor.location = (0.0, 0.0, 0.0) bpy.ops.object.origin_set(type='ORIGIN_CURSOR') def formula(): # pivot factor
64
64
98
7
57
varipon/Work-Plan-3-multi-legs
Task 3.1.5.2 Upper Hindlimb - Equestrianism : canter.py
Python
formula
formula
707
730
707
709
64e9c16c3bf216f4b660d9491f1539f40d7a9b58
bigcode/the-stack
train
bf36472283c38337b7d61818
train
function
def upperhindlimbs(): # scale factor A = 0.6 # pivot factor P = ((0.25* 0.6)/0.6)*A # name move = 'equestrianism-canter' # element part = 'right-upperhindlimb' # left or right helicity = 'left' start = -180 end = start-720 global upperhindlimb_right upperhindlimb_right = U...
def upperhindlimbs(): # scale factor
A = 0.6 # pivot factor P = ((0.25* 0.6)/0.6)*A # name move = 'equestrianism-canter' # element part = 'right-upperhindlimb' # left or right helicity = 'left' start = -180 end = start-720 global upperhindlimb_right upperhindlimb_right = UpperHindlimb(P, A, move, part, helicit...
', object=True, obdata=True, material=True, animation=True) bpy.context.scene.cursor.location = (0.0, 0.0, 0.0) bpy.ops.object.origin_set(type='ORIGIN_CURSOR') def formula(): # pivot factor P = 0 # scale factor A = 1 # joint number J = 6 # name move = 'formula' # element ...
156
156
522
10
146
varipon/Work-Plan-3-multi-legs
Task 3.1.5.2 Upper Hindlimb - Equestrianism : canter.py
Python
upperhindlimbs
upperhindlimbs
733
786
733
735
84b9ca317415c3c1561005154b217e1004ecd142
bigcode/the-stack
train
e7eb5bcca7b44668004af309
train
class
class Formula: def __init__(self, P, A, J, move, part, helicity, start, end): global interval global frame_start global frame_end self.interval = interval self.frame_start = frame_start self.frame_end = frame_end # pivot factor self.P = P ...
class Formula:
def __init__(self, P, A, J, move, part, helicity, start, end): global interval global frame_start global frame_end self.interval = interval self.frame_start = frame_start self.frame_end = frame_end # pivot factor self.P = P # scale factor ...
copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the ...
256
256
5,263
3
253
varipon/Work-Plan-3-multi-legs
Task 3.1.5.2 Upper Hindlimb - Equestrianism : canter.py
Python
Formula
Formula
48
520
48
49
2a3c47a85214f653de62f7241b054c83d6637e60
bigcode/the-stack
train
ce7a74952083cb1b1a293005
train
function
def main(origin): # create new collection newCol = bpy.data.collections.new('movement') # link the newCol to the scene bpy.context.scene.collection.children.link(newCol) newCol = bpy.data.collections.new('link') bpy.context.scene.collection.children.link(newCol) global interval gl...
def main(origin): # create new collection
newCol = bpy.data.collections.new('movement') # link the newCol to the scene bpy.context.scene.collection.children.link(newCol) newCol = bpy.data.collections.new('link') bpy.context.scene.collection.children.link(newCol) global interval global frame_start global frame_end frame_st...
limb_left.rig.location.y += upperhindlimb_loc[1] upperhindlimb_left.rig.location.z += upperhindlimb_loc[2] upperhindlimb_left.rig.rotation_euler = upperhindlimb_rot def main(origin): # create new collection
64
64
110
11
52
varipon/Work-Plan-3-multi-legs
Task 3.1.5.2 Upper Hindlimb - Equestrianism : canter.py
Python
main
main
789
809
789
791
e49c42bcc21c98501e41691b8954ce9fa5af3dd1
bigcode/the-stack
train
330312c51c82ce0b0ae033b4
train
class
class UpperHindlimb(Formula): J = 5 #joint number # Overriding def __init__(self, P, A, move, part, helicity, start, end): global interval global frame_start global frame_end self.interval = interval self.frame_start = frame_start self.frame_end = frame_en...
class UpperHindlimb(Formula):
J = 5 #joint number # Overriding def __init__(self, P, A, move, part, helicity, start, end): global interval global frame_start global frame_end self.interval = interval self.frame_start = frame_start self.frame_end = frame_end # pivot factor ...
ns.target = rig cns.subtarget = n.name[:len(n.name)] cns.owner_space = 'WORLD' cns.target_space = 'WORLD' # Copy rotation constraints Base -> Tip pBase = lnk_rig.pose.bones[n.name[:len(n.name)]] cns = pBase.constraints.new(...
256
256
2,082
9
247
varipon/Work-Plan-3-multi-legs
Task 3.1.5.2 Upper Hindlimb - Equestrianism : canter.py
Python
UpperHindlimb
UpperHindlimb
523
704
523
524
b542723cfc5e3df5ea913febc79a21cc5b46e97a
bigcode/the-stack
train
aa0bd0b60b9e06f24eb307bb
train
class
class Sage3Lunar(Sage3Data): def __init__(self, filename): super(Sage3Lunar, self).__init__(filename) self.speciesData = { 'O3': self.ozone, 'NO2': self.nitrogen_dioxide, 'NO3': self.nitroge_trioxide, 'OClO': self.chlorine_dioxide } @p...
class Sage3Lunar(Sage3Data):
def __init__(self, filename): super(Sage3Lunar, self).__init__(filename) self.speciesData = { 'O3': self.ozone, 'NO2': self.nitrogen_dioxide, 'NO3': self.nitroge_trioxide, 'OClO': self.chlorine_dioxide } @property @nanitize def...
'O3': self.ozone, 'H2O': self.water_vapour, 'NO2': self.nitrogen_dioxide } @property @nanitize def water_vapour(self): """Water vapour concentration in cm ** -3""" return np.array([[x[0], x[1], x[2]] for x in self._getWaterProfiles()]) def _getWater...
148
148
495
10
138
Odin-SMR/odin-api
src/odinapi/views/read_sageIII.py
Python
Sage3Lunar
Sage3Lunar
225
277
225
225
ffda1f49d700e68846ced910eea41349eb47ed86
bigcode/the-stack
train
d05bcca139cf2a0280c9a04d
train
function
def nanitize(f): """A decorator function for replacing undefined values in returned nd-arrays with nan. """ def _decoration(self): data = f(self) if data.dtype == np.int32: maximum = np.iinfo(np.int32).max else: maximum = np.finfo(np.float32).max ...
def nanitize(f):
"""A decorator function for replacing undefined values in returned nd-arrays with nan. """ def _decoration(self): data = f(self) if data.dtype == np.int32: maximum = np.iinfo(np.int32).max else: maximum = np.finfo(np.float32).max return np.where(...
End'] = data.longitudes.tolist()[1] data_dict['Pressure'] = data.pressure.tolist() data_dict['Temperature'] = data.temperature.tolist() data_dict[species] = data.speciesData[species].tolist() # Return data return data_dict def nanitize(f):
64
64
94
5
58
Odin-SMR/odin-api
src/odinapi/views/read_sageIII.py
Python
nanitize
nanitize
48
62
48
48
11a85a61c399f56e88d8fb7856006f237eb2f99c
bigcode/the-stack
train
a2d13a1f548207fd644af3e9
train
function
def read_sageIII_file(filename, date, species, event_type): """Convenience function for getting all data from a Sage III file""" # Handle case of species -- special case for OClO: species = species.upper() if species == "OCLO": species = "OClO" # Construct filename: versions = {'lunar':...
def read_sageIII_file(filename, date, species, event_type):
"""Convenience function for getting all data from a Sage III file""" # Handle case of species -- special case for OClO: species = species.upper() if species == "OCLO": species = "OClO" # Construct filename: versions = {'lunar': 'v03', 'solar': 'v04'} sageIII_datapath = '/vds-data/M...
import os import h5py import numpy as np from datetime import datetime def read_sageIII_file(filename, date, species, event_type):
33
121
406
15
17
Odin-SMR/odin-api
src/odinapi/views/read_sageIII.py
Python
read_sageIII_file
read_sageIII_file
7
45
7
7
0275782d052d9b93d1966e6404504176684ace99
bigcode/the-stack
train
23e53faeecf4ae844b7aadfc
train
class
class Sage3Solar(Sage3Data): def __init__(self, filename): super(Sage3Solar, self).__init__(filename) self.speciesData = { 'O3': self.ozone, 'H2O': self.water_vapour, 'NO2': self.nitrogen_dioxide } @property @nanitize def water_vapour(self...
class Sage3Solar(Sage3Data):
def __init__(self, filename): super(Sage3Solar, self).__init__(filename) self.speciesData = { 'O3': self.ozone, 'H2O': self.water_vapour, 'NO2': self.nitrogen_dioxide } @property @nanitize def water_vapour(self): """Water vapour co...
hour = time // 10000 minute = (time - hour * 10000) // 100 second = time - hour * 10000 - minute * 100 return datetime(year, month, day, hour, minute, second) class Sage3Solar(Sage3Data):
64
64
177
9
55
Odin-SMR/odin-api
src/odinapi/views/read_sageIII.py
Python
Sage3Solar
Sage3Solar
204
222
204
204
efe90814b6e329537e123b145013e1cc090da0fd
bigcode/the-stack
train
f5e813a1af9e2eef3bbcd1ac
train
class
class Sage3Data: def __init__(self, filename): self._hfile = h5py.File(filename, 'r') self.speciesData = { 'O3': self.ozone, 'NO2': self.nitrogen_dioxide } def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): ...
class Sage3Data:
def __init__(self, filename): self._hfile = h5py.File(filename, 'r') self.speciesData = { 'O3': self.ozone, 'NO2': self.nitrogen_dioxide } def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self._hfile.cl...
" data_dict['EventType'] = event_type data_dict['MJDStart'] = data.datetimes_mjd.tolist()[0] data_dict['MJDEnd'] = data.datetimes_mjd.tolist()[1] data_dict['LatStart'] = data.latitudes.tolist()[0] data_dict['LatEnd'] = data.latitudes.tolist()[1] data_dict['LongStart'] = d...
256
256
1,135
5
250
Odin-SMR/odin-api
src/odinapi/views/read_sageIII.py
Python
Sage3Data
Sage3Data
65
201
65
65
edd03eaee682fd4d026e7df98dc579b76e3b19d7
bigcode/the-stack
train
b1d98fc90a015541afb18493
train
function
def count(n, word): if n == 1: return "%d %s" % (n, word) else: return "%d %ss" % (n, word)
def count(n, word):
if n == 1: return "%d %s" % (n, word) else: return "%d %ss" % (n, word)
(len(self.bad) > 0 or self.interrupted) def removepy(names): if not names: return for idx, name in enumerate(names): basename, ext = os.path.splitext(name) if ext == '.py': names[idx] = basename def count(n, word):
64
64
42
6
57
KinkowanWinter/Transcendental-Number-Utilization
Lib/test/libregrtest/main.py
Python
count
count
504
508
504
504
4050277a6c55a5bfb75a0549c00777eff5cf4d24
bigcode/the-stack
train
cc2394bc73f28b5baba70d31
train
class
class Regrtest: """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainl...
class Regrtest:
"""Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to sp...
S, NOTTESTS, PASSED, FAILED, ENV_CHANGED, SKIPPED, RESOURCE_DENIED, INTERRUPTED, CHILD_ERROR, PROGRESS_MIN_TIME, format_test_result) from test.libregrtest.setup import setup_tests from test import support try: import gc except ImportError: gc = None # When tests are run from the Python build directory...
256
256
3,369
5
251
KinkowanWinter/Transcendental-Number-Utilization
Lib/test/libregrtest/main.py
Python
Regrtest
Regrtest
47
492
47
47
58377e3a45e92246b8adb33921844c32578aaff4
bigcode/the-stack
train
196b96661ec8b8a522deb4f8
train
function
def main(tests=None, **kwargs): """Run the Python suite.""" Regrtest().main(tests=tests, **kwargs)
def main(tests=None, **kwargs):
"""Run the Python suite.""" Regrtest().main(tests=tests, **kwargs)
# Print the sorted list: 'x' may be a '--random' list or a set() print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width, initial_indent=blanks, subsequent_indent=blanks)) def main(tests=None, **kwargs):
64
64
30
9
55
KinkowanWinter/Transcendental-Number-Utilization
Lib/test/libregrtest/main.py
Python
main
main
525
527
525
525
009cd691d53c94e33f858ef154723d4e44909a67
bigcode/the-stack
train
4c9025da260f5bdd5b9c0719
train
function
def printlist(x, width=70, indent=4): """Print the elements of iterable x to stdout. Optional arg width (default 70) is the maximum line length. Optional arg indent (default 4) is the number of blanks with which to begin each line. """ blanks = ' ' * indent # Print the sorted list: 'x' may...
def printlist(x, width=70, indent=4):
"""Print the elements of iterable x to stdout. Optional arg width (default 70) is the maximum line length. Optional arg indent (default 4) is the number of blanks with which to begin each line. """ blanks = ' ' * indent # Print the sorted list: 'x' may be a '--random' list or a set() p...
py': names[idx] = basename def count(n, word): if n == 1: return "%d %s" % (n, word) else: return "%d %ss" % (n, word) def printlist(x, width=70, indent=4):
64
64
126
13
51
KinkowanWinter/Transcendental-Number-Utilization
Lib/test/libregrtest/main.py
Python
printlist
printlist
511
522
511
511
254a080b90d9b43a4988645c28d8aacb6c3debfa
bigcode/the-stack
train
3c07ce2e86dd2293e7ba8348
train
function
def format_duration(seconds): if seconds < 1.0: return '%.0f ms' % (seconds * 1e3) if seconds < 60.0: return '%.0f sec' % seconds minutes, seconds = divmod(seconds, 60.0) return '%.0f min %.0f sec' % (minutes, seconds)
def format_duration(seconds):
if seconds < 1.0: return '%.0f ms' % (seconds * 1e3) if seconds < 60.0: return '%.0f sec' % seconds minutes, seconds = divmod(seconds, 60.0) return '%.0f min %.0f sec' % (minutes, seconds)
the "make distclean" command. if sysconfig.is_python_build(): TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build') else: TEMPDIR = tempfile.gettempdir() TEMPDIR = os.path.abspath(TEMPDIR) def format_duration(seconds):
64
64
83
5
59
KinkowanWinter/Transcendental-Number-Utilization
Lib/test/libregrtest/main.py
Python
format_duration
format_duration
37
44
37
37
2ac87db59bb29f43e4b0204816ee2e2561a0392a
bigcode/the-stack
train
dc37b01c9683536dc6f0caa3
train
function
def removepy(names): if not names: return for idx, name in enumerate(names): basename, ext = os.path.splitext(name) if ext == '.py': names[idx] = basename
def removepy(names):
if not names: return for idx, name in enumerate(names): basename, ext = os.path.splitext(name) if ext == '.py': names[idx] = basename
self.list_tests() sys.exit(0) self.run_tests() self.display_result() if self.ns.verbose2 and self.bad: self.rerun_failed_tests() self.finalize() sys.exit(len(self.bad) > 0 or self.interrupted) def removepy(names):
64
64
46
5
59
KinkowanWinter/Transcendental-Number-Utilization
Lib/test/libregrtest/main.py
Python
removepy
removepy
495
501
495
495
b6e0e7236f185d6b831b0e5215e7f3f3e5d1541d
bigcode/the-stack
train
311145eb8b86c44b1bb592f4
train
class
class aux_m(nn.Module): def __init__(self, input_dim=20, h_dim_f=100, out_dim=1): super().__init__() # init network self.lin1 = nn.Linear(input_dim, h_dim_f) self.lin2 = nn.Linear(h_dim_f, out_dim) def forward(self, z_in): h1 = F.elu(self.lin1(z_in)) out...
class aux_m(nn.Module):
def __init__(self, input_dim=20, h_dim_f=100, out_dim=1): super().__init__() # init network self.lin1 = nn.Linear(input_dim, h_dim_f) self.lin2 = nn.Linear(h_dim_f, out_dim) def forward(self, z_in): h1 = F.elu(self.lin1(z_in)) out = torch.sigmoid(self.lin...
=int, default=1) parser.add_argument('-evalIter', type=int, default=500) parser.add_argument('-device', type=str, default='cpu') parser.add_argument('-comment', type=str, default='') args = parser.parse_args() # Model class for auxiliary model class aux_m(nn.Module):
64
64
105
6
57
rik-helwegen/FairTrade
social_welfare_experiment/train_aux.py
Python
aux_m
aux_m
28
38
28
28
ead3664a9ad6f31b6c9a8566005028d6e1b9f982
bigcode/the-stack
train
983312fbc7208ddaeb6a1e17
train
function
def compute_accuracy(logits, labels): with tf.name_scope("Accuracy"): correct_pred = tf.equal(tf.argmax(logits, 1), labels) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) tf.summary.scalar("accuracy", accuracy) return accuracy
def compute_accuracy(logits, labels):
with tf.name_scope("Accuracy"): correct_pred = tf.equal(tf.argmax(logits, 1), labels) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) tf.summary.scalar("accuracy", accuracy) return accuracy
# Calculate the total loss for the current tower. total_loss = cross_entropy_mean + weight_decay_loss tf.summary.scalar(name_scope + '_total_loss', tf.reduce_mean(total_loss)) else: total_loss = cross_entropy_mean return total_loss def compute_accuracy(lo...
64
64
60
8
55
accasio/3DPyraNet
train_keras.py
Python
compute_accuracy
compute_accuracy
96
101
96
96
cb976055ebf6de8edf6468f959375fdb494fd3cb
bigcode/the-stack
train
79fbdede1cf77be3c07aed38
train
function
def random_dataset_no_batch(): train_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) train_y = np.random.randint(0, FLAGS.num_classes, size=FLAGS.batch_size) val_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) ...
def random_dataset_no_batch():
train_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) train_y = np.random.randint(0, FLAGS.num_classes, size=FLAGS.batch_size) val_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) val_y = np.random.randint(0, ...
(val_x, val_y, batch_size=FLAGS.batch_size, shuffle=True) test_batch = input_data.generate_batch(val_x, val_y, batch_size=FLAGS.batch_size, shuffle=False) return batch_step, test_batch_step, train_batch, val_batch, test_batch def random_dataset_no_batch():
64
64
145
6
57
accasio/3DPyraNet
train_keras.py
Python
random_dataset_no_batch
random_dataset_no_batch
154
164
154
154
bbd54abe54a97100515bcf434a2d566bc4db8f81
bigcode/the-stack
train
190d59895587becc02ab20d5
train
function
def train(): # if FLAGS.random_run: train_x, train_y, val_x, val_y = random_dataset_no_batch() def exp_decay(epoch): initial_lrate = FLAGS.decay_rate k = 0.1 lrate = initial_lrate * np.exp(-k * epoch) return float(lrate) lrate_decay = tf.keras.callbacks.LearningRateSche...
def train(): # if FLAGS.random_run:
train_x, train_y, val_x, val_y = random_dataset_no_batch() def exp_decay(epoch): initial_lrate = FLAGS.decay_rate k = 0.1 lrate = initial_lrate * np.exp(-k * epoch) return float(lrate) lrate_decay = tf.keras.callbacks.LearningRateScheduler(exp_decay) optimizer = None ...
.random.randint(0, FLAGS.num_classes, size=FLAGS.batch_size) val_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) val_y = np.random.randint(0, FLAGS.num_classes, size=FLAGS.batch_size) if FLAGS.normalize: train_x = input_data.normalize(train_x, name="t...
119
119
398
10
108
accasio/3DPyraNet
train_keras.py
Python
train
train
167
206
167
168
e7860ddad34d1d7a56c12ef545bd7bce941fc31b
bigcode/the-stack
train
8aea06d6d879633095f8f736
train
function
def compute_loss(name_scope, logits, labels): with tf.name_scope("Loss_{}".format(name_scope)): cross_entropy_mean = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) ) tf.summary.scalar( name_scope + '_cross_entropy', ...
def compute_loss(name_scope, logits, labels):
with tf.name_scope("Loss_{}".format(name_scope)): cross_entropy_mean = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) ) tf.summary.scalar( name_scope + '_cross_entropy', cross_entropy_mean ) w...
flags.FLAGS FLAGS(sys.argv) print("Parameters:") for attr, value in sorted(FLAGS.__flags.items()): params_str += "{} = {}\n".format(attr.upper(), value) print("{} = {}".format(attr.upper(), value.value)) print("") def compute_loss(name_scope, logits, labels):
63
64
172
10
53
accasio/3DPyraNet
train_keras.py
Python
compute_loss
compute_loss
71
93
71
71
57ec3670bcf5928ecee0f1c0939d897372924e7b
bigcode/the-stack
train
69076394e06923b042f746fe
train
function
def main(_): train()
def main(_):
train()
max')) model.summary() model.compile(loss='sparse_categorical_crossentropy', optimizer=optimizer, metrics=['sparse_categorical_accuracy']) model.fit(train_x, train_y, batch_size=FLAGS.batch_size, epochs=FLAGS.max_steps, callbacks=[lrate_decay]) def main(_):
64
64
7
4
60
accasio/3DPyraNet
train_keras.py
Python
main
main
209
210
209
209
591f09bf3028f6840fc99ea17498b97b95a592c1
bigcode/the-stack
train
134beb536edcb86019134fce
train
function
def prepare_dataset(): train_x, train_y, val_x, val_y = input_data.read_dataset( FLAGS.train_path, FLAGS.train_labels_path, FLAGS.val_path, FLAGS.val_labels_path ) batch_step = train_x.shape[0] // FLAGS.batch_size test_batch_step = val_x.shape[0] // FLAGS.batch_size ...
def prepare_dataset():
train_x, train_y, val_x, val_y = input_data.read_dataset( FLAGS.train_path, FLAGS.train_labels_path, FLAGS.val_path, FLAGS.val_labels_path ) batch_step = train_x.shape[0] // FLAGS.batch_size test_batch_step = val_x.shape[0] // FLAGS.batch_size FLAGS.decay_steps *= b...
return total_loss def compute_accuracy(logits, labels): with tf.name_scope("Accuracy"): correct_pred = tf.equal(tf.argmax(logits, 1), labels) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) tf.summary.scalar("accuracy", accuracy) return accuracy def prepare_dat...
69
69
233
4
64
accasio/3DPyraNet
train_keras.py
Python
prepare_dataset
prepare_dataset
104
127
104
104
c90d2d71da64ed9bb4d74936078476753a9371b8
bigcode/the-stack
train
e7fa228d2497465002f15e9a
train
function
def random_dataset(): train_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) train_y = np.random.randint(0, FLAGS.num_classes, size=FLAGS.batch_size) val_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) val_y =...
def random_dataset():
train_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) train_y = np.random.randint(0, FLAGS.num_classes, size=FLAGS.batch_size) val_x = np.random.rand(FLAGS.batch_size, FLAGS.depth, FLAGS.height, FLAGS.width, FLAGS.in_channels) val_y = np.random.randint(0, ...
, train_y, batch_size=FLAGS.batch_size, shuffle=True) val_batch = input_data.generate_batch(val_x, val_y, batch_size=FLAGS.batch_size, shuffle=True) test_batch = input_data.generate_batch(val_x, val_y, batch_size=FLAGS.batch_size, shuffle=False) return batch_step, test_batch_step, train_batch, val_batch, t...
84
84
281
4
79
accasio/3DPyraNet
train_keras.py
Python
random_dataset
random_dataset
130
151
130
130
58bf78c278bf80f0b094640a6c1a6fe6de2f4e72
bigcode/the-stack
train
46a8d45ba60e3ada203f3595
train
class
class HWOFA(OFA): def __init__(self, model, run_config=None, distill_config=None, elastic_order=None, train_full=False, candidate_config=None, backbone='resnet34' ): super(...
class HWOFA(OFA):
def __init__(self, model, run_config=None, distill_config=None, elastic_order=None, train_full=False, candidate_config=None, backbone='resnet34' ): super().__init__(model, ...
import random import logging import numpy as np from collections import OrderedDict from paddle import DataParallel from .ofa import OFA from .layers_base import BaseBlock from ...core import GraphWrapper, dygraph2program from .get_sub_model import get_prune_params_config, prune_params, check_search_space from ...c...
94
256
1,544
7
87
xiteng01/CVPR_2022_Track1_demo
paddleslim/nas/ofa/hwofa.py
Python
HWOFA
HWOFA
19
162
19
19
4a1ff31a125660187738820497da76bdaa457b2d
bigcode/the-stack
train
cedad27ae26dd0efec23d571
train
function
def fleiss_kappa(entities, num_annotators, master, na=False): _entities = entities if (na) & ("NA" not in _entities): _entities.extend(["NA"]) #Not Annotated Class #Calculate P_c per entity P_c_values = [] for entity in _entities: #Get Sum of Entity Values (Column) _sum ...
def fleiss_kappa(entities, num_annotators, master, na=False):
_entities = entities if (na) & ("NA" not in _entities): _entities.extend(["NA"]) #Not Annotated Class #Calculate P_c per entity P_c_values = [] for entity in _entities: #Get Sum of Entity Values (Column) _sum = sum(master[entity]) #Get Number of Entries ...
#COPYRIGHT Justin A. Gould #Required Packages import pandas as pd #Fleiss's Kappa def fleiss_kappa(entities, num_annotators, master, na=False):
43
101
338
18
24
gouldju1/annotator_agreement
equinox/score.py
Python
fleiss_kappa
fleiss_kappa
7
48
7
7
e5eda26c7aca69a2419af3374950925c5ccb8d0c
bigcode/the-stack
train
67c2a9ac6efa3476711a9573
train
class
class TestWhenVerifyingATokenForPublishingToAChannelAlias: token = None @pytest.fixture(autouse=True) def before_each(self): self.token = TokenBuilder() \ .with_application_id('my-application-id') \ .with_secret('my-secret') \ .expires_at(datetime.utcfromtimestam...
class TestWhenVerifyingATokenForPublishingToAChannelAlias:
token = None @pytest.fixture(autouse=True) def before_each(self): self.token = TokenBuilder() \ .with_application_id('my-application-id') \ .with_secret('my-secret') \ .expires_at(datetime.utcfromtimestamp(1.0).replace(tzinfo=pytz.UTC)) \ .for_channel...
import pytest from datetime import datetime import pytz from edgeauth.digest_tokens import DigestTokens from edgeauth.token_builder import TokenBuilder class TestWhenVerifyingATokenForPublishingToAChannelAlias:
44
143
479
14
29
ian-ross/EdgeAuth
python/tests/test_when_verifying_a_token_for_publishing_to_a_channel_alias.py
Python
TestWhenVerifyingATokenForPublishingToAChannelAlias
TestWhenVerifyingATokenForPublishingToAChannelAlias
9
44
9
9
421a34ecd6b72d00cb850cc7f9d04154edaf7e56
bigcode/the-stack
train
f8d3bb847cc1839254442723
train
class
class HcotownHallsSolveRefCountryFamilyChildCommunityWoman(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule cotownHallsSolveRefCountryFamilyChildCommunityWoman. """ # Flag this instance as compiled now self.is_compiled = Tr...
class HcotownHallsSolveRefCountryFamilyChildCommunityWoman(Himesis):
def __init__(self): """ Creates the himesis graph representing the DSLTrans rule cotownHallsSolveRefCountryFamilyChildCommunityWoman. """ # Flag this instance as compiled now self.is_compiled = True super(HcotownHallsSolveRefCountryFamilyChildCommu...
from core.himesis import Himesis import uuid class HcotownHallsSolveRefCountryFamilyChildCommunityWoman(Himesis):
30
256
1,212
17
12
levilucio/SyVOLT
eclipse_integration/examples/ExFamToPerson/transformation/HcotownHallsSolveRefCountryFamilyChildCommunityWoman.py
Python
HcotownHallsSolveRefCountryFamilyChildCommunityWoman
HcotownHallsSolveRefCountryFamilyChildCommunityWoman
4
136
4
4
ca491feffdf3e1dd57ecf93e5a70977ab59026e4
bigcode/the-stack
train
21e4ade38bdea7e57feeb043
train
function
def cross_entropy(predicts: Tensor, targets: Tensor) -> Tensor: def softmax(tensor: Tensor): # Stable softmax without grad compute def _stable_softmax(x: np.ndarray) -> np.ndarray: x = x - np.max(x) _sum = np.sum(np.exp(x)) return np.exp(x) / _sum data = [...
def cross_entropy(predicts: Tensor, targets: Tensor) -> Tensor:
def softmax(tensor: Tensor): # Stable softmax without grad compute def _stable_softmax(x: np.ndarray) -> np.ndarray: x = x - np.max(x) _sum = np.sum(np.exp(x)) return np.exp(x) / _sum data = [] for x in tensor: data.append(_stable_softm...
()/tmp result = ((predicts - targets)**2) .sum()/tmp # return result data = result.data requires_grad = result.requires_grad if requires_grad: depends_on = result.depends_on else: depends_on = [] return Tensor(data, requires_grad, depends_on) def cross_entropy(predicts: Tens...
87
87
291
16
71
EequalsMCsquare/mlearn
mlearn/functional/loss_func.py
Python
cross_entropy
cross_entropy
33
63
33
33
0dd1e74335be0df58ed535a9822f458bf1b06150
bigcode/the-stack
train
fc36a5b92b5724d1ac8afa72
train
function
def mse(predicts: Tensor, targets: Tensor) -> Tensor: assert (predicts.shape == targets.shape), f"[形状不匹配], 预测->{predicts.shape}但是目标却是{targets.shape}" tmp = 1 for x in predicts.shape: tmp *= x # result = [data**2 for data in (predicts - targets)]#.sum()/tmp result = ((predicts - t...
def mse(predicts: Tensor, targets: Tensor) -> Tensor:
assert (predicts.shape == targets.shape), f"[形状不匹配], 预测->{predicts.shape}但是目标却是{targets.shape}" tmp = 1 for x in predicts.shape: tmp *= x # result = [data**2 for data in (predicts - targets)]#.sum()/tmp result = ((predicts - targets)**2) .sum()/tmp # return result data =...
from ..autograd.tensor import Tensor, Dependency, ensure_tensor from .activation import softmax as _softmax import numpy as np """ ################### Loss Function ######################### """ def mse(predicts: Tensor, targets: Tensor) -> Tensor:
53
64
157
15
38
EequalsMCsquare/mlearn
mlearn/functional/loss_func.py
Python
mse
mse
13
29
13
13
5ec58d5a07adea78456288a8b72215c751c9f8e0
bigcode/the-stack
train
d6b3ae4573c1163f4ee58ec0
train
class
class CdrFileFormatError(Error): """Exception raised if the CDR file provided is not the proper format.""" def __init__(self, cdr_file): Error.__init__(self, '%r does not appear to be a CSV file.' % (cdr_file, )) self.cdr_file = cdr_file self.args = (cdr_file, )
class CdrFileFormatError(Error):
"""Exception raised if the CDR file provided is not the proper format.""" def __init__(self, cdr_file): Error.__init__(self, '%r does not appear to be a CSV file.' % (cdr_file, )) self.cdr_file = cdr_file self.args = (cdr_file, )
be located on the system.""" def __init__(self, cdr_file): Error.__init__(self, 'File not found: %r' % (cdr_file, )) self.cdr_file = cdr_file self.args = (cdr_file, ) class CdrFileFormatError(Error):
64
64
77
8
56
kromulas/python-sansay-cdr-parser
sansaycdrparser.py
Python
CdrFileFormatError
CdrFileFormatError
45
50
45
45
94af8780c4b9425cafad45ddc2f1737133c1a8f7
bigcode/the-stack
train
b0e2053711c7c1c9cdfa7b6e
train
class
class CdrFileError(Error): """Exception raised if the CDR file cannot be located on the system.""" def __init__(self, cdr_file): Error.__init__(self, 'File not found: %r' % (cdr_file, )) self.cdr_file = cdr_file self.args = (cdr_file, )
class CdrFileError(Error):
"""Exception raised if the CDR file cannot be located on the system.""" def __init__(self, cdr_file): Error.__init__(self, 'File not found: %r' % (cdr_file, )) self.cdr_file = cdr_file self.args = (cdr_file, )
ivars: msg -- contains the message """ def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) def __repr__(self): return self.message __str__ = __repr__ class CdrFileError(Error):
64
64
73
7
57
kromulas/python-sansay-cdr-parser
sansaycdrparser.py
Python
CdrFileError
CdrFileError
38
43
38
38
57ca82e59cf17c69667a02e2ecf863bca98ccf4d
bigcode/the-stack
train
c2f0b92ceaaf059bec3b6eda
train
class
class Error(Exception): """Exception class for this module. Use: except xdrlib.Error, var: # var has the Error instance for the exception Public ivars: msg -- contains the message """ def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) ...
class Error(Exception):
"""Exception class for this module. Use: except xdrlib.Error, var: # var has the Error instance for the exception Public ivars: msg -- contains the message """ def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) def __repr__(self): ...
is the default passed at this time. Earlier versions and newly released versions will be updated as needed. """ import datetime, csv from os.path import isfile from uuid import uuid4 __version__ = "$Rev: 0.0.2 $" # exception classes class Error(Exception):
64
64
93
4
59
kromulas/python-sansay-cdr-parser
sansaycdrparser.py
Python
Error
Error
19
36
19
19
4e4a21f32a6421a505b79473cd1bad098a72fb99
bigcode/the-stack
train
5c47ba501b43889d5011ee78
train
function
def ParseFile(cdr_file, ver = "1.18"): if not isfile(cdr_file): raise CdrFileError(cdr_file) with open(cdr_file, 'rt') as f: try: dialect = csv.Sniffer().sniff(f.readline(), delimiters=';') f.seek(0) except csv.Error: raise CdrFileFormatError(cdr_file) records = list(csv.reader(f, dialect)) """...
def ParseFile(cdr_file, ver = "1.18"):
if not isfile(cdr_file): raise CdrFileError(cdr_file) with open(cdr_file, 'rt') as f: try: dialect = csv.Sniffer().sniff(f.readline(), delimiters=';') f.seek(0) except csv.Error: raise CdrFileFormatError(cdr_file) records = list(csv.reader(f, dialect)) """CDR version control to support differen...
self.cdr_file = cdr_file self.args = (cdr_file, ) class CdrFileFormatError(Error): """Exception raised if the CDR file provided is not the proper format.""" def __init__(self, cdr_file): Error.__init__(self, '%r does not appear to be a CSV file.' % (cdr_file, )) self.cdr_file = cdr_file self.args = (cdr_fi...
110
110
369
14
96
kromulas/python-sansay-cdr-parser
sansaycdrparser.py
Python
ParseFile
ParseFile
53
84
53
53
1e4cdeb060840d72cf597c15f65d1d75d0f692f5
bigcode/the-stack
train
eccf9589ab8b4caa7386f81c
train
class
class XiaomiSmokeSensor(XiaomiBinarySensor): """Representation of a XiaomiSmokeSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiSmokeSensor.""" self._density = 0 XiaomiBinarySensor.__init__(self, device, 'Smoke Sensor', xiaomi_hub, ...
class XiaomiSmokeSensor(XiaomiBinarySensor):
"""Representation of a XiaomiSmokeSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiSmokeSensor.""" self._density = 0 XiaomiBinarySensor.__init__(self, device, 'Smoke Sensor', xiaomi_hub, 'alarm', 'smoke') @property d...
leak': self._should_poll = True if self._state: return False self._state = True return True if value == 'no_leak': if self._state: self._state = False return True return False class XiaomiSmok...
71
71
238
9
61
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiSmokeSensor
XiaomiSmokeSensor
306
339
306
306
2a11c3821771f494158198abc6dda07bfb903c08
bigcode/the-stack
train
f8b3992d5f7290466bfaa700
train
function
def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Xiaomi devices.""" devices = [] for (_, gateway) in hass.data[PY_XIAOMI_GATEWAY].gateways.items(): for device in gateway.devices['binary_sensor']: model = device['model'] if model in...
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Perform the setup for Xiaomi devices.""" devices = [] for (_, gateway) in hass.data[PY_XIAOMI_GATEWAY].gateways.items(): for device in gateway.devices['binary_sensor']: model = device['model'] if model in ['motion', 'sensor_motion', 'sensor_motion.aq2']: de...
"""Support for Xiaomi aqara binary sensors.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.xiaomi_aqara import (PY_XIAOMI_GATEWAY, XiaomiDevice) from homeassistant.core import callback from homeass...
155
195
653
15
140
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
setup_platform
setup_platform
24
79
24
24
4ea8b1489ffa49fb9e6a5d7cdf08ce415f9ecb60
bigcode/the-stack
train
76368b4b5fefcc8ff687591a
train
class
class XiaomiMotionSensor(XiaomiBinarySensor): """Representation of a XiaomiMotionSensor.""" def __init__(self, device, hass, xiaomi_hub): """Initialize the XiaomiMotionSensor.""" self._hass = hass self._no_motion_since = 0 self._unsub_set_no_motion = None if 'proto' not ...
class XiaomiMotionSensor(XiaomiBinarySensor):
"""Representation of a XiaomiMotionSensor.""" def __init__(self, device, hass, xiaomi_hub): """Initialize the XiaomiMotionSensor.""" self._hass = hass self._no_motion_since = 0 self._unsub_set_no_motion = None if 'proto' not in device or int(device['proto'][0:1]) == 1: ...
') @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_DENSITY: self._density} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" if DEN...
172
172
574
9
162
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiMotionSensor
XiaomiMotionSensor
151
225
151
151
cdad093b27b03291aaeb4b5b57d222fb80a44bf0
bigcode/the-stack
train
73eee53c20d90eecd789d137
train
class
class XiaomiDoorSensor(XiaomiBinarySensor): """Representation of a XiaomiDoorSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiDoorSensor.""" self._open_since = 0 if 'proto' not in device or int(device['proto'][0:1]) == 1: data_key = 'status' ...
class XiaomiDoorSensor(XiaomiBinarySensor):
"""Representation of a XiaomiDoorSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiDoorSensor.""" self._open_since = 0 if 'proto' not in device or int(device['proto'][0:1]) == 1: data_key = 'status' else: data_key = 'window_status...
ass.bus.fire('xiaomi_aqara.motion', { 'entity_id': self.entity_id }) self._no_motion_since = 0 if self._state: return False self._state = True return True if value == NO_MOTION: if not self._...
93
93
313
9
83
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiDoorSensor
XiaomiDoorSensor
228
270
228
228
ac7d12feba0703069b190513269e6d715eb01fca
bigcode/the-stack
train
2d9c3d14c00e6d67dca1fe32
train
class
class XiaomiWaterLeakSensor(XiaomiBinarySensor): """Representation of a XiaomiWaterLeakSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiWaterLeakSensor.""" if 'proto' not in device or int(device['proto'][0:1]) == 1: data_key = 'status' else: ...
class XiaomiWaterLeakSensor(XiaomiBinarySensor):
"""Representation of a XiaomiWaterLeakSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiWaterLeakSensor.""" if 'proto' not in device or int(device['proto'][0:1]) == 1: data_key = 'status' else: data_key = 'wleak_status' XiaomiBina...
if self._state: return False self._state = True return True if value == 'close': self._open_since = 0 if self._state: self._state = False return True return False class XiaomiWaterLeakSensor(X...
68
68
229
10
57
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiWaterLeakSensor
XiaomiWaterLeakSensor
273
303
273
273
26ed8058875124a3abdc0c5f8f42731c4141140d
bigcode/the-stack
train
f8ac9c7411f42c27ecf2c275
train
class
class XiaomiButton(XiaomiBinarySensor): """Representation of a Xiaomi Button.""" def __init__(self, device, name, data_key, hass, xiaomi_hub): """Initialize the XiaomiButton.""" self._hass = hass self._last_action = None XiaomiBinarySensor.__init__(self, device, name, xiaomi_hub...
class XiaomiButton(XiaomiBinarySensor):
"""Representation of a Xiaomi Button.""" def __init__(self, device, name, data_key, hass, xiaomi_hub): """Initialize the XiaomiButton.""" self._hass = hass self._last_action = None XiaomiBinarySensor.__init__(self, device, name, xiaomi_hub, da...
Parse data sent by gateway.""" value = data.get(self._data_key) if value is None: return False if value not in ('vibrate', 'tilt', 'free_fall'): _LOGGER.warning("Unsupported movement_type detected: %s", value) return False ...
118
118
396
8
109
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiButton
XiaomiButton
377
430
377
377
4c436d298744d8f487ce2ea7baa8b934eece175c
bigcode/the-stack
train
9758db26f51f8147614a2da8
train
class
class XiaomiCube(XiaomiBinarySensor): """Representation of a Xiaomi Cube.""" def __init__(self, device, hass, xiaomi_hub): """Initialize the Xiaomi Cube.""" self._hass = hass self._last_action = None self._state = False if 'proto' not in device or int(device['proto'][0:1...
class XiaomiCube(XiaomiBinarySensor):
"""Representation of a Xiaomi Cube.""" def __init__(self, device, hass, xiaomi_hub): """Initialize the Xiaomi Cube.""" self._hass = hass self._last_action = None self._state = False if 'proto' not in device or int(device['proto'][0:1]) == 1: data_key = 'statu...
_type = 'shake' elif value == 'long_click': click_type = 'long' elif value == 'long_both_click': click_type = 'long_both' else: _LOGGER.warning("Unsupported click_type detected: %s", value) return False self._hass.bus.fire('xiaomi_aqara.cl...
117
117
393
8
108
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiCube
XiaomiCube
433
480
433
433
5b759aaa6f05058c78a9c74742bd5bac8e69eb99
bigcode/the-stack
train
f3e607e584fadb9b8c30349e
train
class
class XiaomiBinarySensor(XiaomiDevice, BinarySensorDevice): """Representation of a base XiaomiBinarySensor.""" def __init__(self, device, name, xiaomi_hub, data_key, device_class): """Initialize the XiaomiSmokeSensor.""" self._data_key = data_key self._device_class = device_class ...
class XiaomiBinarySensor(XiaomiDevice, BinarySensorDevice):
"""Representation of a base XiaomiBinarySensor.""" def __init__(self, device, name, xiaomi_hub, data_key, device_class): """Initialize the XiaomiSmokeSensor.""" self._data_key = data_key self._device_class = device_class self._should_poll = False self._density = 0 ...
in ['vibration', 'vibration.aq1']: devices.append(XiaomiVibration(device, 'Vibration', 'status', gateway)) else: _LOGGER.warning('Unmapped Device Model %s', model) add_entities(devices) class XiaomiBinarySensor(XiaomiDevice...
66
66
220
12
54
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiBinarySensor
XiaomiBinarySensor
82
111
82
82
82e8e23623744ed2d1cae670870f74e3a0a1ff59
bigcode/the-stack
train
a6218be09593591c0a6bb294
train
class
class XiaomiVibration(XiaomiBinarySensor): """Representation of a Xiaomi Vibration Sensor.""" def __init__(self, device, name, data_key, xiaomi_hub): """Initialize the XiaomiVibration.""" self._last_action = None super().__init__(device, name, xiaomi_hub, data_key, None) @property ...
class XiaomiVibration(XiaomiBinarySensor):
"""Representation of a Xiaomi Vibration Sensor.""" def __init__(self, device, name, data_key, xiaomi_hub): """Initialize the XiaomiVibration.""" self._last_action = None super().__init__(device, name, xiaomi_hub, data_key, None) @property def device_state_attributes(self): ...
return False if value in ('1', '2'): if self._state: return False self._state = True return True if value == '0': if self._state: self._state = False return True return False class Xi...
72
72
240
9
62
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiVibration
XiaomiVibration
342
374
342
342
051b136061fd0ecfe2fc1b8d080fa34fa75741cd
bigcode/the-stack
train
8b840438c782630258631660
train
class
class XiaomiNatgasSensor(XiaomiBinarySensor): """Representation of a XiaomiNatgasSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiSmokeSensor.""" self._density = None XiaomiBinarySensor.__init__(self, device, 'Natgas Sensor', xiaomi_hub, ...
class XiaomiNatgasSensor(XiaomiBinarySensor):
"""Representation of a XiaomiNatgasSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiSmokeSensor.""" self._density = None XiaomiBinarySensor.__init__(self, device, 'Natgas Sensor', xiaomi_hub, 'alarm', 'gas') @property ...
@property def device_class(self): """Return the class of binary sensor.""" return self._device_class def update(self): """Update the sensor state.""" _LOGGER.debug('Updating xiaomi sensor by polling') self._get_from_hub(self._sid) class XiaomiNatgasSensor(XiaomiBinar...
71
71
239
10
61
dannyqwertz/home-assistant
homeassistant/components/binary_sensor/xiaomi_aqara.py
Python
XiaomiNatgasSensor
XiaomiNatgasSensor
114
148
114
114
715609421deeecb83ad82d90be27248b69d5bada
bigcode/the-stack
train
52f3c5a0dbeefa22d5831b16
train
class
class PicklableKerasModel(tf.keras.Model): def __getstate__(self): with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=True) as fd: tf.keras.models.save_model(self, fd.name, overwrite=True) model_str = fd.read() d = {"model_str": model_str} return d def __se...
class PicklableKerasModel(tf.keras.Model):
def __getstate__(self): with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=True) as fd: tf.keras.models.save_model(self, fd.name, overwrite=True) model_str = fd.read() d = {"model_str": model_str} return d def __setstate__(self, state): with tempfil...
# Created by yingwen at 2019-03-10 import tempfile import tensorflow as tf class PicklableKerasModel(tf.keras.Model):
33
71
238
11
21
wwxFromTju/malib
malib/utils/keras.py
Python
PicklableKerasModel
PicklableKerasModel
7
34
7
7
92dc20232f8f6fd335eae55a11e46096359f2d8b
bigcode/the-stack
train